LCOV - code coverage report
Current view: top level - frmts/pdf - pdfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1876 2917 64.3 %
Date: 2026-02-15 01:53:53 Functions: 88 98 89.8 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  PDF driver
       4             :  * Purpose:  GDALDataset driver for PDF dataset.
       5             :  * Author:   Even Rouault, <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  *
       9             :  * Support for open-source PDFium library
      10             :  *
      11             :  * Copyright (C) 2015 Klokan Technologies GmbH (http://www.klokantech.com/)
      12             :  * Author: Martin Mikita <martin.mikita@klokantech.com>, xmikit00 @ FIT VUT Brno
      13             :  *
      14             :  ******************************************************************************
      15             :  * Copyright (c) 2010-2014, Even Rouault <even dot rouault at spatialys.com>
      16             :  *
      17             :  * SPDX-License-Identifier: MIT
      18             :  ****************************************************************************/
      19             : 
      20             : #include "gdal_pdf.h"
      21             : 
      22             : #include "cpl_json_streaming_writer.h"
      23             : #include "cpl_vsi_virtual.h"
      24             : #include "cpl_spawn.h"
      25             : #include "cpl_string.h"
      26             : #include "gdal_frmts.h"
      27             : #include "gdalalgorithm.h"
      28             : #include "ogr_spatialref.h"
      29             : #include "ogr_geometry.h"
      30             : 
      31             : #ifdef HAVE_POPPLER
      32             : #include "cpl_multiproc.h"
      33             : #include "pdfio.h"
      34             : #endif  // HAVE_POPPLER
      35             : 
      36             : #include "pdfcreatecopy.h"
      37             : 
      38             : #include "pdfdrivercore.h"
      39             : 
      40             : #include <algorithm>
      41             : #include <array>
      42             : #include <cassert>
      43             : #include <cmath>
      44             : #include <limits>
      45             : #include <set>
      46             : 
      47             : #ifdef HAVE_PDFIUM
      48             : // To be able to use
      49             : // https://github.com/rouault/pdfium_build_gdal_3_5/releases/download/v1_pdfium_5106/install-win10-vs2019-x64-rev5106.zip
      50             : // with newer Visual Studio versions.
      51             : // Trick from https://github.com/conan-io/conan-center-index/issues/4826
      52             : #if _MSC_VER >= 1932  // Visual Studio 2022 version 17.2+
      53             : #pragma comment(                                                               \
      54             :     linker,                                                                    \
      55             :     "/alternatename:__imp___std_init_once_complete=__imp_InitOnceComplete")
      56             : #pragma comment(                                                               \
      57             :     linker,                                                                    \
      58             :     "/alternatename:__imp___std_init_once_begin_initialize=__imp_InitOnceBeginInitialize")
      59             : #endif
      60             : #endif
      61             : 
      62             : /* g++ -fPIC -g -Wall frmts/pdf/pdfdataset.cpp -shared -o gdal_PDF.so -Iport
      63             :  * -Igcore -Iogr -L. -lgdal -lpoppler -I/usr/include/poppler */
      64             : 
      65             : #ifdef HAVE_PDF_READ_SUPPORT
      66             : 
      67             : static double Get(GDALPDFObject *poObj, int nIndice = -1);
      68             : 
      69             : #ifdef HAVE_POPPLER
      70             : 
      71             : static CPLMutex *hGlobalParamsMutex = nullptr;
      72             : 
      73             : /************************************************************************/
      74             : /*                           GDALPDFOutputDev                           */
      75             : /************************************************************************/
      76             : 
      77             : class GDALPDFOutputDev final : public SplashOutputDev
      78             : {
      79             :   private:
      80             :     int bEnableVector;
      81             :     int bEnableText;
      82             :     int bEnableBitmap;
      83             : 
      84           0 :     void skipBytes(Stream *str, int width, int height, int nComps, int nBits)
      85             :     {
      86           0 :         int nVals = width * nComps;
      87           0 :         int nLineSize = (nVals * nBits + 7) >> 3;
      88           0 :         int nBytes = nLineSize * height;
      89           0 :         for (int i = 0; i < nBytes; i++)
      90             :         {
      91           0 :             if (str->getChar() == EOF)
      92           0 :                 break;
      93             :         }
      94           0 :     }
      95             : 
      96             :   public:
      97          56 :     GDALPDFOutputDev(SplashColorMode colorModeA, int bitmapRowPadA,
      98             :                      [[maybe_unused]] bool reverseVideoA,
      99             :                      SplashColorPtr paperColorA)
     100          56 :         : SplashOutputDev(colorModeA, bitmapRowPadA,
     101             : #if POPPLER_MAJOR_VERSION < 26 ||                                              \
     102             :     (POPPLER_MAJOR_VERSION == 26 && POPPLER_MINOR_VERSION < 2)
     103             :                           reverseVideoA,
     104             : #endif
     105             :                           paperColorA),
     106          56 :           bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE)
     107             :     {
     108          56 :     }
     109             : 
     110          11 :     void SetEnableVector(int bFlag)
     111             :     {
     112          11 :         bEnableVector = bFlag;
     113          11 :     }
     114             : 
     115          11 :     void SetEnableText(int bFlag)
     116             :     {
     117          11 :         bEnableText = bFlag;
     118          11 :     }
     119             : 
     120          11 :     void SetEnableBitmap(int bFlag)
     121             :     {
     122          11 :         bEnableBitmap = bFlag;
     123          11 :     }
     124             : 
     125             :     void startPage(int pageNum, GfxState *state, XRef *xrefIn) override;
     126             : 
     127        1673 :     void stroke(GfxState *state) override
     128             :     {
     129        1673 :         if (bEnableVector)
     130        1664 :             SplashOutputDev::stroke(state);
     131        1673 :     }
     132             : 
     133           8 :     void fill(GfxState *state) override
     134             :     {
     135           8 :         if (bEnableVector)
     136           8 :             SplashOutputDev::fill(state);
     137           8 :     }
     138             : 
     139          38 :     void eoFill(GfxState *state) override
     140             :     {
     141          38 :         if (bEnableVector)
     142          32 :             SplashOutputDev::eoFill(state);
     143          38 :     }
     144             : 
     145        4295 :     virtual void drawChar(GfxState *state, double x, double y, double dx,
     146             :                           double dy, double originX, double originY,
     147             :                           CharCode code, int nBytes, const Unicode *u,
     148             :                           int uLen) override
     149             :     {
     150        4295 :         if (bEnableText)
     151        4259 :             SplashOutputDev::drawChar(state, x, y, dx, dy, originX, originY,
     152             :                                       code, nBytes, u, uLen);
     153        4295 :     }
     154             : 
     155         681 :     void beginTextObject(GfxState *state) override
     156             :     {
     157         681 :         if (bEnableText)
     158         678 :             SplashOutputDev::beginTextObject(state);
     159         681 :     }
     160             : 
     161         681 :     void endTextObject(GfxState *state) override
     162             :     {
     163         681 :         if (bEnableText)
     164         678 :             SplashOutputDev::endTextObject(state);
     165         681 :     }
     166             : 
     167           0 :     virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
     168             :                                int width, int height, bool invert,
     169             :                                bool interpolate, bool inlineImg) override
     170             :     {
     171           0 :         if (bEnableBitmap)
     172           0 :             SplashOutputDev::drawImageMask(state, ref, str, width, height,
     173             :                                            invert, interpolate, inlineImg);
     174             :         else
     175             :         {
     176           0 :             VSIPDFFileStream::resetNoCheckReturnValue(str);
     177           0 :             if (inlineImg)
     178             :             {
     179           0 :                 skipBytes(str, width, height, 1, 1);
     180             :             }
     181           0 :             str->close();
     182             :         }
     183           0 :     }
     184             : 
     185             : #if POPPLER_MAJOR_VERSION > 26 ||                                              \
     186             :     (POPPLER_MAJOR_VERSION == 26 && POPPLER_MINOR_VERSION >= 2)
     187             :     void setSoftMaskFromImageMask(GfxState *state, Object *ref, Stream *str,
     188             :                                   int width, int height, bool invert,
     189             :                                   bool inlineImg,
     190             :                                   std::array<double, 6> &baseMatrix) override
     191             : #else
     192           0 :     void setSoftMaskFromImageMask(GfxState *state, Object *ref, Stream *str,
     193             :                                   int width, int height, bool invert,
     194             :                                   bool inlineImg, double *baseMatrix) override
     195             : #endif
     196             :     {
     197           0 :         if (bEnableBitmap)
     198           0 :             SplashOutputDev::setSoftMaskFromImageMask(
     199             :                 state, ref, str, width, height, invert, inlineImg, baseMatrix);
     200             :         else
     201           0 :             str->close();
     202           0 :     }
     203             : 
     204             : #if POPPLER_MAJOR_VERSION > 26 ||                                              \
     205             :     (POPPLER_MAJOR_VERSION == 26 && POPPLER_MINOR_VERSION >= 2)
     206             :     void unsetSoftMaskFromImageMask(GfxState *state,
     207             :                                     std::array<double, 6> &baseMatrix) override
     208             : #else
     209           0 :     void unsetSoftMaskFromImageMask(GfxState *state,
     210             :                                     double *baseMatrix) override
     211             : #endif
     212             :     {
     213           0 :         if (bEnableBitmap)
     214           0 :             SplashOutputDev::unsetSoftMaskFromImageMask(state, baseMatrix);
     215           0 :     }
     216             : 
     217          43 :     virtual void drawImage(GfxState *state, Object *ref, Stream *str, int width,
     218             :                            int height, GfxImageColorMap *colorMap,
     219             :                            bool interpolate, const int *maskColors,
     220             :                            bool inlineImg) override
     221             :     {
     222          43 :         if (bEnableBitmap)
     223          40 :             SplashOutputDev::drawImage(state, ref, str, width, height, colorMap,
     224             :                                        interpolate, maskColors, inlineImg);
     225             :         else
     226             :         {
     227           3 :             VSIPDFFileStream::resetNoCheckReturnValue(str);
     228           3 :             if (inlineImg)
     229             :             {
     230           0 :                 skipBytes(str, width, height, colorMap->getNumPixelComps(),
     231             :                           colorMap->getBits());
     232             :             }
     233           3 :             str->close();
     234             :         }
     235          43 :     }
     236             : 
     237           0 :     virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
     238             :                                  int width, int height,
     239             :                                  GfxImageColorMap *colorMap, bool interpolate,
     240             :                                  Stream *maskStr, int maskWidth, int maskHeight,
     241             :                                  bool maskInvert, bool maskInterpolate) override
     242             :     {
     243           0 :         if (bEnableBitmap)
     244           0 :             SplashOutputDev::drawMaskedImage(
     245             :                 state, ref, str, width, height, colorMap, interpolate, maskStr,
     246             :                 maskWidth, maskHeight, maskInvert, maskInterpolate);
     247             :         else
     248           0 :             str->close();
     249           0 :     }
     250             : 
     251           2 :     virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
     252             :                                      int width, int height,
     253             :                                      GfxImageColorMap *colorMap,
     254             :                                      bool interpolate, Stream *maskStr,
     255             :                                      int maskWidth, int maskHeight,
     256             :                                      GfxImageColorMap *maskColorMap,
     257             :                                      bool maskInterpolate) override
     258             :     {
     259           2 :         if (bEnableBitmap)
     260             :         {
     261           2 :             if (maskColorMap->getBits() <=
     262             :                 0) /* workaround poppler bug (robustness) */
     263             :             {
     264           0 :                 str->close();
     265           0 :                 return;
     266             :             }
     267           2 :             SplashOutputDev::drawSoftMaskedImage(
     268             :                 state, ref, str, width, height, colorMap, interpolate, maskStr,
     269             :                 maskWidth, maskHeight, maskColorMap, maskInterpolate);
     270             :         }
     271             :         else
     272           0 :             str->close();
     273             :     }
     274             : };
     275             : 
     276          56 : void GDALPDFOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefIn)
     277             : {
     278          56 :     SplashOutputDev::startPage(pageNum, state, xrefIn);
     279          56 :     SplashBitmap *poBitmap = getBitmap();
     280         112 :     memset(poBitmap->getDataPtr(), 255,
     281          56 :            static_cast<size_t>(poBitmap->getRowSize()) * poBitmap->getHeight());
     282          56 : }
     283             : 
     284             : #endif  // ~ HAVE_POPPLER
     285             : 
     286             : /************************************************************************/
     287             : /*                            Dump routines                             */
     288             : /************************************************************************/
     289             : 
     290             : class GDALPDFDumper
     291             : {
     292             :   private:
     293             :     FILE *f = nullptr;
     294             :     const int nDepthLimit;
     295             :     std::set<int> aoSetObjectExplored{};
     296             :     const bool bDumpParent;
     297             : 
     298             :     void DumpSimplified(GDALPDFObject *poObj);
     299             : 
     300             :     CPL_DISALLOW_COPY_ASSIGN(GDALPDFDumper)
     301             : 
     302             :   public:
     303           1 :     GDALPDFDumper(const char *pszFilename, const char *pszDumpFile,
     304             :                   int nDepthLimitIn = -1)
     305           1 :         : nDepthLimit(nDepthLimitIn),
     306           1 :           bDumpParent(CPLGetConfigOption("PDF_DUMP_PARENT", "FALSE"))
     307             :     {
     308           1 :         if (strcmp(pszDumpFile, "stderr") == 0)
     309           0 :             f = stderr;
     310           1 :         else if (EQUAL(pszDumpFile, "YES"))
     311           0 :             f = fopen(CPLSPrintf("dump_%s.txt", CPLGetFilename(pszFilename)),
     312             :                       "wt");
     313             :         else
     314           1 :             f = fopen(pszDumpFile, "wt");
     315           1 :         if (f == nullptr)
     316           0 :             f = stderr;
     317           1 :     }
     318             : 
     319           1 :     ~GDALPDFDumper()
     320           1 :     {
     321           1 :         if (f != stderr)
     322           1 :             fclose(f);
     323           1 :     }
     324             : 
     325             :     void Dump(GDALPDFObject *poObj, int nDepth = 0);
     326             :     void Dump(GDALPDFDictionary *poDict, int nDepth = 0);
     327             :     void Dump(GDALPDFArray *poArray, int nDepth = 0);
     328             : };
     329             : 
     330           3 : void GDALPDFDumper::Dump(GDALPDFArray *poArray, int nDepth)
     331             : {
     332           3 :     if (nDepthLimit >= 0 && nDepth > nDepthLimit)
     333           0 :         return;
     334             : 
     335           3 :     int nLength = poArray->GetLength();
     336             :     int i;
     337           6 :     CPLString osIndent;
     338          14 :     for (i = 0; i < nDepth; i++)
     339          11 :         osIndent += " ";
     340           8 :     for (i = 0; i < nLength; i++)
     341             :     {
     342           5 :         fprintf(f, "%sItem[%d]:", osIndent.c_str(), i);
     343           5 :         GDALPDFObject *poObj = nullptr;
     344           5 :         if ((poObj = poArray->Get(i)) != nullptr)
     345             :         {
     346           5 :             if (poObj->GetType() == PDFObjectType_String ||
     347           5 :                 poObj->GetType() == PDFObjectType_Null ||
     348           5 :                 poObj->GetType() == PDFObjectType_Bool ||
     349           5 :                 poObj->GetType() == PDFObjectType_Int ||
     350          11 :                 poObj->GetType() == PDFObjectType_Real ||
     351           1 :                 poObj->GetType() == PDFObjectType_Name)
     352             :             {
     353           4 :                 fprintf(f, " ");
     354           4 :                 DumpSimplified(poObj);
     355           4 :                 fprintf(f, "\n");
     356             :             }
     357             :             else
     358             :             {
     359           1 :                 fprintf(f, "\n");
     360           1 :                 Dump(poObj, nDepth + 1);
     361             :             }
     362             :         }
     363             :     }
     364             : }
     365             : 
     366         493 : void GDALPDFDumper::DumpSimplified(GDALPDFObject *poObj)
     367             : {
     368         493 :     switch (poObj->GetType())
     369             :     {
     370           0 :         case PDFObjectType_String:
     371           0 :             fprintf(f, "%s (string)", poObj->GetString().c_str());
     372           0 :             break;
     373             : 
     374           0 :         case PDFObjectType_Null:
     375           0 :             fprintf(f, "null");
     376           0 :             break;
     377             : 
     378           0 :         case PDFObjectType_Bool:
     379           0 :             fprintf(f, "%s (bool)", poObj->GetBool() ? "true" : "false");
     380           0 :             break;
     381             : 
     382         247 :         case PDFObjectType_Int:
     383         247 :             fprintf(f, "%d (int)", poObj->GetInt());
     384         247 :             break;
     385             : 
     386           0 :         case PDFObjectType_Real:
     387           0 :             fprintf(f, "%f (real)", poObj->GetReal());
     388           0 :             break;
     389             : 
     390         246 :         case PDFObjectType_Name:
     391         246 :             fprintf(f, "%s (name)", poObj->GetName().c_str());
     392         246 :             break;
     393             : 
     394           0 :         default:
     395           0 :             fprintf(f, "unknown !");
     396           0 :             break;
     397             :     }
     398         493 : }
     399             : 
     400          70 : void GDALPDFDumper::Dump(GDALPDFObject *poObj, int nDepth)
     401             : {
     402          70 :     if (nDepthLimit >= 0 && nDepth > nDepthLimit)
     403           1 :         return;
     404             : 
     405             :     int i;
     406          70 :     CPLString osIndent;
     407         516 :     for (i = 0; i < nDepth; i++)
     408         446 :         osIndent += " ";
     409          70 :     fprintf(f, "%sType = %s", osIndent.c_str(), poObj->GetTypeName());
     410          70 :     int nRefNum = poObj->GetRefNum().toInt();
     411          70 :     if (nRefNum != 0)
     412          66 :         fprintf(f, ", Num = %d, Gen = %d", nRefNum, poObj->GetRefGen());
     413          70 :     fprintf(f, "\n");
     414             : 
     415          70 :     if (nRefNum != 0)
     416             :     {
     417          66 :         if (aoSetObjectExplored.find(nRefNum) != aoSetObjectExplored.end())
     418           1 :             return;
     419          65 :         aoSetObjectExplored.insert(nRefNum);
     420             :     }
     421             : 
     422          69 :     switch (poObj->GetType())
     423             :     {
     424           3 :         case PDFObjectType_Array:
     425           3 :             Dump(poObj->GetArray(), nDepth + 1);
     426           3 :             break;
     427             : 
     428          66 :         case PDFObjectType_Dictionary:
     429          66 :             Dump(poObj->GetDictionary(), nDepth + 1);
     430          66 :             break;
     431             : 
     432           0 :         case PDFObjectType_String:
     433             :         case PDFObjectType_Null:
     434             :         case PDFObjectType_Bool:
     435             :         case PDFObjectType_Int:
     436             :         case PDFObjectType_Real:
     437             :         case PDFObjectType_Name:
     438           0 :             fprintf(f, "%s", osIndent.c_str());
     439           0 :             DumpSimplified(poObj);
     440           0 :             fprintf(f, "\n");
     441           0 :             break;
     442             : 
     443           0 :         default:
     444           0 :             fprintf(f, "%s", osIndent.c_str());
     445           0 :             fprintf(f, "unknown !\n");
     446           0 :             break;
     447             :     }
     448             : 
     449          69 :     GDALPDFStream *poStream = poObj->GetStream();
     450          69 :     if (poStream != nullptr)
     451             :     {
     452          61 :         fprintf(f,
     453             :                 "%sHas stream (" CPL_FRMT_GIB
     454             :                 " uncompressed bytes, " CPL_FRMT_GIB " raw bytes)\n",
     455          61 :                 osIndent.c_str(), static_cast<GIntBig>(poStream->GetLength()),
     456          61 :                 static_cast<GIntBig>(poStream->GetRawLength()));
     457             :     }
     458             : }
     459             : 
     460          66 : void GDALPDFDumper::Dump(GDALPDFDictionary *poDict, int nDepth)
     461             : {
     462          66 :     if (nDepthLimit >= 0 && nDepth > nDepthLimit)
     463           0 :         return;
     464             : 
     465         132 :     CPLString osIndent;
     466         564 :     for (int i = 0; i < nDepth; i++)
     467         498 :         osIndent += " ";
     468          66 :     int i = 0;
     469          66 :     const auto &oMap = poDict->GetValues();
     470         623 :     for (const auto &[osKey, poObj] : oMap)
     471             :     {
     472         557 :         fprintf(f, "%sItem[%d] : %s", osIndent.c_str(), i, osKey.c_str());
     473         557 :         ++i;
     474         557 :         if (osKey == "Parent" && !bDumpParent)
     475             :         {
     476           0 :             if (poObj->GetRefNum().toBool())
     477           0 :                 fprintf(f, ", Num = %d, Gen = %d", poObj->GetRefNum().toInt(),
     478           0 :                         poObj->GetRefGen());
     479           0 :             fprintf(f, "\n");
     480           0 :             continue;
     481             :         }
     482         557 :         if (poObj != nullptr)
     483             :         {
     484         557 :             if (poObj->GetType() == PDFObjectType_String ||
     485         557 :                 poObj->GetType() == PDFObjectType_Null ||
     486         557 :                 poObj->GetType() == PDFObjectType_Bool ||
     487         557 :                 poObj->GetType() == PDFObjectType_Int ||
     488        1428 :                 poObj->GetType() == PDFObjectType_Real ||
     489         314 :                 poObj->GetType() == PDFObjectType_Name)
     490             :             {
     491         489 :                 fprintf(f, " = ");
     492         489 :                 DumpSimplified(poObj);
     493         489 :                 fprintf(f, "\n");
     494             :             }
     495             :             else
     496             :             {
     497          68 :                 fprintf(f, "\n");
     498          68 :                 Dump(poObj, nDepth + 1);
     499             :             }
     500             :         }
     501             :     }
     502             : }
     503             : 
     504             : /************************************************************************/
     505             : /*                           PDFRasterBand()                            */
     506             : /************************************************************************/
     507             : 
     508         664 : PDFRasterBand::PDFRasterBand(PDFDataset *poDSIn, int nBandIn,
     509         664 :                              int nResolutionLevelIn)
     510         664 :     : nResolutionLevel(nResolutionLevelIn)
     511             : {
     512         664 :     poDS = poDSIn;
     513         664 :     nBand = nBandIn;
     514             : 
     515         664 :     eDataType = GDT_UInt8;
     516         664 : }
     517             : 
     518             : /************************************************************************/
     519             : /*                              SetSize()                               */
     520             : /************************************************************************/
     521             : 
     522         664 : void PDFRasterBand::SetSize(int nXSize, int nYSize)
     523             : {
     524         664 :     nRasterXSize = nXSize;
     525         664 :     nRasterYSize = nYSize;
     526             : 
     527         664 :     const auto poPDFDS = cpl::down_cast<const PDFDataset *>(poDS);
     528         664 :     if (nResolutionLevel > 0)
     529             :     {
     530           0 :         nBlockXSize = 256;
     531           0 :         nBlockYSize = 256;
     532           0 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
     533             :     }
     534         664 :     else if (poPDFDS->m_nBlockXSize)
     535             :     {
     536          36 :         nBlockXSize = poPDFDS->m_nBlockXSize;
     537          36 :         nBlockYSize = poPDFDS->m_nBlockYSize;
     538          36 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
     539             :     }
     540         628 :     else if (nRasterXSize < 64 * 1024 * 1024 / nRasterYSize)
     541             :     {
     542         625 :         nBlockXSize = nRasterXSize;
     543         625 :         nBlockYSize = 1;
     544             :     }
     545             :     else
     546             :     {
     547           3 :         nBlockXSize = std::min(1024, nRasterXSize);
     548           3 :         nBlockYSize = std::min(1024, nRasterYSize);
     549           3 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
     550             :     }
     551         664 : }
     552             : 
     553             : /************************************************************************/
     554             : /*                           InitOverviews()                            */
     555             : /************************************************************************/
     556             : 
     557           5 : void PDFDataset::InitOverviews()
     558             : {
     559             : #ifdef HAVE_PDFIUM
     560             :     // Only if used pdfium, make "arbitrary overviews"
     561             :     // Blocks are 256x256
     562             :     if (m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
     563             :         m_apoOvrDSBackup.empty())
     564             :     {
     565             :         int nXSize = nRasterXSize;
     566             :         int nYSize = nRasterYSize;
     567             :         constexpr int minSize = 256;
     568             :         int nDiscard = 1;
     569             :         while (nXSize > minSize || nYSize > minSize)
     570             :         {
     571             :             nXSize = (nXSize + 1) / 2;
     572             :             nYSize = (nYSize + 1) / 2;
     573             : 
     574             :             auto poOvrDS = std::make_unique<PDFDataset>(this, nXSize, nYSize);
     575             : 
     576             :             for (int i = 0; i < nBands; i++)
     577             :             {
     578             :                 auto poBand = std::make_unique<PDFRasterBand>(poOvrDS.get(),
     579             :                                                               i + 1, nDiscard);
     580             :                 poBand->SetSize(nXSize, nYSize);
     581             :                 poOvrDS->SetBand(i + 1, std::move(poBand));
     582             :             }
     583             : 
     584             :             m_apoOvrDS.emplace_back(std::move(poOvrDS));
     585             :             ++nDiscard;
     586             :         }
     587             :     }
     588             : #endif
     589             : #if defined(HAVE_POPPLER) || defined(HAVE_PODOFO)
     590          13 :     if (!m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
     591          13 :         m_apoOvrDSBackup.empty() && m_osUserPwd != "ASK_INTERACTIVE")
     592             :     {
     593           2 :         int nXSize = nRasterXSize;
     594           2 :         int nYSize = nRasterYSize;
     595           2 :         constexpr int minSize = 256;
     596           2 :         double dfDPI = m_dfDPI;
     597           4 :         while (nXSize > minSize || nYSize > minSize)
     598             :         {
     599           2 :             nXSize = (nXSize + 1) / 2;
     600           2 :             nYSize = (nYSize + 1) / 2;
     601           2 :             dfDPI /= 2;
     602             : 
     603           2 :             GDALOpenInfo oOpenInfo(GetDescription(), GA_ReadOnly);
     604           2 :             CPLStringList aosOpenOptions(CSLDuplicate(papszOpenOptions));
     605           2 :             aosOpenOptions.SetNameValue("DPI", CPLSPrintf("%g", dfDPI));
     606           2 :             aosOpenOptions.SetNameValue("BANDS", CPLSPrintf("%d", nBands));
     607           2 :             aosOpenOptions.SetNameValue("@OPEN_FOR_OVERVIEW", "YES");
     608           2 :             if (!m_osUserPwd.empty())
     609           0 :                 aosOpenOptions.SetNameValue("USER_PWD", m_osUserPwd.c_str());
     610           2 :             oOpenInfo.papszOpenOptions = aosOpenOptions.List();
     611           2 :             auto poOvrDS = std::unique_ptr<PDFDataset>(Open(&oOpenInfo));
     612           2 :             if (!poOvrDS || poOvrDS->nBands != nBands)
     613           0 :                 break;
     614           2 :             poOvrDS->m_bIsOvrDS = true;
     615           2 :             m_apoOvrDS.emplace_back(std::move(poOvrDS));
     616             :         }
     617             :     }
     618             : #endif
     619           5 : }
     620             : 
     621             : /************************************************************************/
     622             : /*                       GetColorInterpretation()                       */
     623             : /************************************************************************/
     624             : 
     625          16 : GDALColorInterp PDFRasterBand::GetColorInterpretation()
     626             : {
     627          16 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     628          16 :     if (poGDS->nBands == 1)
     629           0 :         return GCI_GrayIndex;
     630             :     else
     631          16 :         return static_cast<GDALColorInterp>(GCI_RedBand + (nBand - 1));
     632             : }
     633             : 
     634             : /************************************************************************/
     635             : /*                          GetOverviewCount()                          */
     636             : /************************************************************************/
     637             : 
     638           9 : int PDFRasterBand::GetOverviewCount()
     639             : {
     640           9 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     641           9 :     if (poGDS->m_bIsOvrDS)
     642           0 :         return 0;
     643           9 :     if (GDALPamRasterBand::GetOverviewCount() > 0)
     644           4 :         return GDALPamRasterBand::GetOverviewCount();
     645             :     else
     646             :     {
     647           5 :         poGDS->InitOverviews();
     648           5 :         return static_cast<int>(poGDS->m_apoOvrDS.size());
     649             :     }
     650             : }
     651             : 
     652             : /************************************************************************/
     653             : /*                            GetOverview()                             */
     654             : /************************************************************************/
     655             : 
     656           4 : GDALRasterBand *PDFRasterBand::GetOverview(int iOverviewIndex)
     657             : {
     658           4 :     if (GDALPamRasterBand::GetOverviewCount() > 0)
     659           1 :         return GDALPamRasterBand::GetOverview(iOverviewIndex);
     660             : 
     661           3 :     else if (iOverviewIndex < 0 || iOverviewIndex >= GetOverviewCount())
     662           2 :         return nullptr;
     663             :     else
     664             :     {
     665           1 :         PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     666           1 :         return poGDS->m_apoOvrDS[iOverviewIndex]->GetRasterBand(nBand);
     667             :     }
     668             : }
     669             : 
     670             : /************************************************************************/
     671             : /*                           ~PDFRasterBand()                           */
     672             : /************************************************************************/
     673             : 
     674        1328 : PDFRasterBand::~PDFRasterBand()
     675             : {
     676        1328 : }
     677             : 
     678             : /************************************************************************/
     679             : /*                         IReadBlockFromTile()                         */
     680             : /************************************************************************/
     681             : 
     682         160 : CPLErr PDFRasterBand::IReadBlockFromTile(int nBlockXOff, int nBlockYOff,
     683             :                                          void *pImage)
     684             : 
     685             : {
     686         160 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     687             : 
     688         160 :     const int nXOff = nBlockXOff * nBlockXSize;
     689         160 :     const int nReqXSize = std::min(nBlockXSize, nRasterXSize - nXOff);
     690         160 :     const int nYOff = nBlockYOff * nBlockYSize;
     691         160 :     const int nReqYSize = std::min(nBlockYSize, nRasterYSize - nYOff);
     692             : 
     693         160 :     const int nXBlocks = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
     694         160 :     int iTile = poGDS->m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff];
     695         160 :     if (iTile < 0)
     696             :     {
     697           0 :         memset(pImage, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
     698           0 :         return CE_None;
     699             :     }
     700             : 
     701         160 :     GDALPDFTileDesc &sTile = poGDS->m_asTiles[iTile];
     702         160 :     GDALPDFObject *poImage = sTile.poImage;
     703             : 
     704         160 :     if (nBand == 4)
     705             :     {
     706          30 :         GDALPDFDictionary *poImageDict = poImage->GetDictionary();
     707          30 :         GDALPDFObject *poSMask = poImageDict->Get("SMask");
     708          60 :         if (poSMask != nullptr &&
     709          30 :             poSMask->GetType() == PDFObjectType_Dictionary)
     710             :         {
     711          30 :             GDALPDFDictionary *poSMaskDict = poSMask->GetDictionary();
     712          30 :             GDALPDFObject *poWidth = poSMaskDict->Get("Width");
     713          30 :             GDALPDFObject *poHeight = poSMaskDict->Get("Height");
     714          30 :             GDALPDFObject *poColorSpace = poSMaskDict->Get("ColorSpace");
     715             :             GDALPDFObject *poBitsPerComponent =
     716          30 :                 poSMaskDict->Get("BitsPerComponent");
     717          30 :             double dfBits = 0;
     718          30 :             if (poBitsPerComponent)
     719          30 :                 dfBits = Get(poBitsPerComponent);
     720          30 :             if (poWidth && Get(poWidth) == nReqXSize && poHeight &&
     721          30 :                 Get(poHeight) == nReqYSize && poColorSpace &&
     722          60 :                 poColorSpace->GetType() == PDFObjectType_Name &&
     723         112 :                 poColorSpace->GetName() == "DeviceGray" &&
     724          22 :                 (dfBits == 1 || dfBits == 8))
     725             :             {
     726          30 :                 GDALPDFStream *poStream = poSMask->GetStream();
     727          30 :                 GByte *pabyStream = nullptr;
     728             : 
     729          30 :                 if (poStream == nullptr)
     730           0 :                     return CE_Failure;
     731             : 
     732          30 :                 pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
     733          30 :                 if (pabyStream == nullptr)
     734           0 :                     return CE_Failure;
     735             : 
     736          30 :                 const int nReqXSize1 = (nReqXSize + 7) / 8;
     737          52 :                 if ((dfBits == 8 &&
     738          22 :                      static_cast<size_t>(poStream->GetLength()) !=
     739          60 :                          static_cast<size_t>(nReqXSize) * nReqYSize) ||
     740           8 :                     (dfBits == 1 &&
     741           8 :                      static_cast<size_t>(poStream->GetLength()) !=
     742           8 :                          static_cast<size_t>(nReqXSize1) * nReqYSize))
     743             :                 {
     744           0 :                     VSIFree(pabyStream);
     745           0 :                     return CE_Failure;
     746             :                 }
     747             : 
     748          30 :                 GByte *pabyData = static_cast<GByte *>(pImage);
     749          30 :                 if (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize)
     750             :                 {
     751          10 :                     memset(pabyData, 0,
     752          10 :                            static_cast<size_t>(nBlockXSize) * nBlockYSize);
     753             :                 }
     754             : 
     755          30 :                 if (dfBits == 8)
     756             :                 {
     757         686 :                     for (int j = 0; j < nReqYSize; j++)
     758             :                     {
     759       21912 :                         for (int i = 0; i < nReqXSize; i++)
     760             :                         {
     761       21248 :                             pabyData[j * nBlockXSize + i] =
     762       21248 :                                 pabyStream[j * nReqXSize + i];
     763             :                         }
     764             :                     }
     765             :                 }
     766             :                 else
     767             :                 {
     768         244 :                     for (int j = 0; j < nReqYSize; j++)
     769             :                     {
     770        3288 :                         for (int i = 0; i < nReqXSize; i++)
     771             :                         {
     772        3052 :                             if (pabyStream[j * nReqXSize1 + i / 8] &
     773        3052 :                                 (1 << (7 - (i % 8))))
     774         896 :                                 pabyData[j * nBlockXSize + i] = 255;
     775             :                             else
     776        2156 :                                 pabyData[j * nBlockXSize + i] = 0;
     777             :                         }
     778             :                     }
     779             :                 }
     780             : 
     781          30 :                 VSIFree(pabyStream);
     782          30 :                 return CE_None;
     783             :             }
     784             :         }
     785             : 
     786           0 :         memset(pImage, 255, static_cast<size_t>(nBlockXSize) * nBlockYSize);
     787           0 :         return CE_None;
     788             :     }
     789             : 
     790         130 :     if (poGDS->m_nLastBlockXOff == nBlockXOff &&
     791           0 :         poGDS->m_nLastBlockYOff == nBlockYOff &&
     792           0 :         poGDS->m_pabyCachedData != nullptr)
     793             :     {
     794             : #ifdef DEBUG
     795           0 :         CPLDebug("PDF", "Using cached block (%d, %d)", nBlockXOff, nBlockYOff);
     796             : #endif
     797             :         // do nothing
     798             :     }
     799             :     else
     800             :     {
     801         130 :         if (!poGDS->m_bTried)
     802             :         {
     803           5 :             poGDS->m_bTried = true;
     804           5 :             poGDS->m_pabyCachedData =
     805           5 :                 static_cast<GByte *>(VSIMalloc3(3, nBlockXSize, nBlockYSize));
     806             :         }
     807         130 :         if (poGDS->m_pabyCachedData == nullptr)
     808           0 :             return CE_Failure;
     809             : 
     810         130 :         GDALPDFStream *poStream = poImage->GetStream();
     811         130 :         GByte *pabyStream = nullptr;
     812             : 
     813         130 :         if (poStream == nullptr)
     814           0 :             return CE_Failure;
     815             : 
     816         130 :         pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
     817         130 :         if (pabyStream == nullptr)
     818           0 :             return CE_Failure;
     819             : 
     820         130 :         if (static_cast<size_t>(poStream->GetLength()) !=
     821         130 :             static_cast<size_t>(sTile.nBands) * nReqXSize * nReqYSize)
     822             :         {
     823           0 :             VSIFree(pabyStream);
     824           0 :             return CE_Failure;
     825             :         }
     826             : 
     827         130 :         memcpy(poGDS->m_pabyCachedData, pabyStream,
     828         130 :                static_cast<size_t>(poStream->GetLength()));
     829         130 :         VSIFree(pabyStream);
     830         130 :         poGDS->m_nLastBlockXOff = nBlockXOff;
     831         130 :         poGDS->m_nLastBlockYOff = nBlockYOff;
     832             :     }
     833             : 
     834         130 :     GByte *pabyData = static_cast<GByte *>(pImage);
     835         130 :     if (nBand != 4 && (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize))
     836             :     {
     837          30 :         memset(pabyData, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
     838             :     }
     839             : 
     840         130 :     if (poGDS->nBands >= 3 && sTile.nBands == 3)
     841             :     {
     842        2790 :         for (int j = 0; j < nReqYSize; j++)
     843             :         {
     844       75600 :             for (int i = 0; i < nReqXSize; i++)
     845             :             {
     846       72900 :                 pabyData[j * nBlockXSize + i] =
     847             :                     poGDS
     848       72900 :                         ->m_pabyCachedData[3 * (j * nReqXSize + i) + nBand - 1];
     849             :             }
     850          90 :         }
     851             :     }
     852          40 :     else if (sTile.nBands == 1)
     853             :     {
     854        6184 :         for (int j = 0; j < nReqYSize; j++)
     855             :         {
     856     1054720 :             for (int i = 0; i < nReqXSize; i++)
     857             :             {
     858     1048580 :                 pabyData[j * nBlockXSize + i] =
     859     1048580 :                     poGDS->m_pabyCachedData[j * nReqXSize + i];
     860             :             }
     861             :         }
     862             :     }
     863             : 
     864         130 :     return CE_None;
     865             : }
     866             : 
     867             : /************************************************************************/
     868             : /*                   GetSuggestedBlockAccessPattern()                   */
     869             : /************************************************************************/
     870             : 
     871             : GDALSuggestedBlockAccessPattern
     872           1 : PDFRasterBand::GetSuggestedBlockAccessPattern() const
     873             : {
     874           1 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     875           1 :     if (!poGDS->m_aiTiles.empty())
     876           0 :         return GSBAP_RANDOM;
     877           1 :     return GSBAP_LARGEST_CHUNK_POSSIBLE;
     878             : }
     879             : 
     880             : /************************************************************************/
     881             : /*                             IReadBlock()                             */
     882             : /************************************************************************/
     883             : 
     884       25832 : CPLErr PDFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
     885             : 
     886             : {
     887       25832 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
     888             : 
     889       25832 :     if (!poGDS->m_aiTiles.empty())
     890             :     {
     891         160 :         if (IReadBlockFromTile(nBlockXOff, nBlockYOff, pImage) == CE_None)
     892             :         {
     893         160 :             return CE_None;
     894             :         }
     895             :         else
     896             :         {
     897           0 :             poGDS->m_aiTiles.resize(0);
     898           0 :             poGDS->m_bTried = false;
     899           0 :             CPLFree(poGDS->m_pabyCachedData);
     900           0 :             poGDS->m_pabyCachedData = nullptr;
     901           0 :             poGDS->m_nLastBlockXOff = -1;
     902           0 :             poGDS->m_nLastBlockYOff = -1;
     903             :         }
     904             :     }
     905             : 
     906       25672 :     const int nXOff = nBlockXOff * nBlockXSize;
     907       25672 :     const int nReqXSize = std::min(nBlockXSize, nRasterXSize - nXOff);
     908             :     const int nReqYSize =
     909       25672 :         nBlockYSize == 1
     910       25673 :             ? nRasterYSize
     911           1 :             : std::min(nBlockYSize, nRasterYSize - nBlockYOff * nBlockYSize);
     912             : 
     913       25672 :     if (!poGDS->m_bTried)
     914             :     {
     915          55 :         poGDS->m_bTried = true;
     916          55 :         if (nBlockYSize == 1)
     917         162 :             poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
     918          54 :                 std::max(3, poGDS->nBands), nRasterXSize, nRasterYSize));
     919             :         else
     920           3 :             poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
     921           1 :                 std::max(3, poGDS->nBands), nBlockXSize, nBlockYSize));
     922             :     }
     923       25672 :     if (poGDS->m_pabyCachedData == nullptr)
     924           0 :         return CE_Failure;
     925             : 
     926       25672 :     if (poGDS->m_nLastBlockXOff == nBlockXOff &&
     927       25617 :         (nBlockYSize == 1 || poGDS->m_nLastBlockYOff == nBlockYOff) &&
     928       25617 :         poGDS->m_pabyCachedData != nullptr)
     929             :     {
     930             :         /*CPLDebug("PDF", "Using cached block (%d, %d)",
     931             :                  nBlockXOff, nBlockYOff);*/
     932             :         // do nothing
     933             :     }
     934             :     else
     935             :     {
     936             : #ifdef HAVE_PODOFO
     937             :         if (poGDS->m_bUseLib.test(PDFLIB_PODOFO) && nBand == 4)
     938             :         {
     939             :             memset(pImage, 255, nBlockXSize * nBlockYSize);
     940             :             return CE_None;
     941             :         }
     942             : #endif
     943             : 
     944          55 :         const int nReqXOff = nBlockXOff * nBlockXSize;
     945          55 :         const int nReqYOff = (nBlockYSize == 1) ? 0 : nBlockYOff * nBlockYSize;
     946          55 :         const GSpacing nPixelSpace = 1;
     947          55 :         const GSpacing nLineSpace = nBlockXSize;
     948          55 :         const GSpacing nBandSpace =
     949          55 :             static_cast<GSpacing>(nBlockXSize) *
     950          55 :             ((nBlockYSize == 1) ? nRasterYSize : nBlockYSize);
     951             : 
     952          55 :         CPLErr eErr = poGDS->ReadPixels(nReqXOff, nReqYOff, nReqXSize,
     953             :                                         nReqYSize, nPixelSpace, nLineSpace,
     954             :                                         nBandSpace, poGDS->m_pabyCachedData);
     955             : 
     956          55 :         if (eErr == CE_None)
     957             :         {
     958          55 :             poGDS->m_nLastBlockXOff = nBlockXOff;
     959          55 :             poGDS->m_nLastBlockYOff = nBlockYOff;
     960             :         }
     961             :         else
     962             :         {
     963           0 :             CPLFree(poGDS->m_pabyCachedData);
     964           0 :             poGDS->m_pabyCachedData = nullptr;
     965             :         }
     966             :     }
     967       25672 :     if (poGDS->m_pabyCachedData == nullptr)
     968           0 :         return CE_Failure;
     969             : 
     970       25672 :     if (nBlockYSize == 1)
     971       25671 :         memcpy(pImage,
     972       25671 :                poGDS->m_pabyCachedData +
     973       25671 :                    (nBand - 1) * nBlockXSize * nRasterYSize +
     974       25671 :                    nBlockYOff * nBlockXSize,
     975       25671 :                nBlockXSize);
     976             :     else
     977             :     {
     978           1 :         memcpy(pImage,
     979           1 :                poGDS->m_pabyCachedData +
     980           1 :                    static_cast<size_t>(nBand - 1) * nBlockXSize * nBlockYSize,
     981           1 :                static_cast<size_t>(nBlockXSize) * nBlockYSize);
     982             : 
     983           1 :         if (poGDS->m_bCacheBlocksForOtherBands && nBand == 1)
     984             :         {
     985           3 :             for (int iBand = 2; iBand <= poGDS->nBands; ++iBand)
     986             :             {
     987           4 :                 auto poOtherBand = cpl::down_cast<PDFRasterBand *>(
     988           2 :                     poGDS->papoBands[iBand - 1]);
     989             :                 GDALRasterBlock *poBlock =
     990           2 :                     poOtherBand->TryGetLockedBlockRef(nBlockXOff, nBlockYOff);
     991           2 :                 if (poBlock)
     992             :                 {
     993           0 :                     poBlock->DropLock();
     994             :                 }
     995             :                 else
     996             :                 {
     997           4 :                     poBlock = poOtherBand->GetLockedBlockRef(nBlockXOff,
     998           2 :                                                              nBlockYOff, TRUE);
     999           2 :                     if (poBlock)
    1000             :                     {
    1001           4 :                         memcpy(poBlock->GetDataRef(),
    1002           2 :                                poGDS->m_pabyCachedData +
    1003           2 :                                    static_cast<size_t>(iBand - 1) *
    1004           2 :                                        nBlockXSize * nBlockYSize,
    1005           2 :                                static_cast<size_t>(nBlockXSize) * nBlockYSize);
    1006           2 :                         poBlock->DropLock();
    1007             :                     }
    1008             :                 }
    1009             :             }
    1010             :         }
    1011             :     }
    1012             : 
    1013       25672 :     return CE_None;
    1014             : }
    1015             : 
    1016             : /************************************************************************/
    1017             : /*                PDFEnterPasswordFromConsoleIfNeeded()                 */
    1018             : /************************************************************************/
    1019             : 
    1020           2 : static const char *PDFEnterPasswordFromConsoleIfNeeded(const char *pszUserPwd)
    1021             : {
    1022           2 :     if (EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
    1023             :     {
    1024             :         static char szPassword[81];
    1025           2 :         printf("Enter password (will be echo'ed in the console): "); /*ok*/
    1026           2 :         if (nullptr == fgets(szPassword, sizeof(szPassword), stdin))
    1027             :         {
    1028           0 :             fprintf(stderr, "WARNING: Error getting password.\n"); /*ok*/
    1029             :         }
    1030           2 :         szPassword[sizeof(szPassword) - 1] = 0;
    1031           2 :         char *sz10 = strchr(szPassword, '\n');
    1032           2 :         if (sz10)
    1033           0 :             *sz10 = 0;
    1034           2 :         return szPassword;
    1035             :     }
    1036           0 :     return pszUserPwd;
    1037             : }
    1038             : 
    1039             : #ifdef HAVE_PDFIUM
    1040             : 
    1041             : /************************************************************************/
    1042             : /*                         Pdfium Load/Unload                           */
    1043             : /* Copyright (C) 2015 Klokan Technologies GmbH (http://www.klokantech.com/) */
    1044             : /* Author: Martin Mikita <martin.mikita@klokantech.com>                 */
    1045             : /************************************************************************/
    1046             : 
    1047             : // Flag for calling PDFium Init and Destroy methods
    1048             : bool PDFDataset::g_bPdfiumInit = false;
    1049             : 
    1050             : // Pdfium global read mutex - Pdfium is not multi-thread
    1051             : static CPLMutex *g_oPdfiumReadMutex = nullptr;
    1052             : static CPLMutex *g_oPdfiumLoadDocMutex = nullptr;
    1053             : 
    1054             : // Comparison of char* for std::map
    1055             : struct cmp_str
    1056             : {
    1057             :     bool operator()(char const *a, char const *b) const
    1058             :     {
    1059             :         return strcmp(a, b) < 0;
    1060             :     }
    1061             : };
    1062             : 
    1063             : static int GDALPdfiumGetBlock(void *param, unsigned long position,
    1064             :                               unsigned char *pBuf, unsigned long size)
    1065             : {
    1066             :     VSILFILE *fp = static_cast<VSILFILE *>(param);
    1067             :     VSIFSeekL(fp, static_cast<vsi_l_offset>(position), SEEK_SET);
    1068             :     return VSIFReadL(pBuf, size, 1, fp) == 1;
    1069             : }
    1070             : 
    1071             : // List of all PDF datasets
    1072             : typedef std::map<const char *, TPdfiumDocumentStruct *, cmp_str>
    1073             :     TMapPdfiumDatasets;
    1074             : static TMapPdfiumDatasets g_mPdfiumDatasets;
    1075             : 
    1076             : /**
    1077             :  * Loading PDFIUM page
    1078             :  * - multithreading requires "mutex"
    1079             :  * - one page can require too much RAM
    1080             :  * - we will have one document per filename and one object per page
    1081             :  */
    1082             : 
    1083             : static int LoadPdfiumDocumentPage(const char *pszFilename,
    1084             :                                   const char *pszUserPwd, int pageNum,
    1085             :                                   TPdfiumDocumentStruct **doc,
    1086             :                                   TPdfiumPageStruct **page, int *pnPageCount)
    1087             : {
    1088             :     // Prepare nullptr for error returning
    1089             :     if (doc)
    1090             :         *doc = nullptr;
    1091             :     if (page)
    1092             :         *page = nullptr;
    1093             :     if (pnPageCount)
    1094             :         *pnPageCount = 0;
    1095             : 
    1096             :     // Loading document and page must be only in one thread!
    1097             :     CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
    1098             : 
    1099             :     // Library can be destroyed if every PDF dataset was closed!
    1100             :     if (!PDFDataset::g_bPdfiumInit)
    1101             :     {
    1102             :         FPDF_InitLibrary();
    1103             :         PDFDataset::g_bPdfiumInit = TRUE;
    1104             :     }
    1105             : 
    1106             :     TMapPdfiumDatasets::iterator it;
    1107             :     it = g_mPdfiumDatasets.find(pszFilename);
    1108             :     TPdfiumDocumentStruct *poDoc = nullptr;
    1109             :     // Load new document if missing
    1110             :     if (it == g_mPdfiumDatasets.end())
    1111             :     {
    1112             :         // Try without password (if PDF not requires password it can fail)
    1113             : 
    1114             :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    1115             :         if (fp == nullptr)
    1116             :         {
    1117             :             CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1118             :             return FALSE;
    1119             :         }
    1120             :         VSIFSeekL(fp, 0, SEEK_END);
    1121             :         const auto nFileLen64 = VSIFTellL(fp);
    1122             :         if constexpr (LONG_MAX < std::numeric_limits<vsi_l_offset>::max())
    1123             :         {
    1124             :             if (nFileLen64 > LONG_MAX)
    1125             :             {
    1126             :                 VSIFCloseL(fp);
    1127             :                 CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1128             :                 return FALSE;
    1129             :             }
    1130             :         }
    1131             : 
    1132             :         FPDF_FILEACCESS *psFileAccess = new FPDF_FILEACCESS;
    1133             :         psFileAccess->m_Param = fp;
    1134             :         psFileAccess->m_FileLen = static_cast<unsigned long>(nFileLen64);
    1135             :         psFileAccess->m_GetBlock = GDALPdfiumGetBlock;
    1136             :         CPDF_Document *docPdfium = CPDFDocumentFromFPDFDocument(
    1137             :             FPDF_LoadCustomDocument(psFileAccess, nullptr));
    1138             :         if (docPdfium == nullptr)
    1139             :         {
    1140             :             unsigned long err = FPDF_GetLastError();
    1141             :             if (err == FPDF_ERR_PASSWORD)
    1142             :             {
    1143             :                 if (pszUserPwd)
    1144             :                 {
    1145             :                     pszUserPwd =
    1146             :                         PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
    1147             :                     docPdfium = CPDFDocumentFromFPDFDocument(
    1148             :                         FPDF_LoadCustomDocument(psFileAccess, pszUserPwd));
    1149             :                     if (docPdfium == nullptr)
    1150             :                         err = FPDF_GetLastError();
    1151             :                     else
    1152             :                         err = FPDF_ERR_SUCCESS;
    1153             :                 }
    1154             :                 else
    1155             :                 {
    1156             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1157             :                              "A password is needed. You can specify it through "
    1158             :                              "the PDF_USER_PWD "
    1159             :                              "configuration option / USER_PWD open option "
    1160             :                              "(that can be set to ASK_INTERACTIVE)");
    1161             : 
    1162             :                     VSIFCloseL(fp);
    1163             :                     delete psFileAccess;
    1164             :                     CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1165             :                     return FALSE;
    1166             :                 }
    1167             :             }  // First Error Password [null password given]
    1168             :             if (err != FPDF_ERR_SUCCESS)
    1169             :             {
    1170             :                 if (err == FPDF_ERR_PASSWORD)
    1171             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1172             :                              "PDFium Invalid password.");
    1173             :                 else if (err == FPDF_ERR_SECURITY)
    1174             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1175             :                              "PDFium Unsupported security scheme.");
    1176             :                 else if (err == FPDF_ERR_FORMAT)
    1177             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1178             :                              "PDFium File not in PDF format or corrupted.");
    1179             :                 else if (err == FPDF_ERR_FILE)
    1180             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1181             :                              "PDFium File not found or could not be opened.");
    1182             :                 else
    1183             :                     CPLError(CE_Failure, CPLE_AppDefined,
    1184             :                              "PDFium Unknown PDF error or invalid PDF.");
    1185             : 
    1186             :                 VSIFCloseL(fp);
    1187             :                 delete psFileAccess;
    1188             :                 CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1189             :                 return FALSE;
    1190             :             }
    1191             :         }  // ~ wrong PDF or password required
    1192             : 
    1193             :         // Create new poDoc
    1194             :         poDoc = new TPdfiumDocumentStruct;
    1195             :         if (!poDoc)
    1196             :         {
    1197             :             CPLError(CE_Failure, CPLE_AppDefined,
    1198             :                      "Not enough memory for Pdfium Document object");
    1199             : 
    1200             :             VSIFCloseL(fp);
    1201             :             delete psFileAccess;
    1202             :             CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1203             :             return FALSE;
    1204             :         }
    1205             :         poDoc->filename = CPLStrdup(pszFilename);
    1206             :         poDoc->doc = docPdfium;
    1207             :         poDoc->psFileAccess = psFileAccess;
    1208             : 
    1209             :         g_mPdfiumDatasets[poDoc->filename] = poDoc;
    1210             :     }
    1211             :     // Document already loaded
    1212             :     else
    1213             :     {
    1214             :         poDoc = it->second;
    1215             :     }
    1216             : 
    1217             :     // Check page num in document
    1218             :     int nPages = poDoc->doc->GetPageCount();
    1219             :     if (pageNum < 1 || pageNum > nPages)
    1220             :     {
    1221             :         CPLError(CE_Failure, CPLE_AppDefined,
    1222             :                  "PDFium Invalid page number (%d/%d) for document %s", pageNum,
    1223             :                  nPages, pszFilename);
    1224             : 
    1225             :         CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1226             :         return FALSE;
    1227             :     }
    1228             : 
    1229             :     /* Sanity check to validate page count */
    1230             :     if (pageNum != nPages)
    1231             :     {
    1232             :         if (poDoc->doc->GetPageDictionary(nPages - 1) == nullptr)
    1233             :         {
    1234             :             CPLError(CE_Failure, CPLE_AppDefined,
    1235             :                      "Invalid PDF : invalid page count");
    1236             :             CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1237             :             return FALSE;
    1238             :         }
    1239             :     }
    1240             : 
    1241             :     TMapPdfiumPages::iterator itPage;
    1242             :     itPage = poDoc->pages.find(pageNum);
    1243             :     TPdfiumPageStruct *poPage = nullptr;
    1244             :     // Page not loaded
    1245             :     if (itPage == poDoc->pages.end())
    1246             :     {
    1247             :         auto pDict = poDoc->doc->GetMutablePageDictionary(pageNum - 1);
    1248             :         if (pDict == nullptr)
    1249             :         {
    1250             :             CPLError(CE_Failure, CPLE_AppDefined,
    1251             :                      "Invalid PDFium : invalid page");
    1252             : 
    1253             :             CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1254             :             return FALSE;
    1255             :         }
    1256             :         auto pPage = pdfium::MakeRetain<CPDF_Page>(poDoc->doc, pDict);
    1257             : 
    1258             :         poPage = new TPdfiumPageStruct;
    1259             :         if (!poPage)
    1260             :         {
    1261             :             CPLError(CE_Failure, CPLE_AppDefined,
    1262             :                      "Not enough memory for Pdfium Page object");
    1263             : 
    1264             :             CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1265             :             return FALSE;
    1266             :         }
    1267             :         poPage->pageNum = pageNum;
    1268             :         poPage->page = pPage.Leak();
    1269             :         poPage->readMutex = nullptr;
    1270             :         poPage->sharedNum = 0;
    1271             : 
    1272             :         poDoc->pages[pageNum] = poPage;
    1273             :     }
    1274             :     // Page already loaded
    1275             :     else
    1276             :     {
    1277             :         poPage = itPage->second;
    1278             :     }
    1279             : 
    1280             :     // Increase number of used
    1281             :     ++poPage->sharedNum;
    1282             : 
    1283             :     if (doc)
    1284             :         *doc = poDoc;
    1285             :     if (page)
    1286             :         *page = poPage;
    1287             :     if (pnPageCount)
    1288             :         *pnPageCount = nPages;
    1289             : 
    1290             :     CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1291             : 
    1292             :     return TRUE;
    1293             : }
    1294             : 
    1295             : // ~ static int LoadPdfiumDocumentPage()
    1296             : 
    1297             : static int UnloadPdfiumDocumentPage(TPdfiumDocumentStruct **doc,
    1298             :                                     TPdfiumPageStruct **page)
    1299             : {
    1300             :     if (!doc || !page)
    1301             :         return FALSE;
    1302             : 
    1303             :     TPdfiumPageStruct *pPage = *page;
    1304             :     TPdfiumDocumentStruct *pDoc = *doc;
    1305             : 
    1306             :     // Get mutex for loading pdfium
    1307             :     CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
    1308             : 
    1309             :     // Decrease page use
    1310             :     --pPage->sharedNum;
    1311             : 
    1312             : #ifdef DEBUG
    1313             :     CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: page shared num %d",
    1314             :              pPage->sharedNum);
    1315             : #endif
    1316             :     // Page is used (also document)
    1317             :     if (pPage->sharedNum != 0)
    1318             :     {
    1319             :         CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1320             :         return TRUE;
    1321             :     }
    1322             : 
    1323             :     // Get mutex, release and destroy it
    1324             :     CPLCreateOrAcquireMutex(&(pPage->readMutex), PDFIUM_MUTEX_TIMEOUT);
    1325             :     CPLReleaseMutex(pPage->readMutex);
    1326             :     CPLDestroyMutex(pPage->readMutex);
    1327             :     // Close page and remove from map
    1328             :     FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
    1329             : 
    1330             :     pDoc->pages.erase(pPage->pageNum);
    1331             :     delete pPage;
    1332             :     pPage = nullptr;
    1333             : 
    1334             : #ifdef DEBUG
    1335             :     CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: pages %lu",
    1336             :              pDoc->pages.size());
    1337             : #endif
    1338             :     // Another page is used
    1339             :     if (!pDoc->pages.empty())
    1340             :     {
    1341             :         CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1342             :         return TRUE;
    1343             :     }
    1344             : 
    1345             :     // Close document and remove from map
    1346             :     FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
    1347             :     g_mPdfiumDatasets.erase(pDoc->filename);
    1348             :     CPLFree(pDoc->filename);
    1349             :     VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
    1350             :     delete pDoc->psFileAccess;
    1351             :     delete pDoc;
    1352             :     pDoc = nullptr;
    1353             : 
    1354             : #ifdef DEBUG
    1355             :     CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: documents %lu",
    1356             :              g_mPdfiumDatasets.size());
    1357             : #endif
    1358             :     // Another document is used
    1359             :     if (!g_mPdfiumDatasets.empty())
    1360             :     {
    1361             :         CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1362             :         return TRUE;
    1363             :     }
    1364             : 
    1365             : #ifdef DEBUG
    1366             :     CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: Nothing loaded, "
    1367             :                     "destroy Library");
    1368             : #endif
    1369             :     // No document loaded, destroy pdfium
    1370             :     FPDF_DestroyLibrary();
    1371             :     PDFDataset::g_bPdfiumInit = FALSE;
    1372             : 
    1373             :     CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    1374             : 
    1375             :     return TRUE;
    1376             : }
    1377             : 
    1378             : // ~ static int UnloadPdfiumDocumentPage()
    1379             : 
    1380             : #endif  // ~ HAVE_PDFIUM
    1381             : 
    1382             : /************************************************************************/
    1383             : /*                             GetOption()                              */
    1384             : /************************************************************************/
    1385             : 
    1386        1176 : const char *PDFDataset::GetOption(char **papszOpenOptionsIn,
    1387             :                                   const char *pszOptionName,
    1388             :                                   const char *pszDefaultVal)
    1389             : {
    1390        1176 :     CPLErr eLastErrType = CPLGetLastErrorType();
    1391        1176 :     CPLErrorNum nLastErrno = CPLGetLastErrorNo();
    1392        2352 :     CPLString osLastErrorMsg(CPLGetLastErrorMsg());
    1393        1176 :     CPLXMLNode *psNode = CPLParseXMLString(PDFGetOpenOptionList());
    1394        1176 :     CPLErrorSetState(eLastErrType, nLastErrno, osLastErrorMsg);
    1395        1176 :     if (psNode == nullptr)
    1396           0 :         return pszDefaultVal;
    1397        1176 :     CPLXMLNode *psIter = psNode->psChild;
    1398        5747 :     while (psIter != nullptr)
    1399             :     {
    1400        5747 :         if (EQUAL(CPLGetXMLValue(psIter, "name", ""), pszOptionName))
    1401             :         {
    1402             :             const char *pszVal =
    1403        1176 :                 CSLFetchNameValue(papszOpenOptionsIn, pszOptionName);
    1404        1176 :             if (pszVal != nullptr)
    1405             :             {
    1406          23 :                 CPLDestroyXMLNode(psNode);
    1407          23 :                 return pszVal;
    1408             :             }
    1409             :             const char *pszAltConfigOption =
    1410        1153 :                 CPLGetXMLValue(psIter, "alt_config_option", nullptr);
    1411        1153 :             if (pszAltConfigOption != nullptr)
    1412             :             {
    1413        1153 :                 pszVal = CPLGetConfigOption(pszAltConfigOption, pszDefaultVal);
    1414        1153 :                 CPLDestroyXMLNode(psNode);
    1415        1153 :                 return pszVal;
    1416             :             }
    1417           0 :             CPLDestroyXMLNode(psNode);
    1418           0 :             return pszDefaultVal;
    1419             :         }
    1420        4571 :         psIter = psIter->psNext;
    1421             :     }
    1422           0 :     CPLError(CE_Failure, CPLE_AppDefined,
    1423             :              "Requesting an undocumented open option '%s'", pszOptionName);
    1424           0 :     CPLDestroyXMLNode(psNode);
    1425           0 :     return pszDefaultVal;
    1426             : }
    1427             : 
    1428             : #ifdef HAVE_PDFIUM
    1429             : 
    1430             : /************************************************************************/
    1431             : /*                         GDALPDFiumOCContext                          */
    1432             : /************************************************************************/
    1433             : 
    1434             : class GDALPDFiumOCContext final : public CPDF_OCContextInterface
    1435             : {
    1436             :     PDFDataset *m_poDS;
    1437             :     RetainPtr<CPDF_OCContext> m_DefaultOCContext;
    1438             : 
    1439             :     CPL_DISALLOW_COPY_ASSIGN(GDALPDFiumOCContext)
    1440             : 
    1441             :   public:
    1442             :     GDALPDFiumOCContext(PDFDataset *poDS, CPDF_Document *pDoc,
    1443             :                         CPDF_OCContext::UsageType usage)
    1444             :         : m_poDS(poDS),
    1445             :           m_DefaultOCContext(pdfium::MakeRetain<CPDF_OCContext>(pDoc, usage))
    1446             :     {
    1447             :     }
    1448             : 
    1449             :     virtual bool
    1450             :     CheckOCGDictVisible(const CPDF_Dictionary *pOCGDict) const override
    1451             :     {
    1452             :         // CPLDebug("PDF", "CheckOCGDictVisible(%d,%d)",
    1453             :         //          pOCGDict->GetObjNum(), pOCGDict->GetGenNum() );
    1454             :         PDFDataset::VisibilityState eVisibility =
    1455             :             m_poDS->GetVisibilityStateForOGCPdfium(pOCGDict->GetObjNum(),
    1456             :                                                    pOCGDict->GetGenNum());
    1457             :         if (eVisibility == PDFDataset::VISIBILITY_ON)
    1458             :             return true;
    1459             :         if (eVisibility == PDFDataset::VISIBILITY_OFF)
    1460             :             return false;
    1461             :         return m_DefaultOCContext->CheckOCGDictVisible(pOCGDict);
    1462             :     }
    1463             : };
    1464             : 
    1465             : /************************************************************************/
    1466             : /*                     GDALPDFiumRenderDeviceDriver                     */
    1467             : /************************************************************************/
    1468             : 
    1469             : class GDALPDFiumRenderDeviceDriver final : public RenderDeviceDriverIface
    1470             : {
    1471             :     std::unique_ptr<RenderDeviceDriverIface> m_poParent;
    1472             :     CFX_RenderDevice *device_;
    1473             : 
    1474             :     int bEnableVector;
    1475             :     int bEnableText;
    1476             :     int bEnableBitmap;
    1477             :     int bTemporaryEnableVectorForTextStroking;
    1478             : 
    1479             :     CPL_DISALLOW_COPY_ASSIGN(GDALPDFiumRenderDeviceDriver)
    1480             : 
    1481             :   public:
    1482             :     GDALPDFiumRenderDeviceDriver(
    1483             :         std::unique_ptr<RenderDeviceDriverIface> &&poParent,
    1484             :         CFX_RenderDevice *pDevice)
    1485             :         : m_poParent(std::move(poParent)), device_(pDevice),
    1486             :           bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE),
    1487             :           bTemporaryEnableVectorForTextStroking(FALSE)
    1488             :     {
    1489             :     }
    1490             : 
    1491             :     virtual ~GDALPDFiumRenderDeviceDriver() = default;
    1492             : 
    1493             :     void SetEnableVector(int bFlag)
    1494             :     {
    1495             :         bEnableVector = bFlag;
    1496             :     }
    1497             : 
    1498             :     void SetEnableText(int bFlag)
    1499             :     {
    1500             :         bEnableText = bFlag;
    1501             :     }
    1502             : 
    1503             :     void SetEnableBitmap(int bFlag)
    1504             :     {
    1505             :         bEnableBitmap = bFlag;
    1506             :     }
    1507             : 
    1508             :     DeviceType GetDeviceType() const override
    1509             :     {
    1510             :         return m_poParent->GetDeviceType();
    1511             :     }
    1512             : 
    1513             :     int GetDeviceCaps(int caps_id) const override
    1514             :     {
    1515             :         return m_poParent->GetDeviceCaps(caps_id);
    1516             :     }
    1517             : 
    1518             :     void SaveState() override
    1519             :     {
    1520             :         m_poParent->SaveState();
    1521             :     }
    1522             : 
    1523             :     void RestoreState(bool bKeepSaved) override
    1524             :     {
    1525             :         m_poParent->RestoreState(bKeepSaved);
    1526             :     }
    1527             : 
    1528             :     void SetBaseClip(const FX_RECT &rect) override
    1529             :     {
    1530             :         m_poParent->SetBaseClip(rect);
    1531             :     }
    1532             : 
    1533             :     virtual bool
    1534             :     SetClip_PathFill(const CFX_Path &path, const CFX_Matrix *pObject2Device,
    1535             :                      const CFX_FillRenderOptions &fill_options) override
    1536             :     {
    1537             :         if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
    1538             :             return true;
    1539             :         return m_poParent->SetClip_PathFill(path, pObject2Device, fill_options);
    1540             :     }
    1541             : 
    1542             :     virtual bool
    1543             :     SetClip_PathStroke(const CFX_Path &path, const CFX_Matrix *pObject2Device,
    1544             :                        const CFX_GraphStateData *pGraphState) override
    1545             :     {
    1546             :         if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
    1547             :             return true;
    1548             :         return m_poParent->SetClip_PathStroke(path, pObject2Device,
    1549             :                                               pGraphState);
    1550             :     }
    1551             : 
    1552             :     virtual bool DrawPath(const CFX_Path &path,
    1553             :                           const CFX_Matrix *pObject2Device,
    1554             :                           const CFX_GraphStateData *pGraphState,
    1555             :                           uint32_t fill_color, uint32_t stroke_color,
    1556             :                           const CFX_FillRenderOptions &fill_options) override
    1557             :     {
    1558             :         if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
    1559             :             return true;
    1560             :         return m_poParent->DrawPath(path, pObject2Device, pGraphState,
    1561             :                                     fill_color, stroke_color, fill_options);
    1562             :     }
    1563             : 
    1564             :     bool FillRect(const FX_RECT &rect, uint32_t fill_color) override
    1565             :     {
    1566             :         return m_poParent->FillRect(rect, fill_color);
    1567             :     }
    1568             : 
    1569             :     virtual bool DrawCosmeticLine(const CFX_PointF &ptMoveTo,
    1570             :                                   const CFX_PointF &ptLineTo,
    1571             :                                   uint32_t color) override
    1572             :     {
    1573             :         if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
    1574             :             return TRUE;
    1575             :         return m_poParent->DrawCosmeticLine(ptMoveTo, ptLineTo, color);
    1576             :     }
    1577             : 
    1578             :     FX_RECT GetClipBox() const override
    1579             :     {
    1580             :         return m_poParent->GetClipBox();
    1581             :     }
    1582             : 
    1583             :     virtual bool GetDIBits(RetainPtr<CFX_DIBitmap> bitmap, int left,
    1584             :                            int top) const override
    1585             :     {
    1586             :         return m_poParent->GetDIBits(std::move(bitmap), left, top);
    1587             :     }
    1588             : 
    1589             :     RetainPtr<const CFX_DIBitmap> GetBackDrop() const override
    1590             :     {
    1591             :         return m_poParent->GetBackDrop();
    1592             :     }
    1593             : 
    1594             :     virtual bool SetDIBits(RetainPtr<const CFX_DIBBase> bitmap, uint32_t color,
    1595             :                            const FX_RECT &src_rect, int dest_left, int dest_top,
    1596             :                            BlendMode blend_type) override
    1597             :     {
    1598             :         if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
    1599             :             return true;
    1600             :         return m_poParent->SetDIBits(std::move(bitmap), color, src_rect,
    1601             :                                      dest_left, dest_top, blend_type);
    1602             :     }
    1603             : 
    1604             :     virtual bool StretchDIBits(RetainPtr<const CFX_DIBBase> bitmap,
    1605             :                                uint32_t color, int dest_left, int dest_top,
    1606             :                                int dest_width, int dest_height,
    1607             :                                const FX_RECT *pClipRect,
    1608             :                                const FXDIB_ResampleOptions &options,
    1609             :                                BlendMode blend_type) override
    1610             :     {
    1611             :         if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
    1612             :             return true;
    1613             :         return m_poParent->StretchDIBits(std::move(bitmap), color, dest_left,
    1614             :                                          dest_top, dest_width, dest_height,
    1615             :                                          pClipRect, options, blend_type);
    1616             :     }
    1617             : 
    1618             :     virtual StartResult StartDIBits(RetainPtr<const CFX_DIBBase> bitmap,
    1619             :                                     float alpha, uint32_t color,
    1620             :                                     const CFX_Matrix &matrix,
    1621             :                                     const FXDIB_ResampleOptions &options,
    1622             :                                     BlendMode blend_type) override
    1623             :     {
    1624             :         if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
    1625             :             return StartResult(Result::kSuccess, nullptr);
    1626             :         return m_poParent->StartDIBits(std::move(bitmap), alpha, color, matrix,
    1627             :                                        options, blend_type);
    1628             :     }
    1629             : 
    1630             :     virtual bool ContinueDIBits(CFX_AggImageRenderer *handle,
    1631             :                                 PauseIndicatorIface *pPause) override
    1632             :     {
    1633             :         return m_poParent->ContinueDIBits(handle, pPause);
    1634             :     }
    1635             : 
    1636             :     virtual bool DrawDeviceText(const pdfium::span<const TextCharPos> &pCharPos,
    1637             :                                 CFX_Font *pFont,
    1638             :                                 const CFX_Matrix &mtObject2Device,
    1639             :                                 float font_size, uint32_t color,
    1640             :                                 const CFX_TextRenderOptions &options) override
    1641             :     {
    1642             :         if (bEnableText)
    1643             :         {
    1644             :             // This is quite tricky. We call again the guy who called us
    1645             :             // (CFX_RenderDevice::DrawNormalText()) but we set a special flag to
    1646             :             // allow vector&raster operations so that the rendering will happen
    1647             :             // in the next phase
    1648             :             if (bTemporaryEnableVectorForTextStroking)
    1649             :                 return FALSE;  // this is the default behavior of the parent
    1650             :             bTemporaryEnableVectorForTextStroking = true;
    1651             :             bool bRet = device_->DrawNormalText(
    1652             :                 pCharPos, pFont, font_size, mtObject2Device, color, options);
    1653             :             bTemporaryEnableVectorForTextStroking = FALSE;
    1654             :             return bRet;
    1655             :         }
    1656             :         else
    1657             :             return true;  // pretend that we did the job
    1658             :     }
    1659             : 
    1660             :     int GetDriverType() const override
    1661             :     {
    1662             :         return m_poParent->GetDriverType();
    1663             :     }
    1664             : 
    1665             : #if defined(_SKIA_SUPPORT_)
    1666             :     virtual bool DrawShading(const CPDF_ShadingPattern &pattern,
    1667             :                              const CFX_Matrix &matrix, const FX_RECT &clip_rect,
    1668             :                              int alpha) override
    1669             :     {
    1670             :         if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
    1671             :             return true;
    1672             :         return m_poParent->DrawShading(pattern, matrix, clip_rect, alpha);
    1673             :     }
    1674             : #endif
    1675             : 
    1676             :     bool MultiplyAlpha(float alpha) override
    1677             :     {
    1678             :         return m_poParent->MultiplyAlpha(alpha);
    1679             :     }
    1680             : 
    1681             :     bool MultiplyAlphaMask(RetainPtr<const CFX_DIBitmap> mask) override
    1682             :     {
    1683             :         return m_poParent->MultiplyAlphaMask(std::move(mask));
    1684             :     }
    1685             : 
    1686             : #if defined(_SKIA_SUPPORT_)
    1687             :     virtual bool SetBitsWithMask(RetainPtr<const CFX_DIBBase> bitmap,
    1688             :                                  RetainPtr<const CFX_DIBBase> mask, int left,
    1689             :                                  int top, float alpha,
    1690             :                                  BlendMode blend_type) override
    1691             :     {
    1692             :         if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
    1693             :             return true;
    1694             :         return m_poParent->SetBitsWithMask(std::move(bitmap), std::move(mask),
    1695             :                                            left, top, alpha, blend_type);
    1696             :     }
    1697             : 
    1698             :     void SetGroupKnockout(bool group_knockout) override
    1699             :     {
    1700             :         m_poParent->SetGroupKnockout(group_knockout);
    1701             :     }
    1702             : #endif
    1703             : #if defined _SKIA_SUPPORT_ || defined _SKIA_SUPPORT_PATHS_
    1704             :     void Flush() override
    1705             :     {
    1706             :         return m_poParent->Flush();
    1707             :     }
    1708             : #endif
    1709             : };
    1710             : 
    1711             : /************************************************************************/
    1712             : /*                       PDFiumRenderPageBitmap()                       */
    1713             : /************************************************************************/
    1714             : 
    1715             : /* This method is a customization of RenderPageImpl()
    1716             :    from pdfium/fpdfsdk/cpdfsdk_renderpage.cpp to allow selection of which OGC/layer are
    1717             :    active. Thus it inherits the following license */
    1718             : // Copyright 2014-2020 PDFium Authors. All rights reserved.
    1719             : //
    1720             : // Redistribution and use in source and binary forms, with or without
    1721             : // modification, are permitted provided that the following conditions are
    1722             : // met:
    1723             : //
    1724             : //    * Redistributions of source code must retain the above copyright
    1725             : // notice, this list of conditions and the following disclaimer.
    1726             : //    * Redistributions in binary form must reproduce the above
    1727             : // copyright notice, this list of conditions and the following disclaimer
    1728             : // in the documentation and/or other materials provided with the
    1729             : // distribution.
    1730             : //    * Neither the name of Google Inc. nor the names of its
    1731             : // contributors may be used to endorse or promote products derived from
    1732             : // this software without specific prior written permission.
    1733             : //
    1734             : // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    1735             : // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    1736             : // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    1737             : // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    1738             : // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    1739             : // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    1740             : // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    1741             : // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    1742             : // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    1743             : // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    1744             : // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1745             : 
    1746             : static void myRenderPageImpl(PDFDataset *poDS, CPDF_PageRenderContext *pContext,
    1747             :                              CPDF_Page *pPage, const CFX_Matrix &matrix,
    1748             :                              const FX_RECT &clipping_rect, int flags,
    1749             :                              const FPDF_COLORSCHEME *color_scheme,
    1750             :                              bool bNeedToRestore, CPDFSDK_PauseAdapter *pause)
    1751             : {
    1752             :     if (!pContext->options_)
    1753             :         pContext->options_ = std::make_unique<CPDF_RenderOptions>();
    1754             : 
    1755             :     auto &options = pContext->options_->GetOptions();
    1756             :     options.bClearType = !!(flags & FPDF_LCD_TEXT);
    1757             :     options.bNoNativeText = !!(flags & FPDF_NO_NATIVETEXT);
    1758             :     options.bLimitedImageCache = !!(flags & FPDF_RENDER_LIMITEDIMAGECACHE);
    1759             :     options.bForceHalftone = !!(flags & FPDF_RENDER_FORCEHALFTONE);
    1760             :     options.bNoTextSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHTEXT);
    1761             :     options.bNoImageSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHIMAGE);
    1762             :     options.bNoPathSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHPATH);
    1763             : 
    1764             :     // Grayscale output
    1765             :     if (flags & FPDF_GRAYSCALE)
    1766             :         pContext->options_->SetColorMode(CPDF_RenderOptions::kGray);
    1767             : 
    1768             :     if (color_scheme)
    1769             :     {
    1770             :         pContext->options_->SetColorMode(CPDF_RenderOptions::kForcedColor);
    1771             :         SetColorFromScheme(color_scheme, pContext->options_.get());
    1772             :         options.bConvertFillToStroke = !!(flags & FPDF_CONVERT_FILL_TO_STROKE);
    1773             :     }
    1774             : 
    1775             :     const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING)
    1776             :                                                 ? CPDF_OCContext::kPrint
    1777             :                                                 : CPDF_OCContext::kView;
    1778             :     pContext->options_->SetOCContext(pdfium::MakeRetain<GDALPDFiumOCContext>(
    1779             :         poDS, pPage->GetDocument(), usage));
    1780             : 
    1781             :     pContext->device_->SaveState();
    1782             :     pContext->device_->SetBaseClip(clipping_rect);
    1783             :     pContext->device_->SetClip_Rect(clipping_rect);
    1784             :     pContext->context_ = std::make_unique<CPDF_RenderContext>(
    1785             :         pPage->GetDocument(), pPage->GetMutablePageResources(),
    1786             :         pPage->GetPageImageCache());
    1787             : 
    1788             :     pContext->context_->AppendLayer(pPage, matrix);
    1789             : 
    1790             :     if (flags & FPDF_ANNOT)
    1791             :     {
    1792             :         auto pOwnedList = std::make_unique<CPDF_AnnotList>(pPage);
    1793             :         CPDF_AnnotList *pList = pOwnedList.get();
    1794             :         pContext->annots_ = std::move(pOwnedList);
    1795             :         bool bPrinting =
    1796             :             pContext->device_->GetDeviceType() != DeviceType::kDisplay;
    1797             : 
    1798             :         // TODO(https://crbug.com/pdfium/993) - maybe pass true here.
    1799             :         const bool bShowWidget = false;
    1800             :         pList->DisplayAnnots(pContext->context_.get(), bPrinting, matrix,
    1801             :                              bShowWidget);
    1802             :     }
    1803             : 
    1804             :     pContext->renderer_ = std::make_unique<CPDF_ProgressiveRenderer>(
    1805             :         pContext->context_.get(), pContext->device_.get(),
    1806             :         pContext->options_.get());
    1807             :     pContext->renderer_->Start(pause);
    1808             :     if (bNeedToRestore)
    1809             :         pContext->device_->RestoreState(false);
    1810             : }
    1811             : 
    1812             : static void
    1813             : myRenderPageWithContext(PDFDataset *poDS, CPDF_PageRenderContext *pContext,
    1814             :                         FPDF_PAGE page, int start_x, int start_y, int size_x,
    1815             :                         int size_y, int rotate, int flags,
    1816             :                         const FPDF_COLORSCHEME *color_scheme,
    1817             :                         bool bNeedToRestore, CPDFSDK_PauseAdapter *pause)
    1818             : {
    1819             :     CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
    1820             :     if (!pPage)
    1821             :         return;
    1822             : 
    1823             :     const FX_RECT rect(start_x, start_y, start_x + size_x, start_y + size_y);
    1824             :     myRenderPageImpl(poDS, pContext, pPage,
    1825             :                      pPage->GetDisplayMatrixForRect(rect, rotate), rect, flags,
    1826             :                      color_scheme, bNeedToRestore, pause);
    1827             : }
    1828             : 
    1829             : class MyRenderDevice final : public CFX_RenderDevice
    1830             : {
    1831             : 
    1832             :   public:
    1833             :     // Substitution for CFX_DefaultRenderDevice::Attach
    1834             :     bool Attach(const RetainPtr<CFX_DIBitmap> &pBitmap, bool bRgbByteOrder,
    1835             :                 const RetainPtr<CFX_DIBitmap> &pBackdropBitmap,
    1836             :                 bool bGroupKnockout, const char *pszRenderingOptions);
    1837             : };
    1838             : 
    1839             : bool MyRenderDevice::Attach(const RetainPtr<CFX_DIBitmap> &pBitmap,
    1840             :                             bool bRgbByteOrder,
    1841             :                             const RetainPtr<CFX_DIBitmap> &pBackdropBitmap,
    1842             :                             bool bGroupKnockout,
    1843             :                             const char *pszRenderingOptions)
    1844             : {
    1845             :     SetBitmap(pBitmap);
    1846             : 
    1847             :     std::unique_ptr<RenderDeviceDriverIface> driver =
    1848             :         std::make_unique<pdfium::CFX_AggDeviceDriver>(
    1849             :             pBitmap, bRgbByteOrder, pBackdropBitmap, bGroupKnockout);
    1850             :     if (pszRenderingOptions != nullptr)
    1851             :     {
    1852             :         int bEnableVector = FALSE;
    1853             :         int bEnableText = FALSE;
    1854             :         int bEnableBitmap = FALSE;
    1855             : 
    1856             :         char **papszTokens = CSLTokenizeString2(pszRenderingOptions, " ,", 0);
    1857             :         for (int i = 0; papszTokens[i] != nullptr; i++)
    1858             :         {
    1859             :             if (EQUAL(papszTokens[i], "VECTOR"))
    1860             :                 bEnableVector = TRUE;
    1861             :             else if (EQUAL(papszTokens[i], "TEXT"))
    1862             :                 bEnableText = TRUE;
    1863             :             else if (EQUAL(papszTokens[i], "RASTER") ||
    1864             :                      EQUAL(papszTokens[i], "BITMAP"))
    1865             :                 bEnableBitmap = TRUE;
    1866             :             else
    1867             :             {
    1868             :                 CPLError(CE_Warning, CPLE_NotSupported,
    1869             :                          "Value %s is not a valid value for "
    1870             :                          "GDAL_PDF_RENDERING_OPTIONS",
    1871             :                          papszTokens[i]);
    1872             :             }
    1873             :         }
    1874             :         CSLDestroy(papszTokens);
    1875             : 
    1876             :         if (!bEnableVector || !bEnableText || !bEnableBitmap)
    1877             :         {
    1878             :             std::unique_ptr<GDALPDFiumRenderDeviceDriver> poGDALRDDriver =
    1879             :                 std::make_unique<GDALPDFiumRenderDeviceDriver>(
    1880             :                     std::move(driver), this);
    1881             :             poGDALRDDriver->SetEnableVector(bEnableVector);
    1882             :             poGDALRDDriver->SetEnableText(bEnableText);
    1883             :             poGDALRDDriver->SetEnableBitmap(bEnableBitmap);
    1884             :             driver = std::move(poGDALRDDriver);
    1885             :         }
    1886             :     }
    1887             : 
    1888             :     SetDeviceDriver(std::move(driver));
    1889             :     return true;
    1890             : }
    1891             : 
    1892             : void PDFDataset::PDFiumRenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page,
    1893             :                                         int start_x, int start_y, int size_x,
    1894             :                                         int size_y,
    1895             :                                         const char *pszRenderingOptions)
    1896             : {
    1897             :     const int rotate = 0;
    1898             :     const int flags = 0;
    1899             : 
    1900             :     if (!bitmap)
    1901             :         return;
    1902             : 
    1903             :     CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
    1904             :     if (!pPage)
    1905             :         return;
    1906             : 
    1907             :     auto pOwnedContext = std::make_unique<CPDF_PageRenderContext>();
    1908             :     CPDF_PageRenderContext *pContext = pOwnedContext.get();
    1909             :     CPDF_Page::RenderContextClearer clearer(pPage);
    1910             :     pPage->SetRenderContext(std::move(pOwnedContext));
    1911             : 
    1912             :     auto pOwnedDevice = std::make_unique<MyRenderDevice>();
    1913             :     auto pDevice = pOwnedDevice.get();
    1914             :     pContext->device_ = std::move(pOwnedDevice);
    1915             : 
    1916             :     RetainPtr<CFX_DIBitmap> pBitmap(CFXDIBitmapFromFPDFBitmap(bitmap));
    1917             : 
    1918             :     pDevice->Attach(pBitmap, !!(flags & FPDF_REVERSE_BYTE_ORDER), nullptr,
    1919             :                     false, pszRenderingOptions);
    1920             : 
    1921             :     myRenderPageWithContext(this, pContext, page, start_x, start_y, size_x,
    1922             :                             size_y, rotate, flags,
    1923             :                             /*color_scheme=*/nullptr,
    1924             :                             /*need_to_restore=*/true, /*pause=*/nullptr);
    1925             : 
    1926             : #ifdef _SKIA_SUPPORT_PATHS_
    1927             :     pDevice->Flush(true);
    1928             :     pBitmap->UnPreMultiply();
    1929             : #endif
    1930             : }
    1931             : 
    1932             : #endif /* HAVE_PDFIUM */
    1933             : 
    1934             : /************************************************************************/
    1935             : /*                             ReadPixels()                             */
    1936             : /************************************************************************/
    1937             : 
    1938          56 : CPLErr PDFDataset::ReadPixels(int nReqXOff, int nReqYOff, int nReqXSize,
    1939             :                               int nReqYSize, GSpacing nPixelSpace,
    1940             :                               GSpacing nLineSpace, GSpacing nBandSpace,
    1941             :                               GByte *pabyData)
    1942             : {
    1943          56 :     CPLErr eErr = CE_None;
    1944             :     const char *pszRenderingOptions =
    1945          56 :         GetOption(papszOpenOptions, "RENDERING_OPTIONS", nullptr);
    1946             : 
    1947             : #ifdef HAVE_POPPLER
    1948          56 :     if (m_bUseLib.test(PDFLIB_POPPLER))
    1949             :     {
    1950             :         SplashColor sColor;
    1951          56 :         sColor[0] = 255;
    1952          56 :         sColor[1] = 255;
    1953          56 :         sColor[2] = 255;
    1954             :         GDALPDFOutputDev *poSplashOut = new GDALPDFOutputDev(
    1955          56 :             (nBands < 4) ? splashModeRGB8 : splashModeXBGR8, 4, false,
    1956          56 :             (nBands < 4) ? sColor : nullptr);
    1957             : 
    1958          56 :         if (pszRenderingOptions != nullptr)
    1959             :         {
    1960           7 :             poSplashOut->SetEnableVector(FALSE);
    1961           7 :             poSplashOut->SetEnableText(FALSE);
    1962           7 :             poSplashOut->SetEnableBitmap(FALSE);
    1963             : 
    1964             :             char **papszTokens =
    1965           7 :                 CSLTokenizeString2(pszRenderingOptions, " ,", 0);
    1966          19 :             for (int i = 0; papszTokens[i] != nullptr; i++)
    1967             :             {
    1968          12 :                 if (EQUAL(papszTokens[i], "VECTOR"))
    1969           4 :                     poSplashOut->SetEnableVector(TRUE);
    1970           8 :                 else if (EQUAL(papszTokens[i], "TEXT"))
    1971           4 :                     poSplashOut->SetEnableText(TRUE);
    1972           4 :                 else if (EQUAL(papszTokens[i], "RASTER") ||
    1973           0 :                          EQUAL(papszTokens[i], "BITMAP"))
    1974           4 :                     poSplashOut->SetEnableBitmap(TRUE);
    1975             :                 else
    1976             :                 {
    1977           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    1978             :                              "Value %s is not a valid value for "
    1979             :                              "GDAL_PDF_RENDERING_OPTIONS",
    1980           0 :                              papszTokens[i]);
    1981             :                 }
    1982             :             }
    1983           7 :             CSLDestroy(papszTokens);
    1984             :         }
    1985             : 
    1986          56 :         PDFDoc *poDoc = m_poDocPoppler;
    1987          56 :         poSplashOut->startDoc(poDoc);
    1988             : 
    1989             :         // Note: Poppler 25.2 is certainly not the lowest version where we can
    1990             :         // avoid the hack.
    1991             : #if !(POPPLER_MAJOR_VERSION > 25 ||                                            \
    1992             :       (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2))
    1993             : #define USE_OPTCONTENT_HACK
    1994             : #endif
    1995             : 
    1996             : #ifdef USE_OPTCONTENT_HACK
    1997             :         /* EVIL: we modify a private member... */
    1998             :         /* poppler (at least 0.12 and 0.14 versions) don't render correctly */
    1999             :         /* some PDFs and display an error message 'Could not find a OCG with
    2000             :          * Ref' */
    2001             :         /* in those cases. This processing of optional content is an addition of
    2002             :          */
    2003             :         /* poppler in comparison to original xpdf, which hasn't the issue. All
    2004             :          * in */
    2005             :         /* all, nullifying optContent removes the error message and improves the
    2006             :          * rendering */
    2007          56 :         Catalog *poCatalog = poDoc->getCatalog();
    2008          56 :         OCGs *poOldOCGs = poCatalog->optContent;
    2009          56 :         if (!m_bUseOCG)
    2010          49 :             poCatalog->optContent = nullptr;
    2011             : #endif
    2012             :         try
    2013             :         {
    2014          56 :             poDoc->displayPageSlice(poSplashOut, m_iPage, m_dfDPI, m_dfDPI, 0,
    2015             :                                     TRUE, false, false, nReqXOff, nReqYOff,
    2016             :                                     nReqXSize, nReqYSize);
    2017             :         }
    2018           0 :         catch (const std::exception &e)
    2019             :         {
    2020           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2021           0 :                      "PDFDoc::displayPageSlice() failed with %s", e.what());
    2022             : 
    2023             : #ifdef USE_OPTCONTENT_HACK
    2024             :             /* Restore back */
    2025           0 :             poCatalog->optContent = poOldOCGs;
    2026             : #endif
    2027           0 :             delete poSplashOut;
    2028           0 :             return CE_Failure;
    2029             :         }
    2030             : 
    2031             : #ifdef USE_OPTCONTENT_HACK
    2032             :         /* Restore back */
    2033          56 :         poCatalog->optContent = poOldOCGs;
    2034             : #endif
    2035             : 
    2036          56 :         SplashBitmap *poBitmap = poSplashOut->getBitmap();
    2037         112 :         if (poBitmap->getWidth() != nReqXSize ||
    2038          56 :             poBitmap->getHeight() != nReqYSize)
    2039             :         {
    2040           0 :             CPLError(
    2041             :                 CE_Failure, CPLE_AppDefined,
    2042             :                 "Bitmap decoded size (%dx%d) doesn't match raster size (%dx%d)",
    2043             :                 poBitmap->getWidth(), poBitmap->getHeight(), nReqXSize,
    2044             :                 nReqYSize);
    2045           0 :             delete poSplashOut;
    2046           0 :             return CE_Failure;
    2047             :         }
    2048             : 
    2049          56 :         GByte *pabyDataR = pabyData;
    2050          56 :         GByte *pabyDataG = pabyData + nBandSpace;
    2051          56 :         GByte *pabyDataB = pabyData + 2 * nBandSpace;
    2052          56 :         GByte *pabyDataA = pabyData + 3 * nBandSpace;
    2053          56 :         GByte *pabySrc = poBitmap->getDataPtr();
    2054             :         GByte *pabyAlphaSrc =
    2055          56 :             reinterpret_cast<GByte *>(poBitmap->getAlphaPtr());
    2056             :         int i, j;
    2057       22919 :         for (j = 0; j < nReqYSize; j++)
    2058             :         {
    2059    20751600 :             for (i = 0; i < nReqXSize; i++)
    2060             :             {
    2061    20728800 :                 if (nBands < 4)
    2062             :                 {
    2063    20680200 :                     pabyDataR[i * nPixelSpace] = pabySrc[i * 3 + 0];
    2064    20680200 :                     pabyDataG[i * nPixelSpace] = pabySrc[i * 3 + 1];
    2065    20680200 :                     pabyDataB[i * nPixelSpace] = pabySrc[i * 3 + 2];
    2066             :                 }
    2067             :                 else
    2068             :                 {
    2069       48600 :                     pabyDataR[i * nPixelSpace] = pabySrc[i * 4 + 2];
    2070       48600 :                     pabyDataG[i * nPixelSpace] = pabySrc[i * 4 + 1];
    2071       48600 :                     pabyDataB[i * nPixelSpace] = pabySrc[i * 4 + 0];
    2072       48600 :                     pabyDataA[i * nPixelSpace] = pabyAlphaSrc[i];
    2073             :                 }
    2074             :             }
    2075       22863 :             pabyDataR += nLineSpace;
    2076       22863 :             pabyDataG += nLineSpace;
    2077       22863 :             pabyDataB += nLineSpace;
    2078       22863 :             pabyDataA += nLineSpace;
    2079       22863 :             pabyAlphaSrc += poBitmap->getAlphaRowSize();
    2080       22863 :             pabySrc += poBitmap->getRowSize();
    2081             :         }
    2082          56 :         delete poSplashOut;
    2083             :     }
    2084             : #endif  // HAVE_POPPLER
    2085             : 
    2086             : #ifdef HAVE_PODOFO
    2087             :     if (m_bUseLib.test(PDFLIB_PODOFO))
    2088             :     {
    2089             :         if (m_bPdfToPpmFailed)
    2090             :             return CE_Failure;
    2091             : 
    2092             :         if (pszRenderingOptions != nullptr &&
    2093             :             !EQUAL(pszRenderingOptions, "RASTER,VECTOR,TEXT"))
    2094             :         {
    2095             :             CPLError(CE_Warning, CPLE_NotSupported,
    2096             :                      "GDAL_PDF_RENDERING_OPTIONS only supported "
    2097             :                      "when PDF lib is Poppler.");
    2098             :         }
    2099             : 
    2100             :         CPLString osTmpFilename;
    2101             :         int nRet;
    2102             : 
    2103             : #ifdef notdef
    2104             :         int bUseSpawn =
    2105             :             CPLTestBool(CPLGetConfigOption("GDAL_PDF_USE_SPAWN", "YES"));
    2106             :         if (!bUseSpawn)
    2107             :         {
    2108             :             CPLString osCmd = CPLSPrintf(
    2109             :                 "pdftoppm -r %f -x %d -y %d -W %d -H %d -f %d -l %d \"%s\"",
    2110             :                 dfDPI, nReqXOff, nReqYOff, nReqXSize, nReqYSize, iPage, iPage,
    2111             :                 osFilename.c_str());
    2112             : 
    2113             :             if (!osUserPwd.empty())
    2114             :             {
    2115             :                 osCmd += " -upw \"";
    2116             :                 osCmd += osUserPwd;
    2117             :                 osCmd += "\"";
    2118             :             }
    2119             : 
    2120             :             CPLString osTmpFilenamePrefix = CPLGenerateTempFilenameSafe("pdf");
    2121             :             osTmpFilename =
    2122             :                 CPLSPrintf("%s-%d.ppm", osTmpFilenamePrefix.c_str(), iPage);
    2123             :             osCmd += CPLSPrintf(" \"%s\"", osTmpFilenamePrefix.c_str());
    2124             : 
    2125             :             CPLDebug("PDF", "Running '%s'", osCmd.c_str());
    2126             :             nRet = CPLSystem(nullptr, osCmd.c_str());
    2127             :         }
    2128             :         else
    2129             : #endif  // notdef
    2130             :         {
    2131             :             char **papszArgs = nullptr;
    2132             :             papszArgs = CSLAddString(papszArgs, "pdftoppm");
    2133             :             papszArgs = CSLAddString(papszArgs, "-r");
    2134             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%f", m_dfDPI));
    2135             :             papszArgs = CSLAddString(papszArgs, "-x");
    2136             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqXOff));
    2137             :             papszArgs = CSLAddString(papszArgs, "-y");
    2138             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqYOff));
    2139             :             papszArgs = CSLAddString(papszArgs, "-W");
    2140             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqXSize));
    2141             :             papszArgs = CSLAddString(papszArgs, "-H");
    2142             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqYSize));
    2143             :             papszArgs = CSLAddString(papszArgs, "-f");
    2144             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", m_iPage));
    2145             :             papszArgs = CSLAddString(papszArgs, "-l");
    2146             :             papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", m_iPage));
    2147             :             if (!m_osUserPwd.empty())
    2148             :             {
    2149             :                 papszArgs = CSLAddString(papszArgs, "-upw");
    2150             :                 papszArgs = CSLAddString(papszArgs, m_osUserPwd.c_str());
    2151             :             }
    2152             :             papszArgs = CSLAddString(papszArgs, m_osFilename.c_str());
    2153             : 
    2154             :             osTmpFilename = VSIMemGenerateHiddenFilename("pdf_temp.ppm");
    2155             :             VSILFILE *fpOut = VSIFOpenL(osTmpFilename, "wb");
    2156             :             if (fpOut != nullptr)
    2157             :             {
    2158             :                 nRet = CPLSpawn(papszArgs, nullptr, fpOut, FALSE);
    2159             :                 VSIFCloseL(fpOut);
    2160             :             }
    2161             :             else
    2162             :                 nRet = -1;
    2163             : 
    2164             :             CSLDestroy(papszArgs);
    2165             :         }
    2166             : 
    2167             :         if (nRet == 0)
    2168             :         {
    2169             :             auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    2170             :                 osTmpFilename, GDAL_OF_RASTER, nullptr, nullptr, nullptr));
    2171             :             if (poDS)
    2172             :             {
    2173             :                 if (poDS->GetRasterCount() == 3)
    2174             :                 {
    2175             :                     eErr = poDS->RasterIO(GF_Read, 0, 0, nReqXSize, nReqYSize,
    2176             :                                           pabyData, nReqXSize, nReqYSize,
    2177             :                                           GDT_UInt8, 3, nullptr, nPixelSpace,
    2178             :                                           nLineSpace, nBandSpace, nullptr);
    2179             :                 }
    2180             :             }
    2181             :         }
    2182             :         else
    2183             :         {
    2184             :             CPLDebug("PDF", "Ret code = %d", nRet);
    2185             :             m_bPdfToPpmFailed = true;
    2186             :             eErr = CE_Failure;
    2187             :         }
    2188             :         VSIUnlink(osTmpFilename);
    2189             :     }
    2190             : #endif  // HAVE_PODOFO
    2191             : #ifdef HAVE_PDFIUM
    2192             :     if (m_bUseLib.test(PDFLIB_PDFIUM))
    2193             :     {
    2194             :         if (!m_poPagePdfium)
    2195             :         {
    2196             :             return CE_Failure;
    2197             :         }
    2198             : 
    2199             :         // Pdfium does not support multithreading
    2200             :         CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex, PDFIUM_MUTEX_TIMEOUT);
    2201             : 
    2202             :         CPLCreateOrAcquireMutex(&(m_poPagePdfium->readMutex),
    2203             :                                 PDFIUM_MUTEX_TIMEOUT);
    2204             : 
    2205             :         // Parsing content required before rastering
    2206             :         // can takes too long for PDF with large number of objects/layers
    2207             :         m_poPagePdfium->page->ParseContent();
    2208             : 
    2209             :         FPDF_BITMAP bitmap =
    2210             :             FPDFBitmap_Create(nReqXSize, nReqYSize, nBands == 4 /*alpha*/);
    2211             :         // As coded now, FPDFBitmap_Create cannot allocate more than 1 GB
    2212             :         if (bitmap == nullptr)
    2213             :         {
    2214             :             // Release mutex - following code is thread-safe
    2215             :             CPLReleaseMutex(m_poPagePdfium->readMutex);
    2216             :             CPLReleaseMutex(g_oPdfiumReadMutex);
    2217             : 
    2218             : #ifdef notdef
    2219             :             // If the requested area is not too small, then try subdividing
    2220             :             if ((GIntBig)nReqXSize * nReqYSize * 4 > 1024 * 1024)
    2221             :             {
    2222             : #ifdef DEBUG
    2223             :                 CPLDebug(
    2224             :                     "PDF",
    2225             :                     "Subdividing PDFDataset::ReadPixels(%d, %d, %d, %d, "
    2226             :                     "scaleFactor=%d)",
    2227             :                     nReqXOff, nReqYOff, nReqXSize, nReqYSize,
    2228             :                     1 << ((PDFRasterBand *)GetRasterBand(1))->nResolutionLevel);
    2229             : #endif
    2230             :                 if (nReqXSize >= nReqYSize)
    2231             :                 {
    2232             :                     eErr = ReadPixels(nReqXOff, nReqYOff, nReqXSize / 2,
    2233             :                                       nReqYSize, nPixelSpace, nLineSpace,
    2234             :                                       nBandSpace, pabyData);
    2235             :                     if (eErr == CE_None)
    2236             :                     {
    2237             :                         eErr = ReadPixels(
    2238             :                             nReqXSize / 2, nReqYOff, nReqXSize - nReqXSize / 2,
    2239             :                             nReqYSize, nPixelSpace, nLineSpace, nBandSpace,
    2240             :                             pabyData + nPixelSpace * (nReqXSize / 2));
    2241             :                     }
    2242             :                 }
    2243             :                 else
    2244             :                 {
    2245             :                     eErr = ReadPixels(nReqXOff, nReqYOff, nReqXSize,
    2246             :                                       nReqYSize - nReqYSize / 2, nPixelSpace,
    2247             :                                       nLineSpace, nBandSpace, pabyData);
    2248             :                     if (eErr == CE_None)
    2249             :                     {
    2250             :                         eErr =
    2251             :                             ReadPixels(nReqXOff, nReqYSize / 2, nReqXSize,
    2252             :                                        nReqYSize - nReqYSize / 2, nPixelSpace,
    2253             :                                        nLineSpace, nBandSpace,
    2254             :                                        pabyData + nLineSpace * (nReqYSize / 2));
    2255             :                     }
    2256             :                 }
    2257             :                 return eErr;
    2258             :             }
    2259             : #endif
    2260             : 
    2261             :             CPLError(CE_Failure, CPLE_AppDefined,
    2262             :                      "FPDFBitmap_Create(%d,%d) failed", nReqXSize, nReqYSize);
    2263             : 
    2264             :             return CE_Failure;
    2265             :         }
    2266             :         // alpha is 0% which is transported to FF if not alpha
    2267             :         // Default background color is white
    2268             :         FPDF_DWORD color = 0x00FFFFFF;  // A,R,G,B
    2269             :         FPDFBitmap_FillRect(bitmap, 0, 0, nReqXSize, nReqYSize, color);
    2270             : 
    2271             : #ifdef DEBUG
    2272             :         // start_x, start_y, size_x, size_y, rotate, flags
    2273             :         CPLDebug("PDF",
    2274             :                  "PDFDataset::ReadPixels(%d, %d, %d, %d, scaleFactor=%d)",
    2275             :                  nReqXOff, nReqYOff, nReqXSize, nReqYSize,
    2276             :                  1 << cpl::down_cast<PDFRasterBand *>(GetRasterBand(1))
    2277             :                           ->nResolutionLevel);
    2278             : 
    2279             :         CPLDebug("PDF", "FPDF_RenderPageBitmap(%d, %d, %d, %d)", -nReqXOff,
    2280             :                  -nReqYOff, nRasterXSize, nRasterYSize);
    2281             : #endif
    2282             : 
    2283             :         // Part of PDF is render with -x, -y, page_width, page_height
    2284             :         // (not requested size!)
    2285             :         PDFiumRenderPageBitmap(
    2286             :             bitmap, FPDFPageFromIPDFPage(m_poPagePdfium->page), -nReqXOff,
    2287             :             -nReqYOff, nRasterXSize, nRasterYSize, pszRenderingOptions);
    2288             : 
    2289             :         int stride = FPDFBitmap_GetStride(bitmap);
    2290             :         const GByte *buffer =
    2291             :             reinterpret_cast<const GByte *>(FPDFBitmap_GetBuffer(bitmap));
    2292             : 
    2293             :         // Release mutex - following code is thread-safe
    2294             :         CPLReleaseMutex(m_poPagePdfium->readMutex);
    2295             :         CPLReleaseMutex(g_oPdfiumReadMutex);
    2296             : 
    2297             :         // Source data is B, G, R, unused.
    2298             :         // Destination data is R, G, B (,A if is alpha)
    2299             :         GByte *pabyDataR = pabyData;
    2300             :         GByte *pabyDataG = pabyData + 1 * nBandSpace;
    2301             :         GByte *pabyDataB = pabyData + 2 * nBandSpace;
    2302             :         GByte *pabyDataA = pabyData + 3 * nBandSpace;
    2303             :         // Copied from Poppler
    2304             :         int i, j;
    2305             :         for (j = 0; j < nReqYSize; j++)
    2306             :         {
    2307             :             for (i = 0; i < nReqXSize; i++)
    2308             :             {
    2309             :                 pabyDataR[i * nPixelSpace] = buffer[(i * 4) + 2];
    2310             :                 pabyDataG[i * nPixelSpace] = buffer[(i * 4) + 1];
    2311             :                 pabyDataB[i * nPixelSpace] = buffer[(i * 4) + 0];
    2312             :                 if (nBands == 4)
    2313             :                 {
    2314             :                     pabyDataA[i * nPixelSpace] = buffer[(i * 4) + 3];
    2315             :                 }
    2316             :             }
    2317             :             pabyDataR += nLineSpace;
    2318             :             pabyDataG += nLineSpace;
    2319             :             pabyDataB += nLineSpace;
    2320             :             pabyDataA += nLineSpace;
    2321             :             buffer += stride;
    2322             :         }
    2323             :         FPDFBitmap_Destroy(bitmap);
    2324             :     }
    2325             : #endif  // ~ HAVE_PDFIUM
    2326             : 
    2327          56 :     return eErr;
    2328             : }
    2329             : 
    2330             : /************************************************************************/
    2331             : /* ==================================================================== */
    2332             : /*                        PDFImageRasterBand                            */
    2333             : /* ==================================================================== */
    2334             : /************************************************************************/
    2335             : 
    2336             : class PDFImageRasterBand final : public PDFRasterBand
    2337             : {
    2338             :     friend class PDFDataset;
    2339             : 
    2340             :   public:
    2341             :     PDFImageRasterBand(PDFDataset *, int);
    2342             : 
    2343             :     CPLErr IReadBlock(int, int, void *) override;
    2344             : };
    2345             : 
    2346             : /************************************************************************/
    2347             : /*                         PDFImageRasterBand()                         */
    2348             : /************************************************************************/
    2349             : 
    2350           0 : PDFImageRasterBand::PDFImageRasterBand(PDFDataset *poDSIn, int nBandIn)
    2351           0 :     : PDFRasterBand(poDSIn, nBandIn, 0)
    2352             : {
    2353           0 : }
    2354             : 
    2355             : /************************************************************************/
    2356             : /*                             IReadBlock()                             */
    2357             : /************************************************************************/
    2358             : 
    2359           0 : CPLErr PDFImageRasterBand::IReadBlock(int /* nBlockXOff */, int nBlockYOff,
    2360             :                                       void *pImage)
    2361             : {
    2362           0 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
    2363           0 :     CPLAssert(poGDS->m_poImageObj != nullptr);
    2364             : 
    2365           0 :     if (!poGDS->m_bTried)
    2366             :     {
    2367           0 :         int nBands = (poGDS->nBands == 1) ? 1 : 3;
    2368           0 :         poGDS->m_bTried = true;
    2369           0 :         if (nBands == 3)
    2370             :         {
    2371           0 :             poGDS->m_pabyCachedData = static_cast<GByte *>(
    2372           0 :                 VSIMalloc3(nBands, nRasterXSize, nRasterYSize));
    2373           0 :             if (poGDS->m_pabyCachedData == nullptr)
    2374           0 :                 return CE_Failure;
    2375             :         }
    2376             : 
    2377           0 :         GDALPDFStream *poStream = poGDS->m_poImageObj->GetStream();
    2378           0 :         GByte *pabyStream = nullptr;
    2379             : 
    2380           0 :         if (poStream == nullptr ||
    2381           0 :             static_cast<size_t>(poStream->GetLength()) !=
    2382           0 :                 static_cast<size_t>(nBands) * nRasterXSize * nRasterYSize ||
    2383           0 :             (pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes())) ==
    2384             :                 nullptr)
    2385             :         {
    2386           0 :             VSIFree(poGDS->m_pabyCachedData);
    2387           0 :             poGDS->m_pabyCachedData = nullptr;
    2388           0 :             return CE_Failure;
    2389             :         }
    2390             : 
    2391           0 :         if (nBands == 3)
    2392             :         {
    2393             :             /* pixel interleaved to band interleaved */
    2394           0 :             for (size_t i = 0;
    2395           0 :                  i < static_cast<size_t>(nRasterXSize) * nRasterYSize; i++)
    2396             :             {
    2397           0 :                 poGDS->m_pabyCachedData[0 * static_cast<size_t>(nRasterXSize) *
    2398             :                                             nRasterYSize +
    2399           0 :                                         i] = pabyStream[3 * i + 0];
    2400           0 :                 poGDS->m_pabyCachedData[1 * static_cast<size_t>(nRasterXSize) *
    2401           0 :                                             nRasterYSize +
    2402           0 :                                         i] = pabyStream[3 * i + 1];
    2403           0 :                 poGDS->m_pabyCachedData[2 * static_cast<size_t>(nRasterXSize) *
    2404           0 :                                             nRasterYSize +
    2405           0 :                                         i] = pabyStream[3 * i + 2];
    2406             :             }
    2407           0 :             VSIFree(pabyStream);
    2408             :         }
    2409             :         else
    2410           0 :             poGDS->m_pabyCachedData = pabyStream;
    2411             :     }
    2412             : 
    2413           0 :     if (poGDS->m_pabyCachedData == nullptr)
    2414           0 :         return CE_Failure;
    2415             : 
    2416           0 :     if (nBand == 4)
    2417           0 :         memset(pImage, 255, nRasterXSize);
    2418             :     else
    2419           0 :         memcpy(pImage,
    2420           0 :                poGDS->m_pabyCachedData +
    2421           0 :                    static_cast<size_t>(nBand - 1) * nRasterXSize *
    2422           0 :                        nRasterYSize +
    2423           0 :                    static_cast<size_t>(nBlockYOff) * nRasterXSize,
    2424           0 :                nRasterXSize);
    2425             : 
    2426           0 :     return CE_None;
    2427             : }
    2428             : 
    2429             : /************************************************************************/
    2430             : /*                             PDFDataset()                             */
    2431             : /************************************************************************/
    2432             : 
    2433         219 : PDFDataset::PDFDataset(PDFDataset *poParentDSIn, int nXSize, int nYSize)
    2434         219 :     : m_bIsOvrDS(poParentDSIn != nullptr),
    2435             : #ifdef HAVE_PDFIUM
    2436             :       m_poDocPdfium(poParentDSIn ? poParentDSIn->m_poDocPdfium : nullptr),
    2437             :       m_poPagePdfium(poParentDSIn ? poParentDSIn->m_poPagePdfium : nullptr),
    2438             : #endif
    2439         219 :       m_bSetStyle(CPLTestBool(CPLGetConfigOption("OGR_PDF_SET_STYLE", "YES")))
    2440             : {
    2441         219 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2442         219 :     nRasterXSize = nXSize;
    2443         219 :     nRasterYSize = nYSize;
    2444         219 :     if (poParentDSIn)
    2445           0 :         m_bUseLib = poParentDSIn->m_bUseLib;
    2446             : 
    2447         219 :     InitMapOperators();
    2448         219 : }
    2449             : 
    2450             : /************************************************************************/
    2451             : /*                          IBuildOverviews()                           */
    2452             : /************************************************************************/
    2453             : 
    2454           1 : CPLErr PDFDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    2455             :                                    const int *panOverviewList, int nListBands,
    2456             :                                    const int *panBandList,
    2457             :                                    GDALProgressFunc pfnProgress,
    2458             :                                    void *pProgressData,
    2459             :                                    CSLConstList papszOptions)
    2460             : 
    2461             : {
    2462             :     /* -------------------------------------------------------------------- */
    2463             :     /*      In order for building external overviews to work properly we    */
    2464             :     /*      discard any concept of internal overviews when the user         */
    2465             :     /*      first requests to build external overviews.                     */
    2466             :     /* -------------------------------------------------------------------- */
    2467           1 :     if (!m_apoOvrDS.empty())
    2468             :     {
    2469           1 :         m_apoOvrDSBackup = std::move(m_apoOvrDS);
    2470           1 :         m_apoOvrDS.clear();
    2471             :     }
    2472             : 
    2473             :     // Prevents InitOverviews() to run
    2474           1 :     m_apoOvrDSBackup.emplace_back(nullptr);
    2475           1 :     const CPLErr eErr = GDALPamDataset::IBuildOverviews(
    2476             :         pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
    2477             :         pfnProgress, pProgressData, papszOptions);
    2478           1 :     m_apoOvrDSBackup.pop_back();
    2479           1 :     return eErr;
    2480             : }
    2481             : 
    2482             : /************************************************************************/
    2483             : /*                             PDFFreeDoc()                             */
    2484             : /************************************************************************/
    2485             : 
    2486             : #ifdef HAVE_POPPLER
    2487         233 : static void PDFFreeDoc(PDFDoc *poDoc)
    2488             : {
    2489         233 :     if (poDoc)
    2490             :     {
    2491             : #if POPPLER_MAJOR_VERSION < 26 ||                                              \
    2492             :     (POPPLER_MAJOR_VERSION == 26 && POPPLER_MINOR_VERSION < 2)
    2493             :         /* hack to avoid potential cross heap issues on Win32 */
    2494             :         /* str is the VSIPDFFileStream object passed in the constructor of
    2495             :          * PDFDoc */
    2496             :         // NOTE: This is potentially very dangerous. See comment in
    2497             :         // VSIPDFFileStream::FillBuffer() */
    2498         233 :         delete poDoc->str;
    2499         233 :         poDoc->str = nullptr;
    2500             : #endif
    2501             : 
    2502         233 :         delete poDoc;
    2503             :     }
    2504         233 : }
    2505             : #endif
    2506             : 
    2507             : /************************************************************************/
    2508             : /*                             GetCatalog()                             */
    2509             : /************************************************************************/
    2510             : 
    2511         464 : GDALPDFObject *PDFDataset::GetCatalog()
    2512             : {
    2513         464 :     if (m_poCatalogObject)
    2514         245 :         return m_poCatalogObject;
    2515             : 
    2516             : #ifdef HAVE_POPPLER
    2517         219 :     if (m_bUseLib.test(PDFLIB_POPPLER) && m_poDocPoppler)
    2518             :     {
    2519             :         m_poCatalogObjectPoppler =
    2520         219 :             std::make_unique<Object>(m_poDocPoppler->getXRef()->getCatalog());
    2521         219 :         if (!m_poCatalogObjectPoppler->isNull())
    2522         219 :             m_poCatalogObject =
    2523         219 :                 new GDALPDFObjectPoppler(m_poCatalogObjectPoppler.get(), FALSE);
    2524             :     }
    2525             : #endif
    2526             : 
    2527             : #ifdef HAVE_PODOFO
    2528             :     if (m_bUseLib.test(PDFLIB_PODOFO) && m_poDocPodofo)
    2529             :     {
    2530             :         int nCatalogNum = 0;
    2531             :         int nCatalogGen = 0;
    2532             :         VSILFILE *fp = VSIFOpenL(m_osFilename.c_str(), "rb");
    2533             :         if (fp != nullptr)
    2534             :         {
    2535             :             GDALPDFUpdateWriter oWriter(fp);
    2536             :             if (oWriter.ParseTrailerAndXRef())
    2537             :             {
    2538             :                 nCatalogNum = oWriter.GetCatalogNum().toInt();
    2539             :                 nCatalogGen = oWriter.GetCatalogGen();
    2540             :             }
    2541             :             oWriter.Close();
    2542             :         }
    2543             : 
    2544             :         PoDoFo::PdfObject *poCatalogPodofo =
    2545             :             m_poDocPodofo->GetObjects().GetObject(
    2546             :                 PoDoFo::PdfReference(nCatalogNum, nCatalogGen));
    2547             :         if (poCatalogPodofo)
    2548             :             m_poCatalogObject = new GDALPDFObjectPodofo(
    2549             :                 poCatalogPodofo, m_poDocPodofo->GetObjects());
    2550             :     }
    2551             : #endif
    2552             : 
    2553             : #ifdef HAVE_PDFIUM
    2554             :     if (m_bUseLib.test(PDFLIB_PDFIUM) && m_poDocPdfium)
    2555             :     {
    2556             :         RetainPtr<CPDF_Dictionary> catalog =
    2557             :             m_poDocPdfium->doc->GetMutableRoot();
    2558             :         if (catalog)
    2559             :             m_poCatalogObject = GDALPDFObjectPdfium::Build(catalog);
    2560             :     }
    2561             : #endif  // ~ HAVE_PDFIUM
    2562             : 
    2563         219 :     return m_poCatalogObject;
    2564             : }
    2565             : 
    2566             : /************************************************************************/
    2567             : /*                            ~PDFDataset()                             */
    2568             : /************************************************************************/
    2569             : 
    2570         438 : PDFDataset::~PDFDataset()
    2571             : {
    2572             : #ifdef HAVE_PDFIUM
    2573             :     m_apoOvrDS.clear();
    2574             :     m_apoOvrDSBackup.clear();
    2575             : #endif
    2576             : 
    2577         219 :     CPLFree(m_pabyCachedData);
    2578         219 :     m_pabyCachedData = nullptr;
    2579             : 
    2580         219 :     delete m_poNeatLine;
    2581         219 :     m_poNeatLine = nullptr;
    2582             : 
    2583             :     /* Collect data necessary to update */
    2584         219 :     int nNum = 0;
    2585         219 :     int nGen = 0;
    2586         219 :     GDALPDFDictionaryRW *poPageDictCopy = nullptr;
    2587         219 :     GDALPDFDictionaryRW *poCatalogDictCopy = nullptr;
    2588         219 :     if (m_poPageObj)
    2589             :     {
    2590         219 :         nNum = m_poPageObj->GetRefNum().toInt();
    2591         219 :         nGen = m_poPageObj->GetRefGen();
    2592         450 :         if (eAccess == GA_Update &&
    2593          12 :             (m_bProjDirty || m_bNeatLineDirty || m_bInfoDirty || m_bXMPDirty) &&
    2594         243 :             nNum != 0 && m_poPageObj != nullptr &&
    2595          12 :             m_poPageObj->GetType() == PDFObjectType_Dictionary)
    2596             :         {
    2597          12 :             poPageDictCopy = m_poPageObj->GetDictionary()->Clone();
    2598             : 
    2599          12 :             if (m_bXMPDirty)
    2600             :             {
    2601             :                 /* We need the catalog because it points to the XMP Metadata
    2602             :                  * object */
    2603           3 :                 GetCatalog();
    2604           6 :                 if (m_poCatalogObject &&
    2605           3 :                     m_poCatalogObject->GetType() == PDFObjectType_Dictionary)
    2606             :                     poCatalogDictCopy =
    2607           3 :                         m_poCatalogObject->GetDictionary()->Clone();
    2608             :             }
    2609             :         }
    2610             :     }
    2611             : 
    2612             :     /* Close document (and file descriptor) to be able to open it */
    2613             :     /* in read-write mode afterwards */
    2614         219 :     delete m_poPageObj;
    2615         219 :     m_poPageObj = nullptr;
    2616         219 :     delete m_poCatalogObject;
    2617         219 :     m_poCatalogObject = nullptr;
    2618             : #ifdef HAVE_POPPLER
    2619         219 :     if (m_bUseLib.test(PDFLIB_POPPLER))
    2620             :     {
    2621         219 :         m_poCatalogObjectPoppler.reset();
    2622         219 :         PDFFreeDoc(m_poDocPoppler);
    2623             :     }
    2624         219 :     m_poDocPoppler = nullptr;
    2625             : #endif
    2626             : #ifdef HAVE_PODOFO
    2627             :     if (m_bUseLib.test(PDFLIB_PODOFO))
    2628             :     {
    2629             :         delete m_poDocPodofo;
    2630             :     }
    2631             :     m_poDocPodofo = nullptr;
    2632             : #endif
    2633             : #ifdef HAVE_PDFIUM
    2634             :     if (!m_bIsOvrDS)
    2635             :     {
    2636             :         if (m_bUseLib.test(PDFLIB_PDFIUM))
    2637             :         {
    2638             :             UnloadPdfiumDocumentPage(&m_poDocPdfium, &m_poPagePdfium);
    2639             :         }
    2640             :     }
    2641             :     m_poDocPdfium = nullptr;
    2642             :     m_poPagePdfium = nullptr;
    2643             : #endif  // ~ HAVE_PDFIUM
    2644             : 
    2645         219 :     m_bHasLoadedLayers = true;
    2646         219 :     m_apoLayers.clear();
    2647             : 
    2648             :     /* Now do the update */
    2649         219 :     if (poPageDictCopy)
    2650             :     {
    2651          12 :         VSILFILE *fp = VSIFOpenL(m_osFilename, "rb+");
    2652          12 :         if (fp != nullptr)
    2653             :         {
    2654          24 :             GDALPDFUpdateWriter oWriter(fp);
    2655          12 :             if (oWriter.ParseTrailerAndXRef())
    2656             :             {
    2657          12 :                 if ((m_bProjDirty || m_bNeatLineDirty) &&
    2658             :                     poPageDictCopy != nullptr)
    2659           6 :                     oWriter.UpdateProj(this, m_dfDPI, poPageDictCopy,
    2660          12 :                                        GDALPDFObjectNum(nNum), nGen);
    2661             : 
    2662          12 :                 if (m_bInfoDirty)
    2663           3 :                     oWriter.UpdateInfo(this);
    2664             : 
    2665          12 :                 if (m_bXMPDirty && poCatalogDictCopy != nullptr)
    2666           3 :                     oWriter.UpdateXMP(this, poCatalogDictCopy);
    2667             :             }
    2668          12 :             oWriter.Close();
    2669             :         }
    2670             :         else
    2671             :         {
    2672           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2673             :                      "Cannot open %s in update mode", m_osFilename.c_str());
    2674             :         }
    2675             :     }
    2676         219 :     delete poPageDictCopy;
    2677         219 :     poPageDictCopy = nullptr;
    2678         219 :     delete poCatalogDictCopy;
    2679         219 :     poCatalogDictCopy = nullptr;
    2680             : 
    2681         219 :     if (m_nGCPCount > 0)
    2682             :     {
    2683           1 :         GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
    2684           1 :         CPLFree(m_pasGCPList);
    2685           1 :         m_pasGCPList = nullptr;
    2686           1 :         m_nGCPCount = 0;
    2687             :     }
    2688             : 
    2689         219 :     CleanupIntermediateResources();
    2690             : 
    2691             :     // Do that only after having destroyed Poppler objects
    2692         219 :     m_fp.reset();
    2693         438 : }
    2694             : 
    2695             : /************************************************************************/
    2696             : /*                             IRasterIO()                              */
    2697             : /************************************************************************/
    2698             : 
    2699        1671 : CPLErr PDFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2700             :                              int nXSize, int nYSize, void *pData, int nBufXSize,
    2701             :                              int nBufYSize, GDALDataType eBufType,
    2702             :                              int nBandCount, BANDMAP_TYPE panBandMap,
    2703             :                              GSpacing nPixelSpace, GSpacing nLineSpace,
    2704             :                              GSpacing nBandSpace,
    2705             :                              GDALRasterIOExtraArg *psExtraArg)
    2706             : {
    2707             :     // Try to pass the request to the most appropriate overview dataset.
    2708        1671 :     if (nBufXSize < nXSize && nBufYSize < nYSize)
    2709             :     {
    2710           0 :         int bTried = FALSE;
    2711           0 :         const CPLErr eErr = TryOverviewRasterIO(
    2712             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2713             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
    2714             :             nBandSpace, psExtraArg, &bTried);
    2715           0 :         if (bTried)
    2716           0 :             return eErr;
    2717             :     }
    2718             : 
    2719             :     int nBandBlockXSize, nBandBlockYSize;
    2720        1671 :     int bReadPixels = FALSE;
    2721        1671 :     GetRasterBand(1)->GetBlockSize(&nBandBlockXSize, &nBandBlockYSize);
    2722        3342 :     if (m_aiTiles.empty() && eRWFlag == GF_Read && nXSize == nBufXSize &&
    2723        1671 :         nYSize == nBufYSize &&
    2724        1671 :         (nBufXSize > nBandBlockXSize || nBufYSize > nBandBlockYSize) &&
    2725        3343 :         eBufType == GDT_UInt8 && nBandCount == nBands &&
    2726           1 :         IsAllBands(nBandCount, panBandMap))
    2727             :     {
    2728           1 :         bReadPixels = TRUE;
    2729             : #ifdef HAVE_PODOFO
    2730             :         if (m_bUseLib.test(PDFLIB_PODOFO) && nBands == 4)
    2731             :         {
    2732             :             bReadPixels = FALSE;
    2733             :         }
    2734             : #endif
    2735             :     }
    2736             : 
    2737        1671 :     if (bReadPixels)
    2738           1 :         return ReadPixels(nXOff, nYOff, nXSize, nYSize, nPixelSpace, nLineSpace,
    2739           1 :                           nBandSpace, static_cast<GByte *>(pData));
    2740             : 
    2741        1670 :     if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_UInt8)
    2742             :     {
    2743           0 :         m_bCacheBlocksForOtherBands = true;
    2744             :     }
    2745        1670 :     CPLErr eErr = GDALPamDataset::IRasterIO(
    2746             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2747             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    2748             :         psExtraArg);
    2749        1670 :     m_bCacheBlocksForOtherBands = false;
    2750        1670 :     return eErr;
    2751             : }
    2752             : 
    2753             : /************************************************************************/
    2754             : /*                             IRasterIO()                              */
    2755             : /************************************************************************/
    2756             : 
    2757       25684 : CPLErr PDFRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2758             :                                 int nXSize, int nYSize, void *pData,
    2759             :                                 int nBufXSize, int nBufYSize,
    2760             :                                 GDALDataType eBufType, GSpacing nPixelSpace,
    2761             :                                 GSpacing nLineSpace,
    2762             :                                 GDALRasterIOExtraArg *psExtraArg)
    2763             : {
    2764       25684 :     PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
    2765             : 
    2766             :     // Try to pass the request to the most appropriate overview dataset.
    2767       25684 :     if (nBufXSize < nXSize && nBufYSize < nYSize)
    2768             :     {
    2769           0 :         int bTried = FALSE;
    2770           0 :         const CPLErr eErr = TryOverviewRasterIO(
    2771             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2772             :             eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
    2773           0 :         if (bTried)
    2774           0 :             return eErr;
    2775             :     }
    2776             : 
    2777       25684 :     if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_UInt8)
    2778             :     {
    2779       20674 :         poGDS->m_bCacheBlocksForOtherBands = true;
    2780             :     }
    2781       25684 :     CPLErr eErr = GDALPamRasterBand::IRasterIO(
    2782             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2783             :         eBufType, nPixelSpace, nLineSpace, psExtraArg);
    2784       25684 :     poGDS->m_bCacheBlocksForOtherBands = false;
    2785       25684 :     return eErr;
    2786             : }
    2787             : 
    2788             : /************************************************************************/
    2789             : /*                      PDFDatasetErrorFunction()                       */
    2790             : /************************************************************************/
    2791             : 
    2792             : #ifdef HAVE_POPPLER
    2793             : 
    2794          29 : static void PDFDatasetErrorFunctionCommon(const CPLString &osError)
    2795             : {
    2796          29 :     if (strcmp(osError.c_str(), "Incorrect password") == 0)
    2797           5 :         return;
    2798             :     /* Reported on newer USGS GeoPDF */
    2799          24 :     if (strcmp(osError.c_str(),
    2800          24 :                "Couldn't find group for reference to set OFF") == 0)
    2801             :     {
    2802           0 :         CPLDebug("PDF", "%s", osError.c_str());
    2803           0 :         return;
    2804             :     }
    2805             : 
    2806          24 :     CPLError(CE_Failure, CPLE_AppDefined, "%s", osError.c_str());
    2807             : }
    2808             : 
    2809             : static int g_nPopplerErrors = 0;
    2810             : constexpr int MAX_POPPLER_ERRORS = 1000;
    2811             : 
    2812          29 : static void PDFDatasetErrorFunction(ErrorCategory /* eErrCategory */,
    2813             :                                     Goffset nPos, const char *pszMsg)
    2814             : {
    2815          29 :     if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
    2816             :     {
    2817             :         // If there are too many errors, then unregister ourselves and turn
    2818             :         // quiet error mode, as the error() function in poppler can spend
    2819             :         // significant time formatting an error message we won't emit...
    2820           0 :         setErrorCallback(nullptr);
    2821           0 :         globalParams->setErrQuiet(true);
    2822           0 :         return;
    2823             :     }
    2824             : 
    2825          29 :     g_nPopplerErrors++;
    2826          58 :     CPLString osError;
    2827             : 
    2828          29 :     if (nPos >= 0)
    2829             :         osError.Printf("Pos = " CPL_FRMT_GUIB ", ",
    2830           0 :                        static_cast<GUIntBig>(nPos));
    2831          29 :     osError += pszMsg;
    2832          29 :     PDFDatasetErrorFunctionCommon(osError);
    2833             : }
    2834             : #endif
    2835             : 
    2836             : /************************************************************************/
    2837             : /*               GDALPDFParseStreamContentOnlyDrawForm()                */
    2838             : /************************************************************************/
    2839             : 
    2840         204 : static CPLString GDALPDFParseStreamContentOnlyDrawForm(const char *pszContent)
    2841             : {
    2842         408 :     CPLString osToken;
    2843             :     char ch;
    2844         204 :     int nCurIdx = 0;
    2845         408 :     CPLString osCurrentForm;
    2846             : 
    2847             :     // CPLDebug("PDF", "content = %s", pszContent);
    2848             : 
    2849         736 :     while ((ch = *pszContent) != '\0')
    2850             :     {
    2851         736 :         if (ch == '%')
    2852             :         {
    2853             :             /* Skip comments until end-of-line */
    2854           0 :             while ((ch = *pszContent) != '\0')
    2855             :             {
    2856           0 :                 if (ch == '\r' || ch == '\n')
    2857             :                     break;
    2858           0 :                 pszContent++;
    2859             :             }
    2860           0 :             if (ch == 0)
    2861           0 :                 break;
    2862             :         }
    2863         736 :         else if (ch == ' ' || ch == '\r' || ch == '\n')
    2864             :         {
    2865         241 :             if (!osToken.empty())
    2866             :             {
    2867         241 :                 if (nCurIdx == 0 && osToken[0] == '/')
    2868             :                 {
    2869          37 :                     osCurrentForm = osToken.substr(1);
    2870          37 :                     nCurIdx++;
    2871             :                 }
    2872         204 :                 else if (nCurIdx == 1 && osToken == "Do")
    2873             :                 {
    2874           0 :                     nCurIdx++;
    2875             :                 }
    2876             :                 else
    2877             :                 {
    2878         204 :                     return "";
    2879             :                 }
    2880             :             }
    2881          37 :             osToken = "";
    2882             :         }
    2883             :         else
    2884         495 :             osToken += ch;
    2885         532 :         pszContent++;
    2886             :     }
    2887             : 
    2888           0 :     return osCurrentForm;
    2889             : }
    2890             : 
    2891             : /************************************************************************/
    2892             : /*                     GDALPDFParseStreamContent()                      */
    2893             : /************************************************************************/
    2894             : 
    2895             : typedef enum
    2896             : {
    2897             :     STATE_INIT,
    2898             :     STATE_AFTER_q,
    2899             :     STATE_AFTER_cm,
    2900             :     STATE_AFTER_Do
    2901             : } PDFStreamState;
    2902             : 
    2903             : /* This parser is reduced to understanding sequences that draw rasters, such as
    2904             :    :
    2905             :    q
    2906             :    scaleX 0 0 scaleY translateX translateY cm
    2907             :    /ImXXX Do
    2908             :    Q
    2909             : 
    2910             :    All other sequences will abort the parsing.
    2911             : 
    2912             :    Returns TRUE if the stream only contains images.
    2913             : */
    2914             : 
    2915         204 : static int GDALPDFParseStreamContent(const char *pszContent,
    2916             :                                      GDALPDFDictionary *poXObjectDict,
    2917             :                                      double *pdfDPI, int *pbDPISet,
    2918             :                                      int *pnBands,
    2919             :                                      std::vector<GDALPDFTileDesc> &asTiles,
    2920             :                                      int bAcceptRotationTerms)
    2921             : {
    2922         408 :     CPLString osToken;
    2923             :     char ch;
    2924         204 :     PDFStreamState nState = STATE_INIT;
    2925         204 :     int nCurIdx = 0;
    2926             :     double adfVals[6];
    2927         408 :     CPLString osCurrentImage;
    2928             : 
    2929         204 :     double dfDPI = DEFAULT_DPI;
    2930         204 :     *pbDPISet = FALSE;
    2931             : 
    2932       11463 :     while ((ch = *pszContent) != '\0')
    2933             :     {
    2934       11312 :         if (ch == '%')
    2935             :         {
    2936             :             /* Skip comments until end-of-line */
    2937           0 :             while ((ch = *pszContent) != '\0')
    2938             :             {
    2939           0 :                 if (ch == '\r' || ch == '\n')
    2940             :                     break;
    2941           0 :                 pszContent++;
    2942             :             }
    2943           0 :             if (ch == 0)
    2944           0 :                 break;
    2945             :         }
    2946       11312 :         else if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
    2947             :         {
    2948        3419 :             if (!osToken.empty())
    2949             :             {
    2950        3419 :                 if (nState == STATE_INIT)
    2951             :                 {
    2952         359 :                     if (osToken == "q")
    2953             :                     {
    2954         306 :                         nState = STATE_AFTER_q;
    2955         306 :                         nCurIdx = 0;
    2956             :                     }
    2957          53 :                     else if (osToken != "Q")
    2958          53 :                         return FALSE;
    2959             :                 }
    2960        3060 :                 else if (nState == STATE_AFTER_q)
    2961             :                 {
    2962        2142 :                     if (osToken == "q")
    2963             :                     {
    2964             :                         // ignore
    2965             :                     }
    2966        2142 :                     else if (nCurIdx < 6)
    2967             :                     {
    2968        1836 :                         adfVals[nCurIdx++] = CPLAtof(osToken);
    2969             :                     }
    2970         306 :                     else if (nCurIdx == 6 && osToken == "cm")
    2971             :                     {
    2972         306 :                         nState = STATE_AFTER_cm;
    2973         306 :                         nCurIdx = 0;
    2974             :                     }
    2975             :                     else
    2976           0 :                         return FALSE;
    2977             :                 }
    2978         918 :                 else if (nState == STATE_AFTER_cm)
    2979             :                 {
    2980         612 :                     if (nCurIdx == 0 && osToken[0] == '/')
    2981             :                     {
    2982         306 :                         osCurrentImage = osToken.substr(1);
    2983             :                     }
    2984         306 :                     else if (osToken == "Do")
    2985             :                     {
    2986         306 :                         nState = STATE_AFTER_Do;
    2987             :                     }
    2988             :                     else
    2989           0 :                         return FALSE;
    2990             :                 }
    2991         306 :                 else if (nState == STATE_AFTER_Do)
    2992             :                 {
    2993         306 :                     if (osToken == "Q")
    2994             :                     {
    2995             :                         GDALPDFObject *poImage =
    2996         306 :                             poXObjectDict->Get(osCurrentImage);
    2997         612 :                         if (poImage != nullptr &&
    2998         306 :                             poImage->GetType() == PDFObjectType_Dictionary)
    2999             :                         {
    3000             :                             GDALPDFTileDesc sTile;
    3001             :                             GDALPDFDictionary *poImageDict =
    3002         306 :                                 poImage->GetDictionary();
    3003         306 :                             GDALPDFObject *poWidth = poImageDict->Get("Width");
    3004             :                             GDALPDFObject *poHeight =
    3005         306 :                                 poImageDict->Get("Height");
    3006             :                             GDALPDFObject *poColorSpace =
    3007         306 :                                 poImageDict->Get("ColorSpace");
    3008         306 :                             GDALPDFObject *poSMask = poImageDict->Get("SMask");
    3009         612 :                             if (poColorSpace &&
    3010         306 :                                 poColorSpace->GetType() == PDFObjectType_Name)
    3011             :                             {
    3012         303 :                                 if (poColorSpace->GetName() == "DeviceRGB")
    3013             :                                 {
    3014         115 :                                     sTile.nBands = 3;
    3015         115 :                                     if (*pnBands < 3)
    3016          28 :                                         *pnBands = 3;
    3017             :                                 }
    3018         188 :                                 else if (poColorSpace->GetName() ==
    3019             :                                          "DeviceGray")
    3020             :                                 {
    3021         188 :                                     sTile.nBands = 1;
    3022         188 :                                     if (*pnBands < 1)
    3023         134 :                                         *pnBands = 1;
    3024             :                                 }
    3025             :                                 else
    3026           0 :                                     sTile.nBands = 0;
    3027             :                             }
    3028         306 :                             if (poSMask != nullptr)
    3029          94 :                                 *pnBands = 4;
    3030             : 
    3031         306 :                             if (poWidth && poHeight &&
    3032           0 :                                 ((bAcceptRotationTerms &&
    3033         306 :                                   adfVals[1] == -adfVals[2]) ||
    3034         306 :                                  (!bAcceptRotationTerms && adfVals[1] == 0.0 &&
    3035         306 :                                   adfVals[2] == 0.0)))
    3036             :                             {
    3037         306 :                                 double dfWidth = Get(poWidth);
    3038         306 :                                 double dfHeight = Get(poHeight);
    3039         306 :                                 double dfScaleX = adfVals[0];
    3040         306 :                                 double dfScaleY = adfVals[3];
    3041         306 :                                 if (dfWidth > 0 && dfHeight > 0 &&
    3042         306 :                                     dfScaleX > 0 && dfScaleY > 0 &&
    3043         306 :                                     dfWidth / dfScaleX * DEFAULT_DPI <
    3044         306 :                                         INT_MAX &&
    3045         306 :                                     dfHeight / dfScaleY * DEFAULT_DPI < INT_MAX)
    3046             :                                 {
    3047         612 :                                     double dfDPI_X = ROUND_IF_CLOSE(
    3048         306 :                                         dfWidth / dfScaleX * DEFAULT_DPI, 1e-3);
    3049         612 :                                     double dfDPI_Y = ROUND_IF_CLOSE(
    3050         306 :                                         dfHeight / dfScaleY * DEFAULT_DPI,
    3051             :                                         1e-3);
    3052             :                                     // CPLDebug("PDF", "Image %s, width = %.16g,
    3053             :                                     // height = %.16g, scaleX = %.16g, scaleY =
    3054             :                                     // %.16g --> DPI_X = %.16g, DPI_Y = %.16g",
    3055             :                                     //                 osCurrentImage.c_str(),
    3056             :                                     //                 dfWidth, dfHeight,
    3057             :                                     //                 dfScaleX, dfScaleY,
    3058             :                                     //                 dfDPI_X, dfDPI_Y);
    3059         306 :                                     if (dfDPI_X > dfDPI)
    3060          20 :                                         dfDPI = dfDPI_X;
    3061         306 :                                     if (dfDPI_Y > dfDPI)
    3062           0 :                                         dfDPI = dfDPI_Y;
    3063             : 
    3064         306 :                                     memcpy(&(sTile.adfCM), adfVals,
    3065             :                                            6 * sizeof(double));
    3066         306 :                                     sTile.poImage = poImage;
    3067         306 :                                     sTile.dfWidth = dfWidth;
    3068         306 :                                     sTile.dfHeight = dfHeight;
    3069         306 :                                     asTiles.push_back(sTile);
    3070             : 
    3071         306 :                                     *pbDPISet = TRUE;
    3072         306 :                                     *pdfDPI = dfDPI;
    3073             :                                 }
    3074             :                             }
    3075             :                         }
    3076         306 :                         nState = STATE_INIT;
    3077             :                     }
    3078             :                     else
    3079           0 :                         return FALSE;
    3080             :                 }
    3081             :             }
    3082        3366 :             osToken = "";
    3083             :         }
    3084             :         else
    3085        7893 :             osToken += ch;
    3086       11259 :         pszContent++;
    3087             :     }
    3088             : 
    3089         151 :     return TRUE;
    3090             : }
    3091             : 
    3092             : /************************************************************************/
    3093             : /*                          CheckTiledRaster()                          */
    3094             : /************************************************************************/
    3095             : 
    3096         163 : int PDFDataset::CheckTiledRaster()
    3097             : {
    3098             :     size_t i;
    3099         163 :     int l_nBlockXSize = 0;
    3100         163 :     int l_nBlockYSize = 0;
    3101         163 :     const double dfUserUnit = m_dfDPI * USER_UNIT_IN_INCH;
    3102             : 
    3103             :     /* First pass : check that all tiles have same DPI, */
    3104             :     /* are contained entirely in the raster size, */
    3105             :     /* and determine the block size */
    3106         461 :     for (i = 0; i < m_asTiles.size(); i++)
    3107             :     {
    3108         304 :         double dfDrawWidth = m_asTiles[i].adfCM[0] * dfUserUnit;
    3109         304 :         double dfDrawHeight = m_asTiles[i].adfCM[3] * dfUserUnit;
    3110         304 :         double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
    3111         304 :         double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
    3112         304 :         int nX = static_cast<int>(dfX + 0.1);
    3113         304 :         int nY = static_cast<int>(dfY + 0.1);
    3114         304 :         int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
    3115         304 :         int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
    3116             : 
    3117         304 :         GDALPDFDictionary *poImageDict = m_asTiles[i].poImage->GetDictionary();
    3118             :         GDALPDFObject *poBitsPerComponent =
    3119         304 :             poImageDict->Get("BitsPerComponent");
    3120         304 :         GDALPDFObject *poColorSpace = poImageDict->Get("ColorSpace");
    3121         304 :         GDALPDFObject *poFilter = poImageDict->Get("Filter");
    3122             : 
    3123             :         /* Podofo cannot uncompress JPEG2000 streams */
    3124         304 :         if (m_bUseLib.test(PDFLIB_PODOFO) && poFilter != nullptr &&
    3125         304 :             poFilter->GetType() == PDFObjectType_Name &&
    3126           0 :             poFilter->GetName() == "JPXDecode")
    3127             :         {
    3128           0 :             CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
    3129             :                      static_cast<int>(i));
    3130           0 :             return FALSE;
    3131             :         }
    3132             : 
    3133         304 :         if (poBitsPerComponent == nullptr || Get(poBitsPerComponent) != 8 ||
    3134         304 :             poColorSpace == nullptr ||
    3135        1097 :             poColorSpace->GetType() != PDFObjectType_Name ||
    3136         489 :             (poColorSpace->GetName() != "DeviceRGB" &&
    3137         188 :              poColorSpace->GetName() != "DeviceGray"))
    3138             :         {
    3139           3 :             CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
    3140             :                      static_cast<int>(i));
    3141           3 :             return FALSE;
    3142             :         }
    3143             : 
    3144         301 :         if (fabs(dfDrawWidth - m_asTiles[i].dfWidth) > 1e-2 ||
    3145         298 :             fabs(dfDrawHeight - m_asTiles[i].dfHeight) > 1e-2 ||
    3146         298 :             fabs(nWidth - m_asTiles[i].dfWidth) > 1e-8 ||
    3147         298 :             fabs(nHeight - m_asTiles[i].dfHeight) > 1e-8 ||
    3148         298 :             fabs(nX - dfX) > 1e-1 || fabs(nY - dfY) > 1e-1 || nX < 0 ||
    3149         599 :             nY < 0 || nX + nWidth > nRasterXSize || nY >= nRasterYSize)
    3150             :         {
    3151           3 :             CPLDebug("PDF", "Tile %d : %f %f %f %f %f %f", static_cast<int>(i),
    3152           3 :                      dfX, dfY, dfDrawWidth, dfDrawHeight, m_asTiles[i].dfWidth,
    3153           3 :                      m_asTiles[i].dfHeight);
    3154           3 :             return FALSE;
    3155             :         }
    3156         298 :         if (l_nBlockXSize == 0 && l_nBlockYSize == 0 && nX == 0 && nY != 0)
    3157             :         {
    3158           9 :             l_nBlockXSize = nWidth;
    3159           9 :             l_nBlockYSize = nHeight;
    3160             :         }
    3161             :     }
    3162         157 :     if (l_nBlockXSize <= 0 || l_nBlockYSize <= 0 || l_nBlockXSize > 2048 ||
    3163             :         l_nBlockYSize > 2048)
    3164         148 :         return FALSE;
    3165             : 
    3166           9 :     int nXBlocks = DIV_ROUND_UP(nRasterXSize, l_nBlockXSize);
    3167           9 :     int nYBlocks = DIV_ROUND_UP(nRasterYSize, l_nBlockYSize);
    3168             : 
    3169             :     /* Second pass to determine that all tiles are properly aligned on block
    3170             :      * size */
    3171         159 :     for (i = 0; i < m_asTiles.size(); i++)
    3172             :     {
    3173         150 :         double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
    3174         150 :         double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
    3175         150 :         int nX = static_cast<int>(dfX + 0.1);
    3176         150 :         int nY = static_cast<int>(dfY + 0.1);
    3177         150 :         int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
    3178         150 :         int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
    3179         150 :         int bOK = TRUE;
    3180         150 :         int nBlockXOff = nX / l_nBlockXSize;
    3181         150 :         if ((nX % l_nBlockXSize) != 0)
    3182           0 :             bOK = FALSE;
    3183         150 :         if (nBlockXOff < nXBlocks - 1 && nWidth != l_nBlockXSize)
    3184           0 :             bOK = FALSE;
    3185         150 :         if (nBlockXOff == nXBlocks - 1 && nX + nWidth != nRasterXSize)
    3186           0 :             bOK = FALSE;
    3187             : 
    3188         150 :         if (nY > 0 && nHeight != l_nBlockYSize)
    3189           0 :             bOK = FALSE;
    3190         150 :         if (nY == 0 && nHeight != nRasterYSize - (nYBlocks - 1) * l_nBlockYSize)
    3191           0 :             bOK = FALSE;
    3192             : 
    3193         150 :         if (!bOK)
    3194             :         {
    3195           0 :             CPLDebug("PDF", "Tile %d : %d %d %d %d", static_cast<int>(i), nX,
    3196             :                      nY, nWidth, nHeight);
    3197           0 :             return FALSE;
    3198             :         }
    3199             :     }
    3200             : 
    3201             :     /* Third pass to set the aiTiles array */
    3202           9 :     m_aiTiles.resize(static_cast<size_t>(nXBlocks) * nYBlocks, -1);
    3203         159 :     for (i = 0; i < m_asTiles.size(); i++)
    3204             :     {
    3205         150 :         double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
    3206         150 :         double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
    3207         150 :         int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
    3208         150 :         int nX = static_cast<int>(dfX + 0.1);
    3209         150 :         int nY = nRasterYSize - (static_cast<int>(dfY + 0.1) + nHeight);
    3210         150 :         int nBlockXOff = nX / l_nBlockXSize;
    3211         150 :         int nBlockYOff = nY / l_nBlockYSize;
    3212         150 :         m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff] = static_cast<int>(i);
    3213             :     }
    3214             : 
    3215           9 :     this->m_nBlockXSize = l_nBlockXSize;
    3216           9 :     this->m_nBlockYSize = l_nBlockYSize;
    3217             : 
    3218           9 :     return TRUE;
    3219             : }
    3220             : 
    3221             : /************************************************************************/
    3222             : /*                        GuessDPIAndBandCount()                        */
    3223             : /************************************************************************/
    3224             : 
    3225         219 : void PDFDataset::GuessDPIAndBandCount(GDALPDFDictionary *poPageDict,
    3226             :                                       double &dfDPI, int &nBandsGuessed)
    3227             : {
    3228             :     /* Try to get a better value from the images that are drawn */
    3229             :     /* Very simplistic logic. Will only work for raster only PDF */
    3230             : 
    3231         219 :     GDALPDFObject *poContents = poPageDict->Get("Contents");
    3232         219 :     if (poContents != nullptr && poContents->GetType() == PDFObjectType_Array)
    3233             :     {
    3234           1 :         GDALPDFArray *poContentsArray = poContents->GetArray();
    3235           1 :         if (poContentsArray->GetLength() == 1)
    3236             :         {
    3237           1 :             poContents = poContentsArray->Get(0);
    3238             :         }
    3239             :     }
    3240             : 
    3241         219 :     GDALPDFObject *poXObject = poPageDict->LookupObject("Resources.XObject");
    3242         437 :     if (poContents != nullptr &&
    3243         218 :         poContents->GetType() == PDFObjectType_Dictionary &&
    3244         437 :         poXObject != nullptr &&
    3245         205 :         poXObject->GetType() == PDFObjectType_Dictionary)
    3246             :     {
    3247         205 :         GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
    3248         205 :         GDALPDFDictionary *poContentDict = poXObjectDict;
    3249         205 :         GDALPDFStream *poPageStream = poContents->GetStream();
    3250         205 :         if (poPageStream != nullptr)
    3251             :         {
    3252         204 :             char *pszContent = nullptr;
    3253         204 :             constexpr int64_t MAX_LENGTH = 10 * 1000 * 1000;
    3254         204 :             const int64_t nLength = poPageStream->GetLength(MAX_LENGTH);
    3255         204 :             int bResetTiles = FALSE;
    3256         204 :             double dfScaleDPI = 1.0;
    3257             : 
    3258         204 :             if (nLength < MAX_LENGTH)
    3259             :             {
    3260         408 :                 CPLString osForm;
    3261         204 :                 pszContent = poPageStream->GetBytes();
    3262         204 :                 if (pszContent != nullptr)
    3263             :                 {
    3264             : #ifdef DEBUG
    3265             :                     const char *pszDumpStream =
    3266         204 :                         CPLGetConfigOption("PDF_DUMP_STREAM", nullptr);
    3267         204 :                     if (pszDumpStream != nullptr)
    3268             :                     {
    3269           0 :                         VSILFILE *fpDump = VSIFOpenL(pszDumpStream, "wb");
    3270           0 :                         if (fpDump)
    3271             :                         {
    3272           0 :                             VSIFWriteL(pszContent, 1, static_cast<int>(nLength),
    3273             :                                        fpDump);
    3274           0 :                             VSIFCloseL(fpDump);
    3275             :                         }
    3276             :                     }
    3277             : #endif  // DEBUG
    3278         204 :                     osForm = GDALPDFParseStreamContentOnlyDrawForm(pszContent);
    3279         204 :                     if (osForm.empty())
    3280             :                     {
    3281             :                         /* Special case for USGS Topo PDF, like
    3282             :                              * CA_Hollywood_20090811_OM_geo.pdf */
    3283         204 :                         const char *pszOGCDo = strstr(pszContent, " /XO1 Do");
    3284         204 :                         if (pszOGCDo)
    3285             :                         {
    3286           0 :                             const char *pszcm = strstr(pszContent, " cm ");
    3287           0 :                             if (pszcm != nullptr && pszcm < pszOGCDo)
    3288             :                             {
    3289           0 :                                 const char *pszNextcm = strstr(pszcm + 2, "cm");
    3290           0 :                                 if (pszNextcm == nullptr ||
    3291             :                                     pszNextcm > pszOGCDo)
    3292             :                                 {
    3293           0 :                                     const char *pszIter = pszcm;
    3294           0 :                                     while (pszIter > pszContent)
    3295             :                                     {
    3296           0 :                                         if ((*pszIter >= '0' &&
    3297           0 :                                              *pszIter <= '9') ||
    3298           0 :                                             *pszIter == '-' ||
    3299           0 :                                             *pszIter == '.' || *pszIter == ' ')
    3300           0 :                                             pszIter--;
    3301             :                                         else
    3302             :                                         {
    3303           0 :                                             pszIter++;
    3304           0 :                                             break;
    3305             :                                         }
    3306             :                                     }
    3307           0 :                                     CPLString oscm(pszIter);
    3308           0 :                                     oscm.resize(pszcm - pszIter);
    3309             :                                     char **papszTokens =
    3310           0 :                                         CSLTokenizeString(oscm);
    3311           0 :                                     double dfScaleX = -1.0;
    3312           0 :                                     double dfScaleY = -2.0;
    3313           0 :                                     if (CSLCount(papszTokens) == 6)
    3314             :                                     {
    3315           0 :                                         dfScaleX = CPLAtof(papszTokens[0]);
    3316           0 :                                         dfScaleY = CPLAtof(papszTokens[3]);
    3317             :                                     }
    3318           0 :                                     CSLDestroy(papszTokens);
    3319           0 :                                     if (dfScaleX == dfScaleY && dfScaleX > 0.0)
    3320             :                                     {
    3321           0 :                                         osForm = "XO1";
    3322           0 :                                         bResetTiles = TRUE;
    3323           0 :                                         dfScaleDPI = 1.0 / dfScaleX;
    3324             :                                     }
    3325           0 :                                 }
    3326             :                             }
    3327             :                             else
    3328             :                             {
    3329           0 :                                 osForm = "XO1";
    3330           0 :                                 bResetTiles = TRUE;
    3331             :                             }
    3332             :                         }
    3333             :                         /* Special case for USGS Topo PDF, like
    3334             :                              * CA_Sacramento_East_20120308_TM_geo.pdf */
    3335             :                         else
    3336             :                         {
    3337             :                             CPLString osOCG =
    3338         408 :                                 FindLayerOCG(poPageDict, "Orthoimage");
    3339         204 :                             if (!osOCG.empty())
    3340             :                             {
    3341             :                                 const char *pszBDCLookup =
    3342           0 :                                     CPLSPrintf("/OC /%s BDC", osOCG.c_str());
    3343             :                                 const char *pszBDC =
    3344           0 :                                     strstr(pszContent, pszBDCLookup);
    3345           0 :                                 if (pszBDC != nullptr)
    3346             :                                 {
    3347           0 :                                     const char *pszIter =
    3348           0 :                                         pszBDC + strlen(pszBDCLookup);
    3349           0 :                                     while (*pszIter != '\0')
    3350             :                                     {
    3351           0 :                                         if (*pszIter == 13 || *pszIter == 10 ||
    3352           0 :                                             *pszIter == ' ' || *pszIter == 'q')
    3353           0 :                                             pszIter++;
    3354             :                                         else
    3355             :                                             break;
    3356             :                                     }
    3357           0 :                                     if (STARTS_WITH(pszIter,
    3358             :                                                     "1 0 0 1 0 0 cm\n"))
    3359           0 :                                         pszIter += strlen("1 0 0 1 0 0 cm\n");
    3360           0 :                                     if (*pszIter == '/')
    3361             :                                     {
    3362           0 :                                         pszIter++;
    3363             :                                         const char *pszDo =
    3364           0 :                                             strstr(pszIter, " Do");
    3365           0 :                                         if (pszDo != nullptr)
    3366             :                                         {
    3367           0 :                                             osForm = pszIter;
    3368           0 :                                             osForm.resize(pszDo - pszIter);
    3369           0 :                                             bResetTiles = TRUE;
    3370             :                                         }
    3371             :                                     }
    3372             :                                 }
    3373             :                             }
    3374             :                         }
    3375             :                     }
    3376             :                 }
    3377             : 
    3378         204 :                 if (!osForm.empty())
    3379             :                 {
    3380           0 :                     CPLFree(pszContent);
    3381           0 :                     pszContent = nullptr;
    3382             : 
    3383           0 :                     GDALPDFObject *poObjForm = poXObjectDict->Get(osForm);
    3384           0 :                     if (poObjForm != nullptr &&
    3385           0 :                         poObjForm->GetType() == PDFObjectType_Dictionary &&
    3386           0 :                         (poPageStream = poObjForm->GetStream()) != nullptr)
    3387             :                     {
    3388             :                         GDALPDFDictionary *poObjFormDict =
    3389           0 :                             poObjForm->GetDictionary();
    3390             :                         GDALPDFObject *poSubtype =
    3391           0 :                             poObjFormDict->Get("Subtype");
    3392           0 :                         if (poSubtype != nullptr &&
    3393           0 :                             poSubtype->GetType() == PDFObjectType_Name &&
    3394           0 :                             poSubtype->GetName() == "Form")
    3395             :                         {
    3396           0 :                             if (poPageStream->GetLength(MAX_LENGTH) <
    3397             :                                 MAX_LENGTH)
    3398             :                             {
    3399           0 :                                 pszContent = poPageStream->GetBytes();
    3400             : 
    3401             :                                 GDALPDFObject *poXObject2 =
    3402           0 :                                     poObjFormDict->LookupObject(
    3403             :                                         "Resources.XObject");
    3404           0 :                                 if (poXObject2 != nullptr &&
    3405           0 :                                     poXObject2->GetType() ==
    3406             :                                         PDFObjectType_Dictionary)
    3407           0 :                                     poContentDict = poXObject2->GetDictionary();
    3408             :                             }
    3409             :                         }
    3410             :                     }
    3411             :                 }
    3412             :             }
    3413             : 
    3414         204 :             if (pszContent != nullptr)
    3415             :             {
    3416         204 :                 int bDPISet = FALSE;
    3417             : 
    3418         204 :                 const char *pszContentToParse = pszContent;
    3419         204 :                 if (bResetTiles)
    3420             :                 {
    3421           0 :                     while (*pszContentToParse != '\0')
    3422             :                     {
    3423           0 :                         if (*pszContentToParse == 13 ||
    3424           0 :                             *pszContentToParse == 10 ||
    3425           0 :                             *pszContentToParse == ' ' ||
    3426           0 :                             (*pszContentToParse >= '0' &&
    3427           0 :                              *pszContentToParse <= '9') ||
    3428           0 :                             *pszContentToParse == '.' ||
    3429           0 :                             *pszContentToParse == '-' ||
    3430           0 :                             *pszContentToParse == 'l' ||
    3431           0 :                             *pszContentToParse == 'm' ||
    3432           0 :                             *pszContentToParse == 'n' ||
    3433           0 :                             *pszContentToParse == 'W')
    3434           0 :                             pszContentToParse++;
    3435             :                         else
    3436             :                             break;
    3437             :                     }
    3438             :                 }
    3439             : 
    3440         204 :                 GDALPDFParseStreamContent(pszContentToParse, poContentDict,
    3441             :                                           &dfDPI, &bDPISet, &nBandsGuessed,
    3442         204 :                                           m_asTiles, bResetTiles);
    3443         204 :                 CPLFree(pszContent);
    3444         204 :                 if (bDPISet)
    3445             :                 {
    3446         165 :                     dfDPI *= dfScaleDPI;
    3447             : 
    3448         165 :                     CPLDebug("PDF", "DPI guessed from contents stream = %.16g",
    3449             :                              dfDPI);
    3450         165 :                     SetMetadataItem("DPI", CPLSPrintf("%.16g", dfDPI));
    3451         165 :                     if (bResetTiles)
    3452           0 :                         m_asTiles.resize(0);
    3453             :                 }
    3454             :                 else
    3455          39 :                     m_asTiles.resize(0);
    3456             :             }
    3457             :         }
    3458             :     }
    3459             : 
    3460         219 :     GDALPDFObject *poUserUnit = nullptr;
    3461         402 :     if ((poUserUnit = poPageDict->Get("UserUnit")) != nullptr &&
    3462         183 :         (poUserUnit->GetType() == PDFObjectType_Int ||
    3463          12 :          poUserUnit->GetType() == PDFObjectType_Real))
    3464             :     {
    3465         183 :         dfDPI = ROUND_IF_CLOSE(Get(poUserUnit) * DEFAULT_DPI, 1e-5);
    3466         183 :         CPLDebug("PDF", "Found UserUnit in Page --> DPI = %.16g", dfDPI);
    3467             :     }
    3468         219 : }
    3469             : 
    3470             : /************************************************************************/
    3471             : /*                              FindXMP()                               */
    3472             : /************************************************************************/
    3473             : 
    3474           0 : void PDFDataset::FindXMP(GDALPDFObject *poObj)
    3475             : {
    3476           0 :     if (poObj->GetType() != PDFObjectType_Dictionary)
    3477           0 :         return;
    3478             : 
    3479           0 :     GDALPDFDictionary *poDict = poObj->GetDictionary();
    3480           0 :     GDALPDFObject *poType = poDict->Get("Type");
    3481           0 :     GDALPDFObject *poSubtype = poDict->Get("Subtype");
    3482           0 :     if (poType == nullptr || poType->GetType() != PDFObjectType_Name ||
    3483           0 :         poType->GetName() != "Metadata" || poSubtype == nullptr ||
    3484           0 :         poSubtype->GetType() != PDFObjectType_Name ||
    3485           0 :         poSubtype->GetName() != "XML")
    3486             :     {
    3487           0 :         return;
    3488             :     }
    3489             : 
    3490           0 :     GDALPDFStream *poStream = poObj->GetStream();
    3491           0 :     if (poStream == nullptr)
    3492           0 :         return;
    3493             : 
    3494           0 :     char *pszContent = poStream->GetBytes();
    3495           0 :     const auto nLength = poStream->GetLength();
    3496           0 :     if (pszContent != nullptr && nLength > 15 &&
    3497           0 :         STARTS_WITH(pszContent, "<?xpacket begin="))
    3498             :     {
    3499             :         char *apszMDList[2];
    3500           0 :         apszMDList[0] = pszContent;
    3501           0 :         apszMDList[1] = nullptr;
    3502           0 :         SetMetadata(apszMDList, "xml:XMP");
    3503             :     }
    3504           0 :     CPLFree(pszContent);
    3505             : }
    3506             : 
    3507             : /************************************************************************/
    3508             : /*                             ParseInfo()                              */
    3509             : /************************************************************************/
    3510             : 
    3511         219 : void PDFDataset::ParseInfo(GDALPDFObject *poInfoObj)
    3512             : {
    3513         219 :     if (poInfoObj->GetType() != PDFObjectType_Dictionary)
    3514         180 :         return;
    3515             : 
    3516          39 :     GDALPDFDictionary *poInfoObjDict = poInfoObj->GetDictionary();
    3517          39 :     GDALPDFObject *poItem = nullptr;
    3518          39 :     int bOneMDISet = FALSE;
    3519          48 :     if ((poItem = poInfoObjDict->Get("Author")) != nullptr &&
    3520           9 :         poItem->GetType() == PDFObjectType_String)
    3521             :     {
    3522           9 :         SetMetadataItem("AUTHOR", poItem->GetString().c_str());
    3523           9 :         bOneMDISet = TRUE;
    3524             :     }
    3525          66 :     if ((poItem = poInfoObjDict->Get("Creator")) != nullptr &&
    3526          27 :         poItem->GetType() == PDFObjectType_String)
    3527             :     {
    3528          27 :         SetMetadataItem("CREATOR", poItem->GetString().c_str());
    3529          27 :         bOneMDISet = TRUE;
    3530             :     }
    3531          43 :     if ((poItem = poInfoObjDict->Get("Keywords")) != nullptr &&
    3532           4 :         poItem->GetType() == PDFObjectType_String)
    3533             :     {
    3534           4 :         SetMetadataItem("KEYWORDS", poItem->GetString().c_str());
    3535           4 :         bOneMDISet = TRUE;
    3536             :     }
    3537          45 :     if ((poItem = poInfoObjDict->Get("Subject")) != nullptr &&
    3538           6 :         poItem->GetType() == PDFObjectType_String)
    3539             :     {
    3540           6 :         SetMetadataItem("SUBJECT", poItem->GetString().c_str());
    3541           6 :         bOneMDISet = TRUE;
    3542             :     }
    3543          46 :     if ((poItem = poInfoObjDict->Get("Title")) != nullptr &&
    3544           7 :         poItem->GetType() == PDFObjectType_String)
    3545             :     {
    3546           7 :         SetMetadataItem("TITLE", poItem->GetString().c_str());
    3547           7 :         bOneMDISet = TRUE;
    3548             :     }
    3549          52 :     if ((poItem = poInfoObjDict->Get("Producer")) != nullptr &&
    3550          13 :         poItem->GetType() == PDFObjectType_String)
    3551             :     {
    3552          19 :         if (bOneMDISet ||
    3553           6 :             poItem->GetString() != "PoDoFo - http://podofo.sf.net")
    3554             :         {
    3555           7 :             SetMetadataItem("PRODUCER", poItem->GetString().c_str());
    3556           7 :             bOneMDISet = TRUE;
    3557             :         }
    3558             :     }
    3559          68 :     if ((poItem = poInfoObjDict->Get("CreationDate")) != nullptr &&
    3560          29 :         poItem->GetType() == PDFObjectType_String)
    3561             :     {
    3562          29 :         if (bOneMDISet)
    3563          23 :             SetMetadataItem("CREATION_DATE", poItem->GetString().c_str());
    3564             :     }
    3565             : }
    3566             : 
    3567             : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
    3568             : 
    3569             : /************************************************************************/
    3570             : /*                              AddLayer()                              */
    3571             : /************************************************************************/
    3572             : 
    3573         368 : void PDFDataset::AddLayer(const std::string &osName, int iPage)
    3574             : {
    3575         736 :     LayerStruct layerStruct;
    3576         368 :     layerStruct.osName = osName;
    3577         368 :     layerStruct.nInsertIdx = static_cast<int>(m_oLayerNameSet.size());
    3578         368 :     layerStruct.iPage = iPage;
    3579         368 :     m_oLayerNameSet.emplace_back(std::move(layerStruct));
    3580         368 : }
    3581             : 
    3582             : /************************************************************************/
    3583             : /*                           SortLayerList()                            */
    3584             : /************************************************************************/
    3585             : 
    3586          63 : void PDFDataset::SortLayerList()
    3587             : {
    3588          63 :     if (!m_oLayerNameSet.empty())
    3589             :     {
    3590             :         // Sort layers by prioritizing page number and then insertion index
    3591          63 :         std::sort(m_oLayerNameSet.begin(), m_oLayerNameSet.end(),
    3592        1777 :                   [](const LayerStruct &a, const LayerStruct &b)
    3593             :                   {
    3594        1777 :                       if (a.iPage < b.iPage)
    3595          39 :                           return true;
    3596        1738 :                       if (a.iPage > b.iPage)
    3597           0 :                           return false;
    3598        1738 :                       return a.nInsertIdx < b.nInsertIdx;
    3599             :                   });
    3600             :     }
    3601          63 : }
    3602             : 
    3603             : /************************************************************************/
    3604             : /*                          CreateLayerList()                           */
    3605             : /************************************************************************/
    3606             : 
    3607          63 : void PDFDataset::CreateLayerList()
    3608             : {
    3609          63 :     SortLayerList();
    3610             : 
    3611          63 :     if (m_oLayerNameSet.size() >= 100)
    3612             :     {
    3613         199 :         for (const auto &oLayerStruct : m_oLayerNameSet)
    3614             :         {
    3615             :             m_aosLayerNames.AddNameValue(
    3616             :                 CPLSPrintf("LAYER_%03d_NAME", m_aosLayerNames.size()),
    3617         198 :                 oLayerStruct.osName.c_str());
    3618             :         }
    3619             :     }
    3620             :     else
    3621             :     {
    3622         232 :         for (const auto &oLayerStruct : m_oLayerNameSet)
    3623             :         {
    3624             :             m_aosLayerNames.AddNameValue(
    3625             :                 CPLSPrintf("LAYER_%02d_NAME", m_aosLayerNames.size()),
    3626         170 :                 oLayerStruct.osName.c_str());
    3627             :         }
    3628             :     }
    3629          63 : }
    3630             : 
    3631             : /************************************************************************/
    3632             : /*                 BuildPostfixedLayerNameAndAddLayer()                 */
    3633             : /************************************************************************/
    3634             : 
    3635             : /** Append a suffix with the page number(s) to the provided layer name, if
    3636             :  * it makes sense (that is if it is a multiple page PDF and we haven't selected
    3637             :  * a specific name). And also call AddLayer() on it if successful.
    3638             :  * If may return an empty string if the layer isn't used by the page of interest
    3639             :  */
    3640         440 : std::string PDFDataset::BuildPostfixedLayerNameAndAddLayer(
    3641             :     const std::string &osName, const std::pair<int, int> &oOCGRef,
    3642             :     int iPageOfInterest, int nPageCount)
    3643             : {
    3644         880 :     std::string osPostfixedName = osName;
    3645         440 :     int iLayerPage = 0;
    3646         440 :     if (nPageCount > 1 && !m_oMapOCGNumGenToPages.empty())
    3647             :     {
    3648         108 :         const auto oIterToPages = m_oMapOCGNumGenToPages.find(oOCGRef);
    3649         108 :         if (oIterToPages != m_oMapOCGNumGenToPages.end())
    3650             :         {
    3651         108 :             const auto &anPages = oIterToPages->second;
    3652         108 :             if (iPageOfInterest > 0)
    3653             :             {
    3654          96 :                 if (std::find(anPages.begin(), anPages.end(),
    3655          96 :                               iPageOfInterest) == anPages.end())
    3656             :                 {
    3657          72 :                     return std::string();
    3658             :                 }
    3659             :             }
    3660          12 :             else if (anPages.size() == 1)
    3661             :             {
    3662          12 :                 iLayerPage = anPages.front();
    3663          12 :                 osPostfixedName += CPLSPrintf(" (page %d)", anPages.front());
    3664             :             }
    3665             :             else
    3666             :             {
    3667           0 :                 osPostfixedName += " (pages ";
    3668           0 :                 for (size_t j = 0; j < anPages.size(); ++j)
    3669             :                 {
    3670           0 :                     if (j > 0)
    3671           0 :                         osPostfixedName += ", ";
    3672           0 :                     osPostfixedName += CPLSPrintf("%d", anPages[j]);
    3673             :                 }
    3674           0 :                 osPostfixedName += ')';
    3675             :             }
    3676             :         }
    3677             :     }
    3678             : 
    3679         368 :     AddLayer(osPostfixedName, iLayerPage);
    3680             : 
    3681         368 :     return osPostfixedName;
    3682             : }
    3683             : 
    3684             : #endif  //  defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
    3685             : 
    3686             : #ifdef HAVE_POPPLER
    3687             : 
    3688             : /************************************************************************/
    3689             : /*                        ExploreLayersPoppler()                        */
    3690             : /************************************************************************/
    3691             : 
    3692         215 : void PDFDataset::ExploreLayersPoppler(GDALPDFArray *poArray,
    3693             :                                       int iPageOfInterest, int nPageCount,
    3694             :                                       CPLString osTopLayer, int nRecLevel,
    3695             :                                       int &nVisited, bool &bStop)
    3696             : {
    3697         215 :     if (nRecLevel == 16 || nVisited == 1000)
    3698             :     {
    3699           0 :         CPLError(
    3700             :             CE_Failure, CPLE_AppDefined,
    3701             :             "ExploreLayersPoppler(): too deep exploration or too many items");
    3702           0 :         bStop = true;
    3703           0 :         return;
    3704             :     }
    3705         215 :     if (bStop)
    3706           0 :         return;
    3707             : 
    3708         215 :     int nLength = poArray->GetLength();
    3709         215 :     CPLString osCurLayer;
    3710         807 :     for (int i = 0; i < nLength; i++)
    3711             :     {
    3712         592 :         nVisited++;
    3713         592 :         GDALPDFObject *poObj = poArray->Get(i);
    3714         592 :         if (poObj == nullptr)
    3715           0 :             continue;
    3716         592 :         if (i == 0 && poObj->GetType() == PDFObjectType_String)
    3717             :         {
    3718             :             std::string osName =
    3719           0 :                 PDFSanitizeLayerName(poObj->GetString().c_str());
    3720           0 :             if (!osTopLayer.empty())
    3721             :             {
    3722           0 :                 osTopLayer += '.';
    3723           0 :                 osTopLayer += osName;
    3724             :             }
    3725             :             else
    3726           0 :                 osTopLayer = std::move(osName);
    3727           0 :             AddLayer(osTopLayer, 0);
    3728           0 :             m_oLayerOCGListPoppler.push_back(std::pair(osTopLayer, nullptr));
    3729             :         }
    3730         592 :         else if (poObj->GetType() == PDFObjectType_Array)
    3731             :         {
    3732         152 :             ExploreLayersPoppler(poObj->GetArray(), iPageOfInterest, nPageCount,
    3733             :                                  osCurLayer, nRecLevel + 1, nVisited, bStop);
    3734         152 :             if (bStop)
    3735           0 :                 return;
    3736         152 :             osCurLayer = "";
    3737             :         }
    3738         440 :         else if (poObj->GetType() == PDFObjectType_Dictionary)
    3739             :         {
    3740         440 :             GDALPDFDictionary *poDict = poObj->GetDictionary();
    3741         440 :             GDALPDFObject *poName = poDict->Get("Name");
    3742         440 :             if (poName != nullptr && poName->GetType() == PDFObjectType_String)
    3743             :             {
    3744             :                 std::string osName =
    3745         440 :                     PDFSanitizeLayerName(poName->GetString().c_str());
    3746             :                 /* coverity[copy_paste_error] */
    3747         440 :                 if (!osTopLayer.empty())
    3748             :                 {
    3749         310 :                     osCurLayer = osTopLayer;
    3750         310 :                     osCurLayer += '.';
    3751         310 :                     osCurLayer += osName;
    3752             :                 }
    3753             :                 else
    3754         130 :                     osCurLayer = std::move(osName);
    3755             :                 // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
    3756             : 
    3757             : #if POPPLER_MAJOR_VERSION > 25 ||                                              \
    3758             :     (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
    3759             :                 const
    3760             : #endif
    3761             :                     OCGs *optContentConfig =
    3762         440 :                         m_poDocPoppler->getOptContentConfig();
    3763             :                 struct Ref r;
    3764         440 :                 r.num = poObj->GetRefNum().toInt();
    3765         440 :                 r.gen = poObj->GetRefGen();
    3766         440 :                 OptionalContentGroup *ocg = optContentConfig->findOcgByRef(r);
    3767         440 :                 if (ocg)
    3768             :                 {
    3769         440 :                     const auto oRefPair = std::pair(poObj->GetRefNum().toInt(),
    3770         880 :                                                     poObj->GetRefGen());
    3771             :                     const std::string osPostfixedName =
    3772             :                         BuildPostfixedLayerNameAndAddLayer(
    3773         440 :                             osCurLayer, oRefPair, iPageOfInterest, nPageCount);
    3774         440 :                     if (osPostfixedName.empty())
    3775          72 :                         continue;
    3776             : 
    3777         368 :                     m_oLayerOCGListPoppler.push_back(
    3778         736 :                         std::make_pair(osPostfixedName, ocg));
    3779         368 :                     m_aoLayerWithRef.emplace_back(osPostfixedName.c_str(),
    3780         736 :                                                   poObj->GetRefNum(), r.gen);
    3781             :                 }
    3782             :             }
    3783             :         }
    3784             :     }
    3785             : }
    3786             : 
    3787             : /************************************************************************/
    3788             : /*                         FindLayersPoppler()                          */
    3789             : /************************************************************************/
    3790             : 
    3791         219 : void PDFDataset::FindLayersPoppler(int iPageOfInterest)
    3792             : {
    3793         219 :     int nPageCount = 0;
    3794         219 :     const auto poPages = GetPagesKids();
    3795         219 :     if (poPages)
    3796         219 :         nPageCount = poPages->GetLength();
    3797             : 
    3798             : #if POPPLER_MAJOR_VERSION > 25 ||                                              \
    3799             :     (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
    3800             :     const
    3801             : #endif
    3802         219 :         OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
    3803         219 :     if (optContentConfig == nullptr || !optContentConfig->isOk())
    3804         156 :         return;
    3805             : 
    3806             : #if POPPLER_MAJOR_VERSION > 25 ||                                              \
    3807             :     (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
    3808             :     const
    3809             : #endif
    3810          63 :         Array *array = optContentConfig->getOrderArray();
    3811          63 :     if (array)
    3812             :     {
    3813          63 :         GDALPDFArray *poArray = GDALPDFCreateArray(array);
    3814          63 :         int nVisited = 0;
    3815          63 :         bool bStop = false;
    3816          63 :         ExploreLayersPoppler(poArray, iPageOfInterest, nPageCount, CPLString(),
    3817             :                              0, nVisited, bStop);
    3818          63 :         delete poArray;
    3819             :     }
    3820             :     else
    3821             :     {
    3822           0 :         for (const auto &refOCGPair : optContentConfig->getOCGs())
    3823             :         {
    3824           0 :             auto ocg = refOCGPair.second.get();
    3825           0 :             if (ocg != nullptr && ocg->getName() != nullptr)
    3826             :             {
    3827             :                 const char *pszLayerName =
    3828           0 :                     reinterpret_cast<const char *>(ocg->getName()->c_str());
    3829           0 :                 AddLayer(pszLayerName, 0);
    3830           0 :                 m_oLayerOCGListPoppler.push_back(
    3831           0 :                     std::make_pair(CPLString(pszLayerName), ocg));
    3832             :             }
    3833             :         }
    3834             :     }
    3835             : 
    3836          63 :     CreateLayerList();
    3837          63 :     m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
    3838             : }
    3839             : 
    3840             : /************************************************************************/
    3841             : /*                       TurnLayersOnOffPoppler()                       */
    3842             : /************************************************************************/
    3843             : 
    3844         219 : void PDFDataset::TurnLayersOnOffPoppler()
    3845             : {
    3846             : #if POPPLER_MAJOR_VERSION > 25 ||                                              \
    3847             :     (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
    3848             :     const
    3849             : #endif
    3850         219 :         OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
    3851         219 :     if (optContentConfig == nullptr || !optContentConfig->isOk())
    3852         156 :         return;
    3853             : 
    3854             :     // Which layers to turn ON ?
    3855          63 :     const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
    3856          63 :     if (pszLayers)
    3857             :     {
    3858             :         int i;
    3859           2 :         int bAll = EQUAL(pszLayers, "ALL");
    3860          12 :         for (const auto &refOCGPair : optContentConfig->getOCGs())
    3861             :         {
    3862          10 :             auto ocg = refOCGPair.second.get();
    3863          10 :             ocg->setState((bAll) ? OptionalContentGroup::On
    3864             :                                  : OptionalContentGroup::Off);
    3865             :         }
    3866             : 
    3867           2 :         char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
    3868           4 :         for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
    3869             :         {
    3870           2 :             bool isFound = false;
    3871          12 :             for (auto oIter2 = m_oLayerOCGListPoppler.begin();
    3872          22 :                  oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
    3873             :             {
    3874          10 :                 if (oIter2->first != papszLayers[i])
    3875           8 :                     continue;
    3876             : 
    3877           2 :                 isFound = true;
    3878           2 :                 auto oIter = oIter2;
    3879           2 :                 if (oIter->second)
    3880             :                 {
    3881             :                     // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
    3882           2 :                     oIter->second->setState(OptionalContentGroup::On);
    3883             :                 }
    3884             : 
    3885             :                 // Turn child layers on, unless there's one of them explicitly
    3886             :                 // listed in the list.
    3887           2 :                 size_t nLen = strlen(papszLayers[i]);
    3888           2 :                 int bFoundChildLayer = FALSE;
    3889           2 :                 oIter = m_oLayerOCGListPoppler.begin();
    3890          10 :                 for (;
    3891          12 :                      oIter != m_oLayerOCGListPoppler.end() && !bFoundChildLayer;
    3892          10 :                      ++oIter)
    3893             :                 {
    3894          10 :                     if (oIter->first.size() > nLen &&
    3895           5 :                         strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
    3896          15 :                             0 &&
    3897           2 :                         oIter->first[nLen] == '.')
    3898             :                     {
    3899           4 :                         for (int j = 0; papszLayers[j] != nullptr; j++)
    3900             :                         {
    3901           2 :                             if (strcmp(papszLayers[j], oIter->first.c_str()) ==
    3902             :                                 0)
    3903             :                             {
    3904           0 :                                 bFoundChildLayer = TRUE;
    3905           0 :                                 break;
    3906             :                             }
    3907             :                         }
    3908             :                     }
    3909             :                 }
    3910             : 
    3911           2 :                 if (!bFoundChildLayer)
    3912             :                 {
    3913           2 :                     oIter = m_oLayerOCGListPoppler.begin();
    3914          12 :                     for (; oIter != m_oLayerOCGListPoppler.end() &&
    3915             :                            !bFoundChildLayer;
    3916          10 :                          ++oIter)
    3917             :                     {
    3918          10 :                         if (oIter->first.size() > nLen &&
    3919           5 :                             strncmp(oIter->first.c_str(), papszLayers[i],
    3920          15 :                                     nLen) == 0 &&
    3921           2 :                             oIter->first[nLen] == '.')
    3922             :                         {
    3923           2 :                             if (oIter->second)
    3924             :                             {
    3925             :                                 // CPLDebug("PDF", "Turn '%s' on too",
    3926             :                                 // oIter->first.c_str());
    3927           2 :                                 oIter->second->setState(
    3928             :                                     OptionalContentGroup::On);
    3929             :                             }
    3930             :                         }
    3931             :                     }
    3932             :                 }
    3933             : 
    3934             :                 // Turn parent layers on too
    3935           6 :                 std::string layer(papszLayers[i]);
    3936             :                 std::string::size_type j;
    3937           3 :                 while ((j = layer.find_last_of('.')) != std::string::npos)
    3938             :                 {
    3939           1 :                     layer.resize(j);
    3940           1 :                     oIter = m_oLayerOCGListPoppler.begin();
    3941           6 :                     for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
    3942             :                     {
    3943           5 :                         if (oIter->first == layer && oIter->second)
    3944             :                         {
    3945             :                             // CPLDebug("PDF", "Turn '%s' on too",
    3946             :                             // layer.c_str());
    3947           1 :                             oIter->second->setState(OptionalContentGroup::On);
    3948             :                         }
    3949             :                     }
    3950             :                 }
    3951             :             }
    3952           2 :             if (!isFound)
    3953             :             {
    3954           0 :                 CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
    3955           0 :                          papszLayers[i]);
    3956             :             }
    3957             :         }
    3958           2 :         CSLDestroy(papszLayers);
    3959             : 
    3960           2 :         m_bUseOCG = true;
    3961             :     }
    3962             : 
    3963             :     // Which layers to turn OFF ?
    3964             :     const char *pszLayersOFF =
    3965          63 :         GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
    3966          63 :     if (pszLayersOFF)
    3967             :     {
    3968           5 :         char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
    3969          10 :         for (int i = 0; papszLayersOFF[i] != nullptr; i++)
    3970             :         {
    3971           5 :             bool isFound = false;
    3972          22 :             for (auto oIter2 = m_oLayerOCGListPoppler.begin();
    3973          39 :                  oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
    3974             :             {
    3975          17 :                 if (oIter2->first != papszLayersOFF[i])
    3976          12 :                     continue;
    3977             : 
    3978           5 :                 isFound = true;
    3979           5 :                 auto oIter = oIter2;
    3980           5 :                 if (oIter->second)
    3981             :                 {
    3982             :                     // CPLDebug("PDF", "Turn '%s' off", papszLayersOFF[i]);
    3983           5 :                     oIter->second->setState(OptionalContentGroup::Off);
    3984             :                 }
    3985             : 
    3986             :                 // Turn child layers off too
    3987           5 :                 size_t nLen = strlen(papszLayersOFF[i]);
    3988           5 :                 oIter = m_oLayerOCGListPoppler.begin();
    3989          22 :                 for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
    3990             :                 {
    3991          17 :                     if (oIter->first.size() > nLen &&
    3992           3 :                         strncmp(oIter->first.c_str(), papszLayersOFF[i],
    3993          20 :                                 nLen) == 0 &&
    3994           1 :                         oIter->first[nLen] == '.')
    3995             :                     {
    3996           1 :                         if (oIter->second)
    3997             :                         {
    3998             :                             // CPLDebug("PDF", "Turn '%s' off too",
    3999             :                             // oIter->first.c_str());
    4000           1 :                             oIter->second->setState(OptionalContentGroup::Off);
    4001             :                         }
    4002             :                     }
    4003             :                 }
    4004             :             }
    4005           5 :             if (!isFound)
    4006             :             {
    4007           0 :                 CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
    4008           0 :                          papszLayersOFF[i]);
    4009             :             }
    4010             :         }
    4011           5 :         CSLDestroy(papszLayersOFF);
    4012             : 
    4013           5 :         m_bUseOCG = true;
    4014             :     }
    4015             : }
    4016             : 
    4017             : #endif
    4018             : 
    4019             : #ifdef HAVE_PDFIUM
    4020             : 
    4021             : /************************************************************************/
    4022             : /*                        ExploreLayersPdfium()                         */
    4023             : /************************************************************************/
    4024             : 
    4025             : void PDFDataset::ExploreLayersPdfium(GDALPDFArray *poArray, int iPageOfInterest,
    4026             :                                      int nPageCount, int nRecLevel,
    4027             :                                      CPLString osTopLayer)
    4028             : {
    4029             :     if (nRecLevel == 16)
    4030             :         return;
    4031             : 
    4032             :     const int nLength = poArray->GetLength();
    4033             :     std::string osCurLayer;
    4034             :     for (int i = 0; i < nLength; i++)
    4035             :     {
    4036             :         GDALPDFObject *poObj = poArray->Get(i);
    4037             :         if (poObj == nullptr)
    4038             :             continue;
    4039             :         if (i == 0 && poObj->GetType() == PDFObjectType_String)
    4040             :         {
    4041             :             const std::string osName =
    4042             :                 PDFSanitizeLayerName(poObj->GetString().c_str());
    4043             :             if (!osTopLayer.empty())
    4044             :                 osTopLayer = std::string(osTopLayer).append(".").append(osName);
    4045             :             else
    4046             :                 osTopLayer = osName;
    4047             :             AddLayer(osTopLayer, 0);
    4048             :             m_oMapLayerNameToOCGNumGenPdfium[osTopLayer] = std::pair(-1, -1);
    4049             :         }
    4050             :         else if (poObj->GetType() == PDFObjectType_Array)
    4051             :         {
    4052             :             ExploreLayersPdfium(poObj->GetArray(), iPageOfInterest, nPageCount,
    4053             :                                 nRecLevel + 1, osCurLayer);
    4054             :             osCurLayer.clear();
    4055             :         }
    4056             :         else if (poObj->GetType() == PDFObjectType_Dictionary)
    4057             :         {
    4058             :             GDALPDFDictionary *poDict = poObj->GetDictionary();
    4059             :             GDALPDFObject *poName = poDict->Get("Name");
    4060             :             if (poName != nullptr && poName->GetType() == PDFObjectType_String)
    4061             :             {
    4062             :                 std::string osName =
    4063             :                     PDFSanitizeLayerName(poName->GetString().c_str());
    4064             :                 // coverity[copy_paste_error]
    4065             :                 if (!osTopLayer.empty())
    4066             :                 {
    4067             :                     osCurLayer =
    4068             :                         std::string(osTopLayer).append(".").append(osName);
    4069             :                 }
    4070             :                 else
    4071             :                     osCurLayer = std::move(osName);
    4072             :                 // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
    4073             : 
    4074             :                 const auto oRefPair =
    4075             :                     std::pair(poObj->GetRefNum().toInt(), poObj->GetRefGen());
    4076             :                 const std::string osPostfixedName =
    4077             :                     BuildPostfixedLayerNameAndAddLayer(
    4078             :                         osCurLayer, oRefPair, iPageOfInterest, nPageCount);
    4079             :                 if (osPostfixedName.empty())
    4080             :                     continue;
    4081             : 
    4082             :                 m_aoLayerWithRef.emplace_back(
    4083             :                     osPostfixedName, poObj->GetRefNum(), poObj->GetRefGen());
    4084             :                 m_oMapLayerNameToOCGNumGenPdfium[osPostfixedName] = oRefPair;
    4085             :             }
    4086             :         }
    4087             :     }
    4088             : }
    4089             : 
    4090             : /************************************************************************/
    4091             : /*                          FindLayersPdfium()                          */
    4092             : /************************************************************************/
    4093             : 
    4094             : void PDFDataset::FindLayersPdfium(int iPageOfInterest)
    4095             : {
    4096             :     int nPageCount = 0;
    4097             :     const auto poPages = GetPagesKids();
    4098             :     if (poPages)
    4099             :         nPageCount = poPages->GetLength();
    4100             : 
    4101             :     GDALPDFObject *poCatalog = GetCatalog();
    4102             :     if (poCatalog == nullptr ||
    4103             :         poCatalog->GetType() != PDFObjectType_Dictionary)
    4104             :         return;
    4105             :     GDALPDFObject *poOrder = poCatalog->LookupObject("OCProperties.D.Order");
    4106             :     if (poOrder != nullptr && poOrder->GetType() == PDFObjectType_Array)
    4107             :     {
    4108             :         ExploreLayersPdfium(poOrder->GetArray(), iPageOfInterest, nPageCount,
    4109             :                             0);
    4110             :     }
    4111             : #if 0
    4112             :     else
    4113             :     {
    4114             :         GDALPDFObject* poOCGs = poD->GetDictionary()->Get("OCGs");
    4115             :         if( poOCGs != nullptr && poOCGs->GetType() == PDFObjectType_Array )
    4116             :         {
    4117             :             GDALPDFArray* poArray = poOCGs->GetArray();
    4118             :             int nLength = poArray->GetLength();
    4119             :             for(int i=0;i<nLength;i++)
    4120             :             {
    4121             :                 GDALPDFObject* poObj = poArray->Get(i);
    4122             :                 if( poObj != nullptr )
    4123             :                 {
    4124             :                     // TODO ?
    4125             :                 }
    4126             :             }
    4127             :         }
    4128             :     }
    4129             : #endif
    4130             : 
    4131             :     CreateLayerList();
    4132             :     m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
    4133             : }
    4134             : 
    4135             : /************************************************************************/
    4136             : /*                       TurnLayersOnOffPdfium()                        */
    4137             : /************************************************************************/
    4138             : 
    4139             : void PDFDataset::TurnLayersOnOffPdfium()
    4140             : {
    4141             :     GDALPDFObject *poCatalog = GetCatalog();
    4142             :     if (poCatalog == nullptr ||
    4143             :         poCatalog->GetType() != PDFObjectType_Dictionary)
    4144             :         return;
    4145             :     GDALPDFObject *poOCGs = poCatalog->LookupObject("OCProperties.OCGs");
    4146             :     if (poOCGs == nullptr || poOCGs->GetType() != PDFObjectType_Array)
    4147             :         return;
    4148             : 
    4149             :     // Which layers to turn ON ?
    4150             :     const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
    4151             :     if (pszLayers)
    4152             :     {
    4153             :         int i;
    4154             :         int bAll = EQUAL(pszLayers, "ALL");
    4155             : 
    4156             :         GDALPDFArray *poOCGsArray = poOCGs->GetArray();
    4157             :         int nLength = poOCGsArray->GetLength();
    4158             :         for (i = 0; i < nLength; i++)
    4159             :         {
    4160             :             GDALPDFObject *poOCG = poOCGsArray->Get(i);
    4161             :             m_oMapOCGNumGenToVisibilityStatePdfium[std::pair(
    4162             :                 poOCG->GetRefNum().toInt(), poOCG->GetRefGen())] =
    4163             :                 (bAll) ? VISIBILITY_ON : VISIBILITY_OFF;
    4164             :         }
    4165             : 
    4166             :         char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
    4167             :         for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
    4168             :         {
    4169             :             auto oIter = m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
    4170             :             if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
    4171             :             {
    4172             :                 if (oIter->second.first >= 0)
    4173             :                 {
    4174             :                     // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
    4175             :                     m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
    4176             :                         VISIBILITY_ON;
    4177             :                 }
    4178             : 
    4179             :                 // Turn child layers on, unless there's one of them explicitly
    4180             :                 // listed in the list.
    4181             :                 size_t nLen = strlen(papszLayers[i]);
    4182             :                 int bFoundChildLayer = FALSE;
    4183             :                 oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
    4184             :                 for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
    4185             :                        !bFoundChildLayer;
    4186             :                      oIter++)
    4187             :                 {
    4188             :                     if (oIter->first.size() > nLen &&
    4189             :                         strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
    4190             :                             0 &&
    4191             :                         oIter->first[nLen] == '.')
    4192             :                     {
    4193             :                         for (int j = 0; papszLayers[j] != nullptr; j++)
    4194             :                         {
    4195             :                             if (strcmp(papszLayers[j], oIter->first.c_str()) ==
    4196             :                                 0)
    4197             :                                 bFoundChildLayer = TRUE;
    4198             :                         }
    4199             :                     }
    4200             :                 }
    4201             : 
    4202             :                 if (!bFoundChildLayer)
    4203             :                 {
    4204             :                     oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
    4205             :                     for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
    4206             :                            !bFoundChildLayer;
    4207             :                          oIter++)
    4208             :                     {
    4209             :                         if (oIter->first.size() > nLen &&
    4210             :                             strncmp(oIter->first.c_str(), papszLayers[i],
    4211             :                                     nLen) == 0 &&
    4212             :                             oIter->first[nLen] == '.')
    4213             :                         {
    4214             :                             if (oIter->second.first >= 0)
    4215             :                             {
    4216             :                                 // CPLDebug("PDF", "Turn '%s' on too",
    4217             :                                 // oIter->first.c_str());
    4218             :                                 m_oMapOCGNumGenToVisibilityStatePdfium
    4219             :                                     [oIter->second] = VISIBILITY_ON;
    4220             :                             }
    4221             :                         }
    4222             :                     }
    4223             :                 }
    4224             : 
    4225             :                 // Turn parent layers on too
    4226             :                 char *pszLastDot = nullptr;
    4227             :                 while ((pszLastDot = strrchr(papszLayers[i], '.')) != nullptr)
    4228             :                 {
    4229             :                     *pszLastDot = '\0';
    4230             :                     oIter =
    4231             :                         m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
    4232             :                     if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
    4233             :                     {
    4234             :                         if (oIter->second.first >= 0)
    4235             :                         {
    4236             :                             // CPLDebug("PDF", "Turn '%s' on too",
    4237             :                             // papszLayers[i]);
    4238             :                             m_oMapOCGNumGenToVisibilityStatePdfium
    4239             :                                 [oIter->second] = VISIBILITY_ON;
    4240             :                         }
    4241             :                     }
    4242             :                 }
    4243             :             }
    4244             :             else
    4245             :             {
    4246             :                 CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
    4247             :                          papszLayers[i]);
    4248             :             }
    4249             :         }
    4250             :         CSLDestroy(papszLayers);
    4251             : 
    4252             :         m_bUseOCG = true;
    4253             :     }
    4254             : 
    4255             :     // Which layers to turn OFF ?
    4256             :     const char *pszLayersOFF =
    4257             :         GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
    4258             :     if (pszLayersOFF)
    4259             :     {
    4260             :         char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
    4261             :         for (int i = 0; papszLayersOFF[i] != nullptr; i++)
    4262             :         {
    4263             :             auto oIter =
    4264             :                 m_oMapLayerNameToOCGNumGenPdfium.find(papszLayersOFF[i]);
    4265             :             if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
    4266             :             {
    4267             :                 if (oIter->second.first >= 0)
    4268             :                 {
    4269             :                     // CPLDebug("PDF", "Turn '%s' (%d,%d) off",
    4270             :                     // papszLayersOFF[i], oIter->second.first,
    4271             :                     // oIter->second.second);
    4272             :                     m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
    4273             :                         VISIBILITY_OFF;
    4274             :                 }
    4275             : 
    4276             :                 // Turn child layers off too
    4277             :                 size_t nLen = strlen(papszLayersOFF[i]);
    4278             :                 oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
    4279             :                 for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end(); oIter++)
    4280             :                 {
    4281             :                     if (oIter->first.size() > nLen &&
    4282             :                         strncmp(oIter->first.c_str(), papszLayersOFF[i],
    4283             :                                 nLen) == 0 &&
    4284             :                         oIter->first[nLen] == '.')
    4285             :                     {
    4286             :                         if (oIter->second.first >= 0)
    4287             :                         {
    4288             :                             // CPLDebug("PDF", "Turn '%s' off too",
    4289             :                             // oIter->first.c_str());
    4290             :                             m_oMapOCGNumGenToVisibilityStatePdfium
    4291             :                                 [oIter->second] = VISIBILITY_OFF;
    4292             :                         }
    4293             :                     }
    4294             :                 }
    4295             :             }
    4296             :             else
    4297             :             {
    4298             :                 CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
    4299             :                          papszLayersOFF[i]);
    4300             :             }
    4301             :         }
    4302             :         CSLDestroy(papszLayersOFF);
    4303             : 
    4304             :         m_bUseOCG = true;
    4305             :     }
    4306             : }
    4307             : 
    4308             : /************************************************************************/
    4309             : /*                   GetVisibilityStateForOGCPdfium()                   */
    4310             : /************************************************************************/
    4311             : 
    4312             : PDFDataset::VisibilityState PDFDataset::GetVisibilityStateForOGCPdfium(int nNum,
    4313             :                                                                        int nGen)
    4314             : {
    4315             :     auto oIter =
    4316             :         m_oMapOCGNumGenToVisibilityStatePdfium.find(std::pair(nNum, nGen));
    4317             :     if (oIter == m_oMapOCGNumGenToVisibilityStatePdfium.end())
    4318             :         return VISIBILITY_DEFAULT;
    4319             :     return oIter->second;
    4320             : }
    4321             : 
    4322             : #endif /* HAVE_PDFIUM */
    4323             : 
    4324             : /************************************************************************/
    4325             : /*                            GetPagesKids()                            */
    4326             : /************************************************************************/
    4327             : 
    4328         438 : GDALPDFArray *PDFDataset::GetPagesKids()
    4329             : {
    4330         438 :     const auto poCatalog = GetCatalog();
    4331         438 :     if (!poCatalog || poCatalog->GetType() != PDFObjectType_Dictionary)
    4332             :     {
    4333           0 :         return nullptr;
    4334             :     }
    4335         438 :     const auto poKids = poCatalog->LookupObject("Pages.Kids");
    4336         438 :     if (!poKids || poKids->GetType() != PDFObjectType_Array)
    4337             :     {
    4338           0 :         return nullptr;
    4339             :     }
    4340         438 :     return poKids->GetArray();
    4341             : }
    4342             : 
    4343             : /************************************************************************/
    4344             : /*                           MapOCGsToPages()                           */
    4345             : /************************************************************************/
    4346             : 
    4347         219 : void PDFDataset::MapOCGsToPages()
    4348             : {
    4349         219 :     const auto poKidsArray = GetPagesKids();
    4350         219 :     if (!poKidsArray)
    4351             :     {
    4352           0 :         return;
    4353             :     }
    4354         219 :     const int nKidsArrayLength = poKidsArray->GetLength();
    4355         470 :     for (int iPage = 0; iPage < nKidsArrayLength; ++iPage)
    4356             :     {
    4357         251 :         const auto poPage = poKidsArray->Get(iPage);
    4358         251 :         if (poPage && poPage->GetType() == PDFObjectType_Dictionary)
    4359             :         {
    4360         251 :             const auto poXObject = poPage->LookupObject("Resources.XObject");
    4361         251 :             if (poXObject && poXObject->GetType() == PDFObjectType_Dictionary)
    4362             :             {
    4363         535 :                 for (const auto &oNameObjectPair :
    4364        1308 :                      poXObject->GetDictionary()->GetValues())
    4365             :                 {
    4366             :                     const auto poProperties =
    4367         535 :                         oNameObjectPair.second->LookupObject(
    4368             :                             "Resources.Properties");
    4369         572 :                     if (poProperties &&
    4370          37 :                         poProperties->GetType() == PDFObjectType_Dictionary)
    4371             :                     {
    4372             :                         const auto &oMap =
    4373          37 :                             poProperties->GetDictionary()->GetValues();
    4374         282 :                         for (const auto &[osKey, poObj] : oMap)
    4375             :                         {
    4376         490 :                             if (poObj->GetRefNum().toBool() &&
    4377         245 :                                 poObj->GetType() == PDFObjectType_Dictionary)
    4378             :                             {
    4379             :                                 GDALPDFObject *poType =
    4380         245 :                                     poObj->GetDictionary()->Get("Type");
    4381             :                                 GDALPDFObject *poName =
    4382         245 :                                     poObj->GetDictionary()->Get("Name");
    4383         490 :                                 if (poType &&
    4384         490 :                                     poType->GetType() == PDFObjectType_Name &&
    4385         980 :                                     poType->GetName() == "OCG" && poName &&
    4386         245 :                                     poName->GetType() == PDFObjectType_String)
    4387             :                                 {
    4388             :                                     m_oMapOCGNumGenToPages
    4389         245 :                                         [std::pair(poObj->GetRefNum().toInt(),
    4390         490 :                                                    poObj->GetRefGen())]
    4391         245 :                                             .push_back(iPage + 1);
    4392             :                                 }
    4393             :                             }
    4394             :                         }
    4395             :                     }
    4396             :                 }
    4397             :             }
    4398             :         }
    4399             :     }
    4400             : }
    4401             : 
    4402             : /************************************************************************/
    4403             : /*                            FindLayerOCG()                            */
    4404             : /************************************************************************/
    4405             : 
    4406         204 : CPLString PDFDataset::FindLayerOCG(GDALPDFDictionary *poPageDict,
    4407             :                                    const char *pszLayerName)
    4408             : {
    4409             :     GDALPDFObject *poProperties =
    4410         204 :         poPageDict->LookupObject("Resources.Properties");
    4411         247 :     if (poProperties != nullptr &&
    4412          43 :         poProperties->GetType() == PDFObjectType_Dictionary)
    4413             :     {
    4414          43 :         const auto &oMap = poProperties->GetDictionary()->GetValues();
    4415         122 :         for (const auto &[osKey, poObj] : oMap)
    4416             :         {
    4417         157 :             if (poObj->GetRefNum().toBool() &&
    4418          78 :                 poObj->GetType() == PDFObjectType_Dictionary)
    4419             :             {
    4420          78 :                 GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
    4421          78 :                 GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
    4422         156 :                 if (poType != nullptr &&
    4423         156 :                     poType->GetType() == PDFObjectType_Name &&
    4424         312 :                     poType->GetName() == "OCG" && poName != nullptr &&
    4425          78 :                     poName->GetType() == PDFObjectType_String)
    4426             :                 {
    4427          78 :                     if (poName->GetString() == pszLayerName)
    4428           0 :                         return osKey;
    4429             :                 }
    4430             :             }
    4431             :         }
    4432             :     }
    4433         204 :     return "";
    4434             : }
    4435             : 
    4436             : /************************************************************************/
    4437             : /*                         FindLayersGeneric()                          */
    4438             : /************************************************************************/
    4439             : 
    4440           0 : void PDFDataset::FindLayersGeneric(GDALPDFDictionary *poPageDict)
    4441             : {
    4442             :     GDALPDFObject *poProperties =
    4443           0 :         poPageDict->LookupObject("Resources.Properties");
    4444           0 :     if (poProperties != nullptr &&
    4445           0 :         poProperties->GetType() == PDFObjectType_Dictionary)
    4446             :     {
    4447           0 :         const auto &oMap = poProperties->GetDictionary()->GetValues();
    4448           0 :         for (const auto &[osKey, poObj] : oMap)
    4449             :         {
    4450           0 :             if (poObj->GetRefNum().toBool() &&
    4451           0 :                 poObj->GetType() == PDFObjectType_Dictionary)
    4452             :             {
    4453           0 :                 GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
    4454           0 :                 GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
    4455           0 :                 if (poType != nullptr &&
    4456           0 :                     poType->GetType() == PDFObjectType_Name &&
    4457           0 :                     poType->GetName() == "OCG" && poName != nullptr &&
    4458           0 :                     poName->GetType() == PDFObjectType_String)
    4459             :                 {
    4460             :                     m_aoLayerWithRef.emplace_back(
    4461           0 :                         PDFSanitizeLayerName(poName->GetString().c_str())
    4462           0 :                             .c_str(),
    4463           0 :                         poObj->GetRefNum(), poObj->GetRefGen());
    4464             :                 }
    4465             :             }
    4466             :         }
    4467             :     }
    4468           0 : }
    4469             : 
    4470             : /************************************************************************/
    4471             : /*                                Open()                                */
    4472             : /************************************************************************/
    4473             : 
    4474         234 : PDFDataset *PDFDataset::Open(GDALOpenInfo *poOpenInfo)
    4475             : 
    4476             : {
    4477         234 :     if (!PDFDatasetIdentify(poOpenInfo))
    4478           1 :         return nullptr;
    4479             : 
    4480             :     const char *pszUserPwd =
    4481         233 :         GetOption(poOpenInfo->papszOpenOptions, "USER_PWD", nullptr);
    4482             : 
    4483         233 :     const bool bOpenSubdataset = STARTS_WITH(poOpenInfo->pszFilename, "PDF:");
    4484         233 :     const bool bOpenSubdatasetImage =
    4485         233 :         STARTS_WITH(poOpenInfo->pszFilename, "PDF_IMAGE:");
    4486         233 :     int iPage = -1;
    4487         233 :     int nImageNum = -1;
    4488         466 :     std::string osSubdatasetName;
    4489         233 :     const char *pszFilename = poOpenInfo->pszFilename;
    4490             : 
    4491         233 :     if (bOpenSubdataset)
    4492             :     {
    4493          15 :         iPage = atoi(pszFilename + 4);
    4494          15 :         if (iPage <= 0)
    4495           1 :             return nullptr;
    4496          14 :         pszFilename = strchr(pszFilename + 4, ':');
    4497          14 :         if (pszFilename == nullptr)
    4498           0 :             return nullptr;
    4499          14 :         pszFilename++;
    4500          14 :         osSubdatasetName = CPLSPrintf("Page %d", iPage);
    4501             :     }
    4502         218 :     else if (bOpenSubdatasetImage)
    4503             :     {
    4504           0 :         iPage = atoi(pszFilename + 10);
    4505           0 :         if (iPage <= 0)
    4506           0 :             return nullptr;
    4507           0 :         const char *pszNext = strchr(pszFilename + 10, ':');
    4508           0 :         if (pszNext == nullptr)
    4509           0 :             return nullptr;
    4510           0 :         nImageNum = atoi(pszNext + 1);
    4511           0 :         if (nImageNum <= 0)
    4512           0 :             return nullptr;
    4513           0 :         pszFilename = strchr(pszNext + 1, ':');
    4514           0 :         if (pszFilename == nullptr)
    4515           0 :             return nullptr;
    4516           0 :         pszFilename++;
    4517           0 :         osSubdatasetName = CPLSPrintf("Image %d", nImageNum);
    4518             :     }
    4519             :     else
    4520         218 :         iPage = 1;
    4521             : 
    4522         232 :     std::bitset<PDFLIB_COUNT> bHasLib;
    4523         232 :     bHasLib.reset();
    4524             :     // Each library set their flag
    4525             : #if defined(HAVE_POPPLER)
    4526         232 :     bHasLib.set(PDFLIB_POPPLER);
    4527             : #endif  // HAVE_POPPLER
    4528             : #if defined(HAVE_PODOFO)
    4529             :     bHasLib.set(PDFLIB_PODOFO);
    4530             : #endif  // HAVE_PODOFO
    4531             : #if defined(HAVE_PDFIUM)
    4532             :     bHasLib.set(PDFLIB_PDFIUM);
    4533             : #endif  // HAVE_PDFIUM
    4534             : 
    4535         232 :     std::bitset<PDFLIB_COUNT> bUseLib;
    4536             : 
    4537             :     // More than one library available
    4538             :     // Detect which one
    4539         232 :     if (bHasLib.count() != 1)
    4540             :     {
    4541           0 :         const char *pszDefaultLib = bHasLib.test(PDFLIB_PDFIUM)    ? "PDFIUM"
    4542           0 :                                     : bHasLib.test(PDFLIB_POPPLER) ? "POPPLER"
    4543           0 :                                                                    : "PODOFO";
    4544             :         const char *pszPDFLib =
    4545           0 :             GetOption(poOpenInfo->papszOpenOptions, "PDF_LIB", pszDefaultLib);
    4546             :         while (true)
    4547             :         {
    4548           0 :             if (EQUAL(pszPDFLib, "POPPLER"))
    4549           0 :                 bUseLib.set(PDFLIB_POPPLER);
    4550           0 :             else if (EQUAL(pszPDFLib, "PODOFO"))
    4551           0 :                 bUseLib.set(PDFLIB_PODOFO);
    4552           0 :             else if (EQUAL(pszPDFLib, "PDFIUM"))
    4553           0 :                 bUseLib.set(PDFLIB_PDFIUM);
    4554             : 
    4555           0 :             if (bUseLib.count() != 1 || (bHasLib & bUseLib) == 0)
    4556             :             {
    4557           0 :                 CPLDebug("PDF",
    4558             :                          "Invalid value for GDAL_PDF_LIB config option: %s. "
    4559             :                          "Fallback to %s",
    4560             :                          pszPDFLib, pszDefaultLib);
    4561           0 :                 pszPDFLib = pszDefaultLib;
    4562           0 :                 bUseLib.reset();
    4563             :             }
    4564             :             else
    4565           0 :                 break;
    4566             :         }
    4567             :     }
    4568             :     else
    4569         232 :         bUseLib = bHasLib;
    4570             : 
    4571         232 :     GDALPDFObject *poPageObj = nullptr;
    4572             : #ifdef HAVE_POPPLER
    4573         232 :     PDFDoc *poDocPoppler = nullptr;
    4574         232 :     Page *poPagePoppler = nullptr;
    4575         232 :     Catalog *poCatalogPoppler = nullptr;
    4576             : #endif
    4577             : #ifdef HAVE_PODOFO
    4578             :     std::unique_ptr<PoDoFo::PdfMemDocument> poDocPodofo;
    4579             :     PoDoFo::PdfPage *poPagePodofo = nullptr;
    4580             : #endif
    4581             : #ifdef HAVE_PDFIUM
    4582             :     TPdfiumDocumentStruct *poDocPdfium = nullptr;
    4583             :     TPdfiumPageStruct *poPagePdfium = nullptr;
    4584             : #endif
    4585         232 :     int nPages = 0;
    4586         232 :     VSIVirtualHandleUniquePtr fp;
    4587             : 
    4588             : #ifdef HAVE_POPPLER
    4589         232 :     if (bUseLib.test(PDFLIB_POPPLER))
    4590             :     {
    4591             :         static bool globalParamsCreatedByGDAL = false;
    4592             :         {
    4593         464 :             CPLMutexHolderD(&hGlobalParamsMutex);
    4594             :             /* poppler global variable */
    4595         232 :             if (globalParams == nullptr)
    4596             :             {
    4597           6 :                 globalParamsCreatedByGDAL = true;
    4598           6 :                 globalParams.reset(new GlobalParams());
    4599             :             }
    4600             : 
    4601         232 :             globalParams->setPrintCommands(CPLTestBool(
    4602             :                 CPLGetConfigOption("GDAL_PDF_PRINT_COMMANDS", "FALSE")));
    4603             :         }
    4604             : 
    4605         466 :         const auto registerErrorCallback = []()
    4606             :         {
    4607             :             /* Set custom error handler for poppler errors */
    4608         466 :             setErrorCallback(PDFDatasetErrorFunction);
    4609         466 :             assert(globalParams);  // avoid CSA false positive
    4610         466 :             globalParams->setErrQuiet(false);
    4611         466 :         };
    4612             : 
    4613         232 :         fp.reset(VSIFOpenL(pszFilename, "rb"));
    4614         232 :         if (!fp)
    4615          13 :             return nullptr;
    4616             : 
    4617             : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    4618             :         {
    4619             :             // Workaround for ossfuzz only due to
    4620             :             // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=37584
    4621             :             // https://gitlab.freedesktop.org/poppler/poppler/-/issues/1137
    4622             :             GByte *pabyRet = nullptr;
    4623             :             vsi_l_offset nSize = 0;
    4624             :             if (VSIIngestFile(fp.get(), pszFilename, &pabyRet, &nSize,
    4625             :                               10 * 1024 * 1024))
    4626             :             {
    4627             :                 // Replace nul byte by something else so that strstr() works
    4628             :                 for (size_t i = 0; i < nSize; i++)
    4629             :                 {
    4630             :                     if (pabyRet[i] == 0)
    4631             :                         pabyRet[i] = ' ';
    4632             :                 }
    4633             :                 if (strstr(reinterpret_cast<const char *>(pabyRet),
    4634             :                            "/JBIG2Decode"))
    4635             :                 {
    4636             :                     CPLError(CE_Failure, CPLE_AppDefined,
    4637             :                              "/JBIG2Decode found. Giving up due to potential "
    4638             :                              "very long processing time.");
    4639             :                     CPLFree(pabyRet);
    4640             :                     return nullptr;
    4641             :                 }
    4642             :             }
    4643             :             CPLFree(pabyRet);
    4644             :         }
    4645             : #endif
    4646             : 
    4647         231 :         fp.reset(VSICreateBufferedReaderHandle(fp.release()));
    4648             :         while (true)
    4649             :         {
    4650         233 :             fp->Seek(0, SEEK_SET);
    4651         233 :             g_nPopplerErrors = 0;
    4652         233 :             if (globalParamsCreatedByGDAL)
    4653         233 :                 registerErrorCallback();
    4654         233 :             Object oObj;
    4655             :             auto poStream = std::make_unique<VSIPDFFileStream>(
    4656         233 :                 fp.get(), pszFilename, std::move(oObj));
    4657         233 :             const bool bFoundLinearizedHint = poStream->FoundLinearizedHint();
    4658             : #if POPPLER_MAJOR_VERSION > 22 ||                                              \
    4659             :     (POPPLER_MAJOR_VERSION == 22 && POPPLER_MINOR_VERSION > 2)
    4660             :             std::optional<GooString> osUserPwd;
    4661             :             if (pszUserPwd)
    4662             :                 osUserPwd = std::optional<GooString>(pszUserPwd);
    4663             :             try
    4664             :             {
    4665             : #if POPPLER_MAJOR_VERSION > 26 ||                                              \
    4666             :     (POPPLER_MAJOR_VERSION == 26 && POPPLER_MINOR_VERSION >= 2)
    4667             :                 poDocPoppler = new PDFDoc(
    4668             :                     std::move(poStream), std::optional<GooString>(), osUserPwd);
    4669             : #else
    4670             :                 poDocPoppler = new PDFDoc(
    4671             :                     poStream.release(), std::optional<GooString>(), osUserPwd);
    4672             : #endif
    4673             :             }
    4674             :             catch (const std::exception &e)
    4675             :             {
    4676             :                 CPLError(CE_Failure, CPLE_AppDefined,
    4677             :                          "PDFDoc::PDFDoc() failed with %s", e.what());
    4678             :                 return nullptr;
    4679             :             }
    4680             : #else
    4681         233 :             GooString *poUserPwd = nullptr;
    4682         233 :             if (pszUserPwd)
    4683           6 :                 poUserPwd = new GooString(pszUserPwd);
    4684         233 :             poDocPoppler = new PDFDoc(poStream.release(), nullptr, poUserPwd);
    4685         233 :             delete poUserPwd;
    4686             : #endif
    4687         233 :             if (globalParamsCreatedByGDAL)
    4688         233 :                 registerErrorCallback();
    4689         233 :             if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
    4690             :             {
    4691           0 :                 PDFFreeDoc(poDocPoppler);
    4692           0 :                 return nullptr;
    4693             :             }
    4694             : 
    4695         233 :             if (!poDocPoppler->isOk() || poDocPoppler->getNumPages() == 0)
    4696             :             {
    4697          13 :                 if (poDocPoppler->getErrorCode() == errEncrypted)
    4698             :                 {
    4699           5 :                     if (pszUserPwd && EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
    4700             :                     {
    4701             :                         pszUserPwd =
    4702           2 :                             PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
    4703           2 :                         PDFFreeDoc(poDocPoppler);
    4704             : 
    4705             :                         /* Reset errors that could have been issued during
    4706             :                          * opening and that */
    4707             :                         /* did not result in an invalid document */
    4708           2 :                         CPLErrorReset();
    4709             : 
    4710           2 :                         continue;
    4711             :                     }
    4712           3 :                     else if (pszUserPwd == nullptr)
    4713             :                     {
    4714           1 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4715             :                                  "A password is needed. You can specify it "
    4716             :                                  "through the PDF_USER_PWD "
    4717             :                                  "configuration option / USER_PWD open option "
    4718             :                                  "(that can be set to ASK_INTERACTIVE)");
    4719             :                     }
    4720             :                     else
    4721             :                     {
    4722           2 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4723             :                                  "Invalid password");
    4724             :                     }
    4725             :                 }
    4726             :                 else
    4727             :                 {
    4728           8 :                     CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
    4729             :                 }
    4730             : 
    4731          11 :                 PDFFreeDoc(poDocPoppler);
    4732          11 :                 return nullptr;
    4733             :             }
    4734         220 :             else if (poDocPoppler->isLinearized() && !bFoundLinearizedHint)
    4735             :             {
    4736             :                 // This is a likely defect of poppler Linearization.cc file that
    4737             :                 // recognizes a file as linearized if the /Linearized hint is
    4738             :                 // missing, but the content of this dictionary are present. But
    4739             :                 // given the hacks of PDFFreeDoc() and
    4740             :                 // VSIPDFFileStream::FillBuffer() opening such a file will
    4741             :                 // result in a null-ptr deref at closing if we try to access a
    4742             :                 // page and build the page cache, so just exit now
    4743           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
    4744             : 
    4745           0 :                 PDFFreeDoc(poDocPoppler);
    4746           0 :                 return nullptr;
    4747             :             }
    4748             :             else
    4749             :             {
    4750         220 :                 break;
    4751             :             }
    4752           2 :         }
    4753             : 
    4754         220 :         poCatalogPoppler = poDocPoppler->getCatalog();
    4755         220 :         if (poCatalogPoppler == nullptr || !poCatalogPoppler->isOk())
    4756             :         {
    4757           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4758             :                      "Invalid PDF : invalid catalog");
    4759           0 :             PDFFreeDoc(poDocPoppler);
    4760           0 :             return nullptr;
    4761             :         }
    4762             : 
    4763         220 :         nPages = poDocPoppler->getNumPages();
    4764             : 
    4765         220 :         if (iPage == 1 && nPages > 10000 &&
    4766           0 :             CPLTestBool(CPLGetConfigOption("GDAL_PDF_LIMIT_PAGE_COUNT", "YES")))
    4767             :         {
    4768           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    4769             :                      "This PDF document reports %d pages. "
    4770             :                      "Limiting count to 10000 for performance reasons. "
    4771             :                      "You may remove this limit by setting the "
    4772             :                      "GDAL_PDF_LIMIT_PAGE_COUNT configuration option to NO",
    4773             :                      nPages);
    4774           0 :             nPages = 10000;
    4775             :         }
    4776             : 
    4777         220 :         if (iPage < 1 || iPage > nPages)
    4778             :         {
    4779           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
    4780             :                      iPage, nPages);
    4781           1 :             PDFFreeDoc(poDocPoppler);
    4782           1 :             return nullptr;
    4783             :         }
    4784             : 
    4785             :         /* Sanity check to validate page count */
    4786         219 :         if (iPage > 1 && nPages <= 10000 && iPage != nPages)
    4787             :         {
    4788           4 :             poPagePoppler = poCatalogPoppler->getPage(nPages);
    4789           4 :             if (poPagePoppler == nullptr || !poPagePoppler->isOk())
    4790             :             {
    4791           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4792             :                          "Invalid PDF : invalid page count");
    4793           0 :                 PDFFreeDoc(poDocPoppler);
    4794           0 :                 return nullptr;
    4795             :             }
    4796             :         }
    4797             : 
    4798         219 :         poPagePoppler = poCatalogPoppler->getPage(iPage);
    4799         219 :         if (poPagePoppler == nullptr || !poPagePoppler->isOk())
    4800             :         {
    4801           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
    4802           0 :             PDFFreeDoc(poDocPoppler);
    4803           0 :             return nullptr;
    4804             :         }
    4805             : 
    4806             : #if POPPLER_MAJOR_VERSION > 25 ||                                              \
    4807             :     (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 3)
    4808             :         const Object &oPageObj = poPagePoppler->getPageObj();
    4809             : #else
    4810             :         /* Here's the dirty part: this is a private member */
    4811             :         /* so we had to #define private public to get it ! */
    4812         219 :         const Object &oPageObj = poPagePoppler->pageObj;
    4813             : #endif
    4814         219 :         if (!oPageObj.isDict())
    4815             :         {
    4816           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4817             :                      "Invalid PDF : !oPageObj.isDict()");
    4818           0 :             PDFFreeDoc(poDocPoppler);
    4819           0 :             return nullptr;
    4820             :         }
    4821             : 
    4822         219 :         poPageObj = new GDALPDFObjectPoppler(&oPageObj);
    4823         219 :         Ref *poPageRef = poCatalogPoppler->getPageRef(iPage);
    4824         219 :         if (poPageRef != nullptr)
    4825             :         {
    4826         438 :             cpl::down_cast<GDALPDFObjectPoppler *>(poPageObj)->SetRefNumAndGen(
    4827         438 :                 GDALPDFObjectNum(poPageRef->num), poPageRef->gen);
    4828             :         }
    4829             :     }
    4830             : #endif  // ~ HAVE_POPPLER
    4831             : 
    4832             : #ifdef HAVE_PODOFO
    4833             :     if (bUseLib.test(PDFLIB_PODOFO) && poPageObj == nullptr)
    4834             :     {
    4835             : #if !(PODOFO_VERSION_MAJOR > 0 ||                                              \
    4836             :       (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10))
    4837             :         PoDoFo::PdfError::EnableDebug(false);
    4838             :         PoDoFo::PdfError::EnableLogging(false);
    4839             : #endif
    4840             : 
    4841             :         poDocPodofo = std::make_unique<PoDoFo::PdfMemDocument>();
    4842             :         try
    4843             :         {
    4844             :             poDocPodofo->Load(pszFilename);
    4845             :         }
    4846             :         catch (PoDoFo::PdfError &oError)
    4847             :         {
    4848             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4849             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4850             :             if (oError.GetCode() == PoDoFo::PdfErrorCode::InvalidPassword)
    4851             : #else
    4852             :             if (oError.GetError() == PoDoFo::ePdfError_InvalidPassword)
    4853             : #endif
    4854             :             {
    4855             :                 if (pszUserPwd)
    4856             :                 {
    4857             :                     pszUserPwd =
    4858             :                         PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
    4859             : 
    4860             :                     try
    4861             :                     {
    4862             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4863             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4864             :                         poDocPodofo =
    4865             :                             std::make_unique<PoDoFo::PdfMemDocument>();
    4866             :                         poDocPodofo->Load(pszFilename, pszUserPwd);
    4867             : #else
    4868             :                         poDocPodofo->SetPassword(pszUserPwd);
    4869             : #endif
    4870             :                     }
    4871             :                     catch (PoDoFo::PdfError &oError2)
    4872             :                     {
    4873             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4874             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4875             :                         if (oError2.GetCode() ==
    4876             :                             PoDoFo::PdfErrorCode::InvalidPassword)
    4877             : #else
    4878             :                         if (oError2.GetError() ==
    4879             :                             PoDoFo::ePdfError_InvalidPassword)
    4880             : #endif
    4881             :                         {
    4882             :                             CPLError(CE_Failure, CPLE_AppDefined,
    4883             :                                      "Invalid password");
    4884             :                         }
    4885             :                         else
    4886             :                         {
    4887             :                             CPLError(CE_Failure, CPLE_AppDefined,
    4888             :                                      "Invalid PDF : %s", oError2.what());
    4889             :                         }
    4890             :                         return nullptr;
    4891             :                     }
    4892             :                     catch (...)
    4893             :                     {
    4894             :                         CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
    4895             :                         return nullptr;
    4896             :                     }
    4897             :                 }
    4898             :                 else
    4899             :                 {
    4900             :                     CPLError(CE_Failure, CPLE_AppDefined,
    4901             :                              "A password is needed. You can specify it through "
    4902             :                              "the PDF_USER_PWD "
    4903             :                              "configuration option / USER_PWD open option "
    4904             :                              "(that can be set to ASK_INTERACTIVE)");
    4905             :                     return nullptr;
    4906             :                 }
    4907             :             }
    4908             :             else
    4909             :             {
    4910             :                 CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
    4911             :                          oError.what());
    4912             :                 return nullptr;
    4913             :             }
    4914             :         }
    4915             :         catch (...)
    4916             :         {
    4917             :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
    4918             :             return nullptr;
    4919             :         }
    4920             : 
    4921             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4922             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4923             :         auto &oPageCollections = poDocPodofo->GetPages();
    4924             :         nPages = static_cast<int>(oPageCollections.GetCount());
    4925             : #else
    4926             :         nPages = poDocPodofo->GetPageCount();
    4927             : #endif
    4928             :         if (iPage < 1 || iPage > nPages)
    4929             :         {
    4930             :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
    4931             :                      iPage, nPages);
    4932             :             return nullptr;
    4933             :         }
    4934             : 
    4935             :         try
    4936             :         {
    4937             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4938             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4939             :             /* Sanity check to validate page count */
    4940             :             if (iPage != nPages)
    4941             :                 CPL_IGNORE_RET_VAL(oPageCollections.GetPageAt(nPages - 1));
    4942             : 
    4943             :             poPagePodofo = &oPageCollections.GetPageAt(iPage - 1);
    4944             : #else
    4945             :             /* Sanity check to validate page count */
    4946             :             if (iPage != nPages)
    4947             :                 CPL_IGNORE_RET_VAL(poDocPodofo->GetPage(nPages - 1));
    4948             : 
    4949             :             poPagePodofo = poDocPodofo->GetPage(iPage - 1);
    4950             : #endif
    4951             :         }
    4952             :         catch (PoDoFo::PdfError &oError)
    4953             :         {
    4954             :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
    4955             :                      oError.what());
    4956             :             return nullptr;
    4957             :         }
    4958             :         catch (...)
    4959             :         {
    4960             :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
    4961             :             return nullptr;
    4962             :         }
    4963             : 
    4964             :         if (poPagePodofo == nullptr)
    4965             :         {
    4966             :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
    4967             :             return nullptr;
    4968             :         }
    4969             : 
    4970             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    4971             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    4972             :         const PoDoFo::PdfObject *pObj = &poPagePodofo->GetObject();
    4973             : #else
    4974             :         const PoDoFo::PdfObject *pObj = poPagePodofo->GetObject();
    4975             : #endif
    4976             :         poPageObj = new GDALPDFObjectPodofo(pObj, poDocPodofo->GetObjects());
    4977             :     }
    4978             : #endif  // ~ HAVE_PODOFO
    4979             : 
    4980             : #ifdef HAVE_PDFIUM
    4981             :     if (bUseLib.test(PDFLIB_PDFIUM) && poPageObj == nullptr)
    4982             :     {
    4983             :         if (!LoadPdfiumDocumentPage(pszFilename, pszUserPwd, iPage,
    4984             :                                     &poDocPdfium, &poPagePdfium, &nPages))
    4985             :         {
    4986             :             // CPLError is called inside function
    4987             :             return nullptr;
    4988             :         }
    4989             : 
    4990             :         const auto pageObj = poPagePdfium->page->GetDict();
    4991             :         if (pageObj == nullptr)
    4992             :         {
    4993             :             CPLError(CE_Failure, CPLE_AppDefined,
    4994             :                      "Invalid PDF : invalid page object");
    4995             :             UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
    4996             :             return nullptr;
    4997             :         }
    4998             :         poPageObj = GDALPDFObjectPdfium::Build(pageObj);
    4999             :     }
    5000             : #endif  // ~ HAVE_PDFIUM
    5001             : 
    5002         219 :     if (poPageObj == nullptr)
    5003           0 :         return nullptr;
    5004         219 :     GDALPDFDictionary *poPageDict = poPageObj->GetDictionary();
    5005         219 :     if (poPageDict == nullptr)
    5006             :     {
    5007           0 :         delete poPageObj;
    5008             : 
    5009           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5010             :                  "Invalid PDF : poPageDict == nullptr");
    5011             : #ifdef HAVE_POPPLER
    5012           0 :         if (bUseLib.test(PDFLIB_POPPLER))
    5013           0 :             PDFFreeDoc(poDocPoppler);
    5014             : #endif
    5015             : #ifdef HAVE_PDFIUM
    5016             :         if (bUseLib.test(PDFLIB_PDFIUM))
    5017             :         {
    5018             :             UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
    5019             :         }
    5020             : #endif
    5021           0 :         return nullptr;
    5022             :     }
    5023             : 
    5024         219 :     const char *pszDumpObject = CPLGetConfigOption("PDF_DUMP_OBJECT", nullptr);
    5025         219 :     if (pszDumpObject != nullptr)
    5026             :     {
    5027           2 :         GDALPDFDumper oDumper(pszFilename, pszDumpObject);
    5028           1 :         oDumper.Dump(poPageObj);
    5029             :     }
    5030             : 
    5031         219 :     PDFDataset *poDS = new PDFDataset();
    5032         219 :     poDS->m_fp = std::move(fp);
    5033         219 :     poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    5034         219 :     poDS->m_bUseLib = bUseLib;
    5035         219 :     poDS->m_osFilename = pszFilename;
    5036         219 :     poDS->eAccess = poOpenInfo->eAccess;
    5037             : 
    5038         219 :     if (nPages > 1 && !bOpenSubdataset)
    5039             :     {
    5040             :         int i;
    5041           4 :         CPLStringList aosList;
    5042           8 :         for (i = 0; i < nPages; i++)
    5043             :         {
    5044             :             char szKey[32];
    5045           6 :             snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_NAME", i + 1);
    5046             :             aosList.AddNameValue(
    5047           6 :                 szKey, CPLSPrintf("PDF:%d:%s", i + 1, poOpenInfo->pszFilename));
    5048           6 :             snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_DESC", i + 1);
    5049             :             aosList.AddNameValue(szKey, CPLSPrintf("Page %d of %s", i + 1,
    5050           6 :                                                    poOpenInfo->pszFilename));
    5051             :         }
    5052           2 :         poDS->SetMetadata(aosList.List(), "SUBDATASETS");
    5053             :     }
    5054             : 
    5055             : #ifdef HAVE_POPPLER
    5056         219 :     poDS->m_poDocPoppler = poDocPoppler;
    5057             : #endif
    5058             : #ifdef HAVE_PODOFO
    5059             :     poDS->m_poDocPodofo = poDocPodofo.release();
    5060             : #endif
    5061             : #ifdef HAVE_PDFIUM
    5062             :     poDS->m_poDocPdfium = poDocPdfium;
    5063             :     poDS->m_poPagePdfium = poPagePdfium;
    5064             : #endif
    5065         219 :     poDS->m_poPageObj = poPageObj;
    5066         219 :     poDS->m_osUserPwd = pszUserPwd ? pszUserPwd : "";
    5067         219 :     poDS->m_iPage = iPage;
    5068             : 
    5069             :     const char *pszDumpCatalog =
    5070         219 :         CPLGetConfigOption("PDF_DUMP_CATALOG", nullptr);
    5071         219 :     if (pszDumpCatalog != nullptr)
    5072             :     {
    5073           0 :         GDALPDFDumper oDumper(pszFilename, pszDumpCatalog);
    5074           0 :         auto poCatalog = poDS->GetCatalog();
    5075           0 :         if (poCatalog)
    5076           0 :             oDumper.Dump(poCatalog);
    5077             :     }
    5078             : 
    5079         219 :     int nBandsGuessed = 0;
    5080         219 :     if (nImageNum < 0)
    5081             :     {
    5082         219 :         double dfDPI = std::numeric_limits<double>::quiet_NaN();
    5083         219 :         poDS->GuessDPIAndBandCount(poPageDict, dfDPI, nBandsGuessed);
    5084         219 :         if (!std::isnan(dfDPI))
    5085         203 :             poDS->m_dfDPI = dfDPI;
    5086         219 :         if (nBandsGuessed < 4)
    5087         212 :             nBandsGuessed = 0;
    5088             :     }
    5089             : 
    5090         219 :     int nTargetBands = 3;
    5091             : #ifdef HAVE_PDFIUM
    5092             :     // Use Alpha channel for PDFIUM as default format RGBA
    5093             :     if (bUseLib.test(PDFLIB_PDFIUM))
    5094             :         nTargetBands = 4;
    5095             : #endif
    5096         219 :     if (nBandsGuessed)
    5097           7 :         nTargetBands = nBandsGuessed;
    5098             :     const char *pszPDFBands =
    5099         219 :         GetOption(poOpenInfo->papszOpenOptions, "BANDS", nullptr);
    5100         219 :     if (pszPDFBands)
    5101             :     {
    5102           2 :         nTargetBands = atoi(pszPDFBands);
    5103           2 :         if (nTargetBands != 3 && nTargetBands != 4)
    5104             :         {
    5105           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    5106             :                      "Invalid value for GDAL_PDF_BANDS. Using 3 as a fallback");
    5107           0 :             nTargetBands = 3;
    5108             :         }
    5109             :     }
    5110             : #ifdef HAVE_PODOFO
    5111             :     if (bUseLib.test(PDFLIB_PODOFO) && nTargetBands == 4 &&
    5112             :         poDS->m_aiTiles.empty())
    5113             :     {
    5114             :         CPLError(CE_Warning, CPLE_NotSupported,
    5115             :                  "GDAL_PDF_BANDS=4 not supported when PDF driver is compiled "
    5116             :                  "against Podofo. "
    5117             :                  "Using 3 as a fallback");
    5118             :         nTargetBands = 3;
    5119             :     }
    5120             : #endif
    5121             : 
    5122             :     // Create bands. We must do that before initializing PAM. But at that point
    5123             :     // we don't know yet the dataset dimension, since we need to know the DPI,
    5124             :     // that we can fully know only after loading PAM... So we will have to patch
    5125             :     // later the band dimension.
    5126         883 :     for (int iBand = 1; iBand <= nTargetBands; iBand++)
    5127             :     {
    5128         664 :         if (poDS->m_poImageObj != nullptr)
    5129           0 :             poDS->SetBand(iBand, new PDFImageRasterBand(poDS, iBand));
    5130             :         else
    5131         664 :             poDS->SetBand(iBand, new PDFRasterBand(poDS, iBand, 0));
    5132             :     }
    5133             : 
    5134             :     /* -------------------------------------------------------------------- */
    5135             :     /*      Initialize any PAM information.                                 */
    5136             :     /* -------------------------------------------------------------------- */
    5137         219 :     if (bOpenSubdataset || bOpenSubdatasetImage)
    5138             :     {
    5139          12 :         poDS->SetPhysicalFilename(pszFilename);
    5140          12 :         poDS->SetSubdatasetName(osSubdatasetName.c_str());
    5141             :     }
    5142             :     else
    5143             :     {
    5144         207 :         poDS->SetDescription(poOpenInfo->pszFilename);
    5145             :     }
    5146             : 
    5147         219 :     poDS->TryLoadXML();
    5148             : 
    5149             :     // Establish DPI
    5150             :     const char *pszDPI =
    5151         219 :         GetOption(poOpenInfo->papszOpenOptions, "DPI", nullptr);
    5152         219 :     if (pszDPI == nullptr)
    5153         213 :         pszDPI = poDS->GDALPamDataset::GetMetadataItem("DPI");
    5154         219 :     if (pszDPI != nullptr)
    5155             :     {
    5156           7 :         poDS->m_dfDPI = CPLAtof(pszDPI);
    5157             : 
    5158           7 :         if (CPLTestBool(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
    5159             :                                              "SAVE_DPI_TO_PAM", "FALSE")))
    5160             :         {
    5161           2 :             const std::string osDPI(pszDPI);
    5162           1 :             poDS->GDALPamDataset::SetMetadataItem("DPI", osDPI.c_str());
    5163             :         }
    5164             :     }
    5165             : 
    5166         219 :     if (poDS->m_dfDPI < 1e-2 || poDS->m_dfDPI > 7200)
    5167             :     {
    5168           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    5169             :                  "Invalid value for GDAL_PDF_DPI. Using default value instead");
    5170           0 :         poDS->m_dfDPI = GDAL_DEFAULT_DPI;
    5171             :     }
    5172         219 :     poDS->SetMetadataItem("DPI", CPLSPrintf("%.16g", poDS->m_dfDPI));
    5173             : 
    5174         219 :     double dfX1 = 0.0;
    5175         219 :     double dfY1 = 0.0;
    5176         219 :     double dfX2 = 0.0;
    5177         219 :     double dfY2 = 0.0;
    5178             : 
    5179             : #ifdef HAVE_POPPLER
    5180         219 :     if (bUseLib.test(PDFLIB_POPPLER))
    5181             :     {
    5182         219 :         const auto *psMediaBox = poPagePoppler->getMediaBox();
    5183         219 :         dfX1 = psMediaBox->x1;
    5184         219 :         dfY1 = psMediaBox->y1;
    5185         219 :         dfX2 = psMediaBox->x2;
    5186         219 :         dfY2 = psMediaBox->y2;
    5187             :     }
    5188             : #endif
    5189             : 
    5190             : #ifdef HAVE_PODOFO
    5191             :     if (bUseLib.test(PDFLIB_PODOFO))
    5192             :     {
    5193             :         CPLAssert(poPagePodofo);
    5194             :         auto oMediaBox = poPagePodofo->GetMediaBox();
    5195             :         dfX1 = oMediaBox.GetLeft();
    5196             :         dfY1 = oMediaBox.GetBottom();
    5197             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    5198             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    5199             :         dfX2 = dfX1 + oMediaBox.Width;
    5200             :         dfY2 = dfY1 + oMediaBox.Height;
    5201             : #else
    5202             :         dfX2 = dfX1 + oMediaBox.GetWidth();
    5203             :         dfY2 = dfY1 + oMediaBox.GetHeight();
    5204             : #endif
    5205             :     }
    5206             : #endif
    5207             : 
    5208             : #ifdef HAVE_PDFIUM
    5209             :     if (bUseLib.test(PDFLIB_PDFIUM))
    5210             :     {
    5211             :         CPLAssert(poPagePdfium);
    5212             :         CFX_FloatRect rect = poPagePdfium->page->GetBBox();
    5213             :         dfX1 = rect.left;
    5214             :         dfX2 = rect.right;
    5215             :         dfY1 = rect.bottom;
    5216             :         dfY2 = rect.top;
    5217             :     }
    5218             : #endif  // ~ HAVE_PDFIUM
    5219             : 
    5220         219 :     double dfUserUnit = poDS->m_dfDPI * USER_UNIT_IN_INCH;
    5221         219 :     poDS->m_dfPageWidth = dfX2 - dfX1;
    5222         219 :     poDS->m_dfPageHeight = dfY2 - dfY1;
    5223             :     // CPLDebug("PDF", "left=%f right=%f bottom=%f top=%f", dfX1, dfX2, dfY1,
    5224             :     // dfY2);
    5225         219 :     const double dfXSize = floor((dfX2 - dfX1) * dfUserUnit + 0.5);
    5226         219 :     const double dfYSize = floor((dfY2 - dfY1) * dfUserUnit + 0.5);
    5227         219 :     if (!(dfXSize >= 0 && dfXSize <= INT_MAX && dfYSize >= 0 &&
    5228         219 :           dfYSize <= INT_MAX))
    5229             :     {
    5230           0 :         delete poDS;
    5231           0 :         return nullptr;
    5232             :     }
    5233         219 :     poDS->nRasterXSize = static_cast<int>(dfXSize);
    5234         219 :     poDS->nRasterYSize = static_cast<int>(dfYSize);
    5235             : 
    5236         219 :     if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize))
    5237             :     {
    5238           0 :         delete poDS;
    5239           0 :         return nullptr;
    5240             :     }
    5241             : 
    5242         219 :     double dfRotation = 0;
    5243             : #ifdef HAVE_POPPLER
    5244         219 :     if (bUseLib.test(PDFLIB_POPPLER))
    5245         219 :         dfRotation = poDocPoppler->getPageRotate(iPage);
    5246             : #endif
    5247             : 
    5248             : #ifdef HAVE_PODOFO
    5249             :     if (bUseLib.test(PDFLIB_PODOFO))
    5250             :     {
    5251             :         CPLAssert(poPagePodofo);
    5252             : #if PODOFO_VERSION_MAJOR >= 1
    5253             :         poPagePodofo->TryGetRotationRaw(dfRotation);
    5254             : #elif (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    5255             :         dfRotation = poPagePodofo->GetRotationRaw();
    5256             : #else
    5257             :         dfRotation = poPagePodofo->GetRotation();
    5258             : #endif
    5259             :     }
    5260             : #endif
    5261             : 
    5262             : #ifdef HAVE_PDFIUM
    5263             :     if (bUseLib.test(PDFLIB_PDFIUM))
    5264             :     {
    5265             :         CPLAssert(poPagePdfium);
    5266             :         dfRotation = poPagePdfium->page->GetPageRotation() * 90;
    5267             :     }
    5268             : #endif
    5269             : 
    5270         219 :     if (dfRotation == 90 || dfRotation == -90 || dfRotation == 270)
    5271             :     {
    5272             : /* FIXME: the podofo case should be implemented. This needs to rotate */
    5273             : /* the output of pdftoppm */
    5274             : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
    5275           0 :         if (bUseLib.test(PDFLIB_POPPLER) || bUseLib.test(PDFLIB_PDFIUM))
    5276             :         {
    5277           0 :             int nTmp = poDS->nRasterXSize;
    5278           0 :             poDS->nRasterXSize = poDS->nRasterYSize;
    5279           0 :             poDS->nRasterYSize = nTmp;
    5280             :         }
    5281             : #endif
    5282             :     }
    5283             : 
    5284         219 :     if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
    5285             :     {
    5286           2 :         poDS->m_nBlockXSize = 512;
    5287           2 :         poDS->m_nBlockYSize = 512;
    5288             :     }
    5289             :     /* Check if the PDF is only made of regularly tiled images */
    5290             :     /* (like some USGS GeoPDF production) */
    5291         380 :     else if (dfRotation == 0.0 && !poDS->m_asTiles.empty() &&
    5292         163 :              EQUAL(GetOption(poOpenInfo->papszOpenOptions, "LAYERS", "ALL"),
    5293             :                    "ALL"))
    5294             :     {
    5295         163 :         poDS->CheckTiledRaster();
    5296         163 :         if (!poDS->m_aiTiles.empty())
    5297           9 :             poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    5298             :     }
    5299             : 
    5300         219 :     GDALPDFObject *poLGIDict = nullptr;
    5301         219 :     GDALPDFObject *poVP = nullptr;
    5302         219 :     int bIsOGCBP = FALSE;
    5303         219 :     if ((poLGIDict = poPageDict->Get("LGIDict")) != nullptr && nImageNum < 0)
    5304             :     {
    5305             :         /* Cf 08-139r3_GeoPDF_Encoding_Best_Practice_Version_2.2.pdf */
    5306           5 :         CPLDebug("PDF", "OGC Encoding Best Practice style detected");
    5307           5 :         if (poDS->ParseLGIDictObject(poLGIDict))
    5308             :         {
    5309           5 :             if (poDS->m_bHasCTM)
    5310             :             {
    5311           5 :                 if (dfRotation == 90)
    5312             :                 {
    5313           0 :                     poDS->m_gt.xorig = poDS->m_adfCTM[4];
    5314           0 :                     poDS->m_gt.xscale = poDS->m_adfCTM[2] / dfUserUnit;
    5315           0 :                     poDS->m_gt.xrot = poDS->m_adfCTM[0] / dfUserUnit;
    5316           0 :                     poDS->m_gt.yorig = poDS->m_adfCTM[5];
    5317           0 :                     poDS->m_gt.yrot = poDS->m_adfCTM[3] / dfUserUnit;
    5318           0 :                     poDS->m_gt.yscale = poDS->m_adfCTM[1] / dfUserUnit;
    5319             :                 }
    5320           5 :                 else if (dfRotation == -90 || dfRotation == 270)
    5321             :                 {
    5322           0 :                     poDS->m_gt.xorig =
    5323           0 :                         poDS->m_adfCTM[4] +
    5324           0 :                         poDS->m_adfCTM[2] * poDS->m_dfPageHeight +
    5325           0 :                         poDS->m_adfCTM[0] * poDS->m_dfPageWidth;
    5326           0 :                     poDS->m_gt.xscale = -poDS->m_adfCTM[2] / dfUserUnit;
    5327           0 :                     poDS->m_gt.xrot = -poDS->m_adfCTM[0] / dfUserUnit;
    5328           0 :                     poDS->m_gt.yorig =
    5329           0 :                         poDS->m_adfCTM[5] +
    5330           0 :                         poDS->m_adfCTM[3] * poDS->m_dfPageHeight +
    5331           0 :                         poDS->m_adfCTM[1] * poDS->m_dfPageWidth;
    5332           0 :                     poDS->m_gt.yrot = -poDS->m_adfCTM[3] / dfUserUnit;
    5333           0 :                     poDS->m_gt.yscale = -poDS->m_adfCTM[1] / dfUserUnit;
    5334             :                 }
    5335             :                 else
    5336             :                 {
    5337           5 :                     poDS->m_gt.xorig = poDS->m_adfCTM[4] +
    5338           5 :                                        poDS->m_adfCTM[2] * dfY2 +
    5339           5 :                                        poDS->m_adfCTM[0] * dfX1;
    5340           5 :                     poDS->m_gt.xscale = poDS->m_adfCTM[0] / dfUserUnit;
    5341           5 :                     poDS->m_gt.xrot = -poDS->m_adfCTM[2] / dfUserUnit;
    5342           5 :                     poDS->m_gt.yorig = poDS->m_adfCTM[5] +
    5343           5 :                                        poDS->m_adfCTM[3] * dfY2 +
    5344           5 :                                        poDS->m_adfCTM[1] * dfX1;
    5345           5 :                     poDS->m_gt.yrot = poDS->m_adfCTM[1] / dfUserUnit;
    5346           5 :                     poDS->m_gt.yscale = -poDS->m_adfCTM[3] / dfUserUnit;
    5347             :                 }
    5348             : 
    5349           5 :                 poDS->m_bGeoTransformValid = true;
    5350             :             }
    5351             : 
    5352           5 :             bIsOGCBP = TRUE;
    5353             : 
    5354             :             int i;
    5355           5 :             for (i = 0; i < poDS->m_nGCPCount; i++)
    5356             :             {
    5357           0 :                 if (dfRotation == 90)
    5358             :                 {
    5359           0 :                     double dfPixel =
    5360           0 :                         poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
    5361           0 :                     double dfLine =
    5362           0 :                         poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
    5363           0 :                     poDS->m_pasGCPList[i].dfGCPPixel = dfLine;
    5364           0 :                     poDS->m_pasGCPList[i].dfGCPLine = dfPixel;
    5365             :                 }
    5366           0 :                 else if (dfRotation == -90 || dfRotation == 270)
    5367             :                 {
    5368           0 :                     double dfPixel =
    5369           0 :                         poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
    5370           0 :                     double dfLine =
    5371           0 :                         poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
    5372           0 :                     poDS->m_pasGCPList[i].dfGCPPixel =
    5373           0 :                         poDS->nRasterXSize - dfLine;
    5374           0 :                     poDS->m_pasGCPList[i].dfGCPLine =
    5375           0 :                         poDS->nRasterYSize - dfPixel;
    5376             :                 }
    5377             :                 else
    5378             :                 {
    5379           0 :                     poDS->m_pasGCPList[i].dfGCPPixel =
    5380           0 :                         (-dfX1 + poDS->m_pasGCPList[i].dfGCPPixel) * dfUserUnit;
    5381           0 :                     poDS->m_pasGCPList[i].dfGCPLine =
    5382           0 :                         (dfY2 - poDS->m_pasGCPList[i].dfGCPLine) * dfUserUnit;
    5383             :                 }
    5384             :             }
    5385             :         }
    5386             :     }
    5387         214 :     else if ((poVP = poPageDict->Get("VP")) != nullptr && nImageNum < 0)
    5388             :     {
    5389             :         /* Cf adobe_supplement_iso32000.pdf */
    5390         155 :         CPLDebug("PDF", "Adobe ISO32000 style Geospatial PDF perhaps ?");
    5391         155 :         if (dfX1 != 0 || dfY1 != 0)
    5392             :         {
    5393           0 :             CPLDebug("PDF", "non null dfX1 or dfY1 values. untested case...");
    5394             :         }
    5395         155 :         poDS->ParseVP(poVP, dfX2 - dfX1, dfY2 - dfY1);
    5396             :     }
    5397             :     else
    5398             :     {
    5399             :         GDALPDFObject *poXObject =
    5400          59 :             poPageDict->LookupObject("Resources.XObject");
    5401             : 
    5402         116 :         if (poXObject != nullptr &&
    5403          57 :             poXObject->GetType() == PDFObjectType_Dictionary)
    5404             :         {
    5405          57 :             GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
    5406          57 :             const auto &oMap = poXObjectDict->GetValues();
    5407          57 :             int nSubDataset = 0;
    5408         231 :             for (const auto &[osKey, poObj] : oMap)
    5409             :             {
    5410         174 :                 if (poObj->GetType() == PDFObjectType_Dictionary)
    5411             :                 {
    5412         174 :                     GDALPDFDictionary *poDict = poObj->GetDictionary();
    5413         174 :                     GDALPDFObject *poSubtype = nullptr;
    5414         174 :                     GDALPDFObject *poMeasure = nullptr;
    5415         174 :                     GDALPDFObject *poWidth = nullptr;
    5416         174 :                     GDALPDFObject *poHeight = nullptr;
    5417         174 :                     int nW = 0;
    5418         174 :                     int nH = 0;
    5419         174 :                     if ((poSubtype = poDict->Get("Subtype")) != nullptr &&
    5420         348 :                         poSubtype->GetType() == PDFObjectType_Name &&
    5421         174 :                         poSubtype->GetName() == "Image" &&
    5422         129 :                         (poMeasure = poDict->Get("Measure")) != nullptr &&
    5423           0 :                         poMeasure->GetType() == PDFObjectType_Dictionary &&
    5424           0 :                         (poWidth = poDict->Get("Width")) != nullptr &&
    5425           0 :                         poWidth->GetType() == PDFObjectType_Int &&
    5426           0 :                         (nW = poWidth->GetInt()) > 0 &&
    5427           0 :                         (poHeight = poDict->Get("Height")) != nullptr &&
    5428         348 :                         poHeight->GetType() == PDFObjectType_Int &&
    5429           0 :                         (nH = poHeight->GetInt()) > 0)
    5430             :                     {
    5431           0 :                         if (nImageNum < 0)
    5432           0 :                             CPLDebug("PDF",
    5433             :                                      "Measure found on Image object (%d)",
    5434           0 :                                      poObj->GetRefNum().toInt());
    5435             : 
    5436           0 :                         GDALPDFObject *poColorSpace = poDict->Get("ColorSpace");
    5437             :                         GDALPDFObject *poBitsPerComponent =
    5438           0 :                             poDict->Get("BitsPerComponent");
    5439           0 :                         if (poObj->GetRefNum().toBool() &&
    5440           0 :                             poObj->GetRefGen() == 0 &&
    5441           0 :                             poColorSpace != nullptr &&
    5442           0 :                             poColorSpace->GetType() == PDFObjectType_Name &&
    5443           0 :                             (poColorSpace->GetName() == "DeviceGray" ||
    5444           0 :                              poColorSpace->GetName() == "DeviceRGB") &&
    5445           0 :                             (poBitsPerComponent == nullptr ||
    5446           0 :                              (poBitsPerComponent->GetType() ==
    5447           0 :                                   PDFObjectType_Int &&
    5448           0 :                               poBitsPerComponent->GetInt() == 8)))
    5449             :                         {
    5450           0 :                             if (nImageNum < 0)
    5451             :                             {
    5452           0 :                                 nSubDataset++;
    5453           0 :                                 poDS->SetMetadataItem(
    5454             :                                     CPLSPrintf("SUBDATASET_%d_NAME",
    5455             :                                                nSubDataset),
    5456             :                                     CPLSPrintf("PDF_IMAGE:%d:%d:%s", iPage,
    5457           0 :                                                poObj->GetRefNum().toInt(),
    5458             :                                                pszFilename),
    5459             :                                     "SUBDATASETS");
    5460           0 :                                 poDS->SetMetadataItem(
    5461             :                                     CPLSPrintf("SUBDATASET_%d_DESC",
    5462             :                                                nSubDataset),
    5463             :                                     CPLSPrintf("Georeferenced image of size "
    5464             :                                                "%dx%d of page %d of %s",
    5465             :                                                nW, nH, iPage, pszFilename),
    5466             :                                     "SUBDATASETS");
    5467             :                             }
    5468           0 :                             else if (poObj->GetRefNum().toInt() == nImageNum)
    5469             :                             {
    5470           0 :                                 poDS->nRasterXSize = nW;
    5471           0 :                                 poDS->nRasterYSize = nH;
    5472           0 :                                 poDS->ParseMeasure(poMeasure, nW, nH, 0, nH, nW,
    5473             :                                                    0);
    5474           0 :                                 poDS->m_poImageObj = poObj;
    5475           0 :                                 if (poColorSpace->GetName() == "DeviceGray")
    5476             :                                 {
    5477           0 :                                     for (int i = 1; i < poDS->nBands; ++i)
    5478           0 :                                         delete poDS->papoBands[i];
    5479           0 :                                     poDS->nBands = 1;
    5480             :                                 }
    5481           0 :                                 break;
    5482             :                             }
    5483             :                         }
    5484             :                     }
    5485             :                 }
    5486             :             }
    5487             :         }
    5488             : 
    5489          59 :         if (nImageNum >= 0 && poDS->m_poImageObj == nullptr)
    5490             :         {
    5491           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot find image %d",
    5492             :                      nImageNum);
    5493           0 :             delete poDS;
    5494           0 :             return nullptr;
    5495             :         }
    5496             : 
    5497             :         /* Not a geospatial PDF doc */
    5498             :     }
    5499             : 
    5500             :     /* If pixel size or top left coordinates are very close to an int, round
    5501             :      * them to the int */
    5502         219 :     double dfEps =
    5503         219 :         (fabs(poDS->m_gt.xorig) > 1e5 && fabs(poDS->m_gt.yorig) > 1e5) ? 1e-5
    5504             :                                                                        : 1e-8;
    5505         219 :     poDS->m_gt.xorig = ROUND_IF_CLOSE(poDS->m_gt.xorig, dfEps);
    5506         219 :     poDS->m_gt.xscale = ROUND_IF_CLOSE(poDS->m_gt.xscale);
    5507         219 :     poDS->m_gt.yorig = ROUND_IF_CLOSE(poDS->m_gt.yorig, dfEps);
    5508         219 :     poDS->m_gt.yscale = ROUND_IF_CLOSE(poDS->m_gt.yscale);
    5509             : 
    5510         219 :     if (bUseLib.test(PDFLIB_PDFIUM))
    5511             :     {
    5512             :         // Attempt to "fix" the loss of precision due to the use of float32 for
    5513             :         // numbers by pdfium
    5514           0 :         if ((fabs(poDS->m_gt.xorig) > 1e5 || fabs(poDS->m_gt.yorig) > 1e5) &&
    5515           0 :             fabs(poDS->m_gt.xorig - std::round(poDS->m_gt.xorig)) <
    5516           0 :                 1e-6 * fabs(poDS->m_gt.xorig) &&
    5517           0 :             fabs(poDS->m_gt.xscale - std::round(poDS->m_gt.xscale)) <
    5518           0 :                 1e-3 * fabs(poDS->m_gt.xscale) &&
    5519           0 :             fabs(poDS->m_gt.yorig - std::round(poDS->m_gt.yorig)) <
    5520           0 :                 1e-6 * fabs(poDS->m_gt.yorig) &&
    5521           0 :             fabs(poDS->m_gt.yscale - std::round(poDS->m_gt.yscale)) <
    5522           0 :                 1e-3 * fabs(poDS->m_gt.yscale))
    5523             :         {
    5524           0 :             for (int i = 0; i < 6; i++)
    5525             :             {
    5526           0 :                 poDS->m_gt[i] = std::round(poDS->m_gt[i]);
    5527             :             }
    5528             :         }
    5529             :     }
    5530             : 
    5531         219 :     if (poDS->m_poNeatLine)
    5532             :     {
    5533         159 :         char *pszNeatLineWkt = nullptr;
    5534         159 :         OGRLinearRing *poRing = poDS->m_poNeatLine->getExteriorRing();
    5535             :         /* Adobe style is already in target SRS units */
    5536         159 :         if (bIsOGCBP)
    5537             :         {
    5538           5 :             int nPoints = poRing->getNumPoints();
    5539             :             int i;
    5540             : 
    5541          30 :             for (i = 0; i < nPoints; i++)
    5542             :             {
    5543             :                 double x, y;
    5544          25 :                 if (dfRotation == 90.0)
    5545             :                 {
    5546           0 :                     x = poRing->getY(i) * dfUserUnit;
    5547           0 :                     y = poRing->getX(i) * dfUserUnit;
    5548             :                 }
    5549          25 :                 else if (dfRotation == -90.0 || dfRotation == 270.0)
    5550             :                 {
    5551           0 :                     x = poDS->nRasterXSize - poRing->getY(i) * dfUserUnit;
    5552           0 :                     y = poDS->nRasterYSize - poRing->getX(i) * dfUserUnit;
    5553             :                 }
    5554             :                 else
    5555             :                 {
    5556          25 :                     x = (-dfX1 + poRing->getX(i)) * dfUserUnit;
    5557          25 :                     y = (dfY2 - poRing->getY(i)) * dfUserUnit;
    5558             :                 }
    5559          25 :                 double X = poDS->m_gt.xorig + x * poDS->m_gt.xscale +
    5560          25 :                            y * poDS->m_gt.xrot;
    5561          25 :                 double Y = poDS->m_gt.yorig + x * poDS->m_gt.yrot +
    5562          25 :                            y * poDS->m_gt.yscale;
    5563          25 :                 poRing->setPoint(i, X, Y);
    5564             :             }
    5565             :         }
    5566         159 :         poRing->closeRings();
    5567             : 
    5568         159 :         poDS->m_poNeatLine->exportToWkt(&pszNeatLineWkt);
    5569         159 :         if (nImageNum < 0)
    5570         159 :             poDS->SetMetadataItem("NEATLINE", pszNeatLineWkt);
    5571         159 :         CPLFree(pszNeatLineWkt);
    5572             :     }
    5573             : 
    5574         219 :     poDS->MapOCGsToPages();
    5575             : 
    5576             : #ifdef HAVE_POPPLER
    5577         219 :     if (bUseLib.test(PDFLIB_POPPLER))
    5578             :     {
    5579         219 :         auto poMetadata = poCatalogPoppler->readMetadata();
    5580         219 :         if (poMetadata)
    5581             :         {
    5582          19 :             const char *pszContent = poMetadata->c_str();
    5583          19 :             if (pszContent != nullptr &&
    5584          19 :                 STARTS_WITH(pszContent, "<?xpacket begin="))
    5585             :             {
    5586          19 :                 const char *const apszMDList[2] = {pszContent, nullptr};
    5587          19 :                 poDS->SetMetadata(const_cast<char **>(apszMDList), "xml:XMP");
    5588             :             }
    5589             : #if (POPPLER_MAJOR_VERSION < 21 ||                                             \
    5590             :      (POPPLER_MAJOR_VERSION == 21 && POPPLER_MINOR_VERSION < 10))
    5591          19 :             delete poMetadata;
    5592             : #endif
    5593             :         }
    5594             : 
    5595             :         /* Read Info object */
    5596             :         /* The test is necessary since with some corrupted PDFs
    5597             :          * poDocPoppler->getDocInfo() */
    5598             :         /* might abort() */
    5599         219 :         if (poDocPoppler->getXRef()->isOk())
    5600             :         {
    5601         438 :             Object oInfo = poDocPoppler->getDocInfo();
    5602         438 :             GDALPDFObjectPoppler oInfoObjPoppler(&oInfo, FALSE);
    5603         219 :             poDS->ParseInfo(&oInfoObjPoppler);
    5604             :         }
    5605             : 
    5606             :         /* Find layers */
    5607         426 :         poDS->FindLayersPoppler(
    5608         207 :             (bOpenSubdataset || bOpenSubdatasetImage) ? iPage : 0);
    5609             : 
    5610             :         /* Turn user specified layers on or off */
    5611         219 :         poDS->TurnLayersOnOffPoppler();
    5612             :     }
    5613             : #endif
    5614             : 
    5615             : #ifdef HAVE_PODOFO
    5616             :     if (bUseLib.test(PDFLIB_PODOFO))
    5617             :     {
    5618             :         for (const auto &obj : poDS->m_poDocPodofo->GetObjects())
    5619             :         {
    5620             :             GDALPDFObjectPodofo oObjPodofo(obj,
    5621             :                                            poDS->m_poDocPodofo->GetObjects());
    5622             :             poDS->FindXMP(&oObjPodofo);
    5623             :         }
    5624             : 
    5625             :         /* Find layers */
    5626             :         poDS->FindLayersGeneric(poPageDict);
    5627             : 
    5628             :         /* Read Info object */
    5629             :         const PoDoFo::PdfInfo *poInfo = poDS->m_poDocPodofo->GetInfo();
    5630             :         if (poInfo != nullptr)
    5631             :         {
    5632             :             GDALPDFObjectPodofo oInfoObjPodofo(
    5633             : #if PODOFO_VERSION_MAJOR > 0 ||                                                \
    5634             :     (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
    5635             :                 &(poInfo->GetObject()),
    5636             : #else
    5637             :                 poInfo->GetObject(),
    5638             : #endif
    5639             :                 poDS->m_poDocPodofo->GetObjects());
    5640             :             poDS->ParseInfo(&oInfoObjPodofo);
    5641             :         }
    5642             :     }
    5643             : #endif
    5644             : #ifdef HAVE_PDFIUM
    5645             :     if (bUseLib.test(PDFLIB_PDFIUM))
    5646             :     {
    5647             :         // coverity is confused by WrapRetain(), believing that multiple
    5648             :         // smart pointers manage the same raw pointer. Which is actually
    5649             :         // true, but a RetainPtr holds a reference counted object. It is
    5650             :         // thus safe to have several RetainPtr holding it.
    5651             :         // coverity[multiple_init_smart_ptr]
    5652             :         GDALPDFObjectPdfium *poRoot = GDALPDFObjectPdfium::Build(
    5653             :             pdfium::WrapRetain(poDocPdfium->doc->GetRoot()));
    5654             :         if (poRoot->GetType() == PDFObjectType_Dictionary)
    5655             :         {
    5656             :             GDALPDFDictionary *poDict = poRoot->GetDictionary();
    5657             :             GDALPDFObject *poMetadata(poDict->Get("Metadata"));
    5658             :             if (poMetadata != nullptr)
    5659             :             {
    5660             :                 GDALPDFStream *poStream = poMetadata->GetStream();
    5661             :                 if (poStream != nullptr)
    5662             :                 {
    5663             :                     char *pszContent = poStream->GetBytes();
    5664             :                     const auto nLength = poStream->GetLength();
    5665             :                     if (pszContent != nullptr && nLength > 15 &&
    5666             :                         STARTS_WITH(pszContent, "<?xpacket begin="))
    5667             :                     {
    5668             :                         char *apszMDList[2];
    5669             :                         apszMDList[0] = pszContent;
    5670             :                         apszMDList[1] = nullptr;
    5671             :                         poDS->SetMetadata(apszMDList, "xml:XMP");
    5672             :                     }
    5673             :                     CPLFree(pszContent);
    5674             :                 }
    5675             :             }
    5676             :         }
    5677             :         delete poRoot;
    5678             : 
    5679             :         /* Find layers */
    5680             :         poDS->FindLayersPdfium((bOpenSubdataset || bOpenSubdatasetImage) ? iPage
    5681             :                                                                          : 0);
    5682             : 
    5683             :         /* Turn user specified layers on or off */
    5684             :         poDS->TurnLayersOnOffPdfium();
    5685             : 
    5686             :         GDALPDFObjectPdfium *poInfo =
    5687             :             GDALPDFObjectPdfium::Build(poDocPdfium->doc->GetInfo());
    5688             :         if (poInfo)
    5689             :         {
    5690             :             /* Read Info object */
    5691             :             poDS->ParseInfo(poInfo);
    5692             :             delete poInfo;
    5693             :         }
    5694             :     }
    5695             : #endif  // ~ HAVE_PDFIUM
    5696             : 
    5697             :     // Patch band size with actual dataset size
    5698         883 :     for (int iBand = 1; iBand <= poDS->nBands; iBand++)
    5699             :     {
    5700             :         cpl::down_cast<PDFRasterBand *>(poDS->GetRasterBand(iBand))
    5701         664 :             ->SetSize(poDS->nRasterXSize, poDS->nRasterYSize);
    5702             :     }
    5703             : 
    5704             :     /* Check if this is a raster-only PDF file and that we are */
    5705             :     /* opened in vector-only mode */
    5706         502 :     if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
    5707         232 :         (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
    5708          13 :         !poDS->OpenVectorLayers(poPageDict))
    5709             :     {
    5710           0 :         CPLDebug("PDF", "This is a raster-only PDF dataset, "
    5711             :                         "but it has been opened in vector-only mode");
    5712             :         /* Clear dirty flag */
    5713           0 :         poDS->m_bProjDirty = false;
    5714           0 :         poDS->m_bNeatLineDirty = false;
    5715           0 :         poDS->m_bInfoDirty = false;
    5716           0 :         poDS->m_bXMPDirty = false;
    5717           0 :         delete poDS;
    5718           0 :         return nullptr;
    5719             :     }
    5720             : 
    5721             :     /* -------------------------------------------------------------------- */
    5722             :     /*      Support overviews.                                              */
    5723             :     /* -------------------------------------------------------------------- */
    5724         219 :     if (!CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
    5725             :     {
    5726         217 :         poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);
    5727             :     }
    5728             : 
    5729             :     /* Clear dirty flag */
    5730         219 :     poDS->m_bProjDirty = false;
    5731         219 :     poDS->m_bNeatLineDirty = false;
    5732         219 :     poDS->m_bInfoDirty = false;
    5733         219 :     poDS->m_bXMPDirty = false;
    5734             : 
    5735         219 :     return (poDS);
    5736             : }
    5737             : 
    5738             : /************************************************************************/
    5739             : /*                         ParseLGIDictObject()                         */
    5740             : /************************************************************************/
    5741             : 
    5742           5 : int PDFDataset::ParseLGIDictObject(GDALPDFObject *poLGIDict)
    5743             : {
    5744           5 :     bool bOK = false;
    5745           5 :     if (poLGIDict->GetType() == PDFObjectType_Array)
    5746             :     {
    5747           0 :         GDALPDFArray *poArray = poLGIDict->GetArray();
    5748           0 :         int nArrayLength = poArray->GetLength();
    5749           0 :         int iMax = -1;
    5750           0 :         GDALPDFObject *poArrayElt = nullptr;
    5751           0 :         for (int i = 0; i < nArrayLength; i++)
    5752             :         {
    5753           0 :             if ((poArrayElt = poArray->Get(i)) == nullptr ||
    5754           0 :                 poArrayElt->GetType() != PDFObjectType_Dictionary)
    5755             :             {
    5756           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    5757             :                          "LGIDict[%d] is not a dictionary", i);
    5758           0 :                 return FALSE;
    5759             :             }
    5760             : 
    5761           0 :             int bIsBestCandidate = FALSE;
    5762           0 :             if (ParseLGIDictDictFirstPass(poArrayElt->GetDictionary(),
    5763           0 :                                           &bIsBestCandidate))
    5764             :             {
    5765           0 :                 if (bIsBestCandidate || iMax < 0)
    5766           0 :                     iMax = i;
    5767             :             }
    5768             :         }
    5769             : 
    5770           0 :         if (iMax < 0)
    5771           0 :             return FALSE;
    5772             : 
    5773           0 :         poArrayElt = poArray->Get(iMax);
    5774           0 :         bOK = CPL_TO_BOOL(
    5775           0 :             ParseLGIDictDictSecondPass(poArrayElt->GetDictionary()));
    5776             :     }
    5777           5 :     else if (poLGIDict->GetType() == PDFObjectType_Dictionary)
    5778             :     {
    5779          10 :         bOK = ParseLGIDictDictFirstPass(poLGIDict->GetDictionary()) &&
    5780           5 :               ParseLGIDictDictSecondPass(poLGIDict->GetDictionary());
    5781             :     }
    5782             :     else
    5783             :     {
    5784           0 :         CPLError(CE_Failure, CPLE_AppDefined, "LGIDict is of type %s",
    5785           0 :                  poLGIDict->GetTypeName());
    5786             :     }
    5787             : 
    5788           5 :     return bOK;
    5789             : }
    5790             : 
    5791             : /************************************************************************/
    5792             : /*                                Get()                                 */
    5793             : /************************************************************************/
    5794             : 
    5795       11241 : static double Get(GDALPDFObject *poObj, int nIndice)
    5796             : {
    5797       11241 :     if (poObj->GetType() == PDFObjectType_Array && nIndice >= 0)
    5798             :     {
    5799        5026 :         poObj = poObj->GetArray()->Get(nIndice);
    5800        5026 :         if (poObj == nullptr)
    5801           0 :             return 0;
    5802        5026 :         return Get(poObj);
    5803             :     }
    5804        6215 :     else if (poObj->GetType() == PDFObjectType_Int)
    5805        4997 :         return poObj->GetInt();
    5806        1218 :     else if (poObj->GetType() == PDFObjectType_Real)
    5807        1208 :         return poObj->GetReal();
    5808          10 :     else if (poObj->GetType() == PDFObjectType_String)
    5809             :     {
    5810          10 :         const char *pszStr = poObj->GetString().c_str();
    5811          10 :         size_t nLen = strlen(pszStr);
    5812          10 :         if (nLen == 0)
    5813           0 :             return 0;
    5814             :         /* cf Military_Installations_2008.pdf that has values like "96 0 0.0W"
    5815             :          */
    5816          10 :         char chLast = pszStr[nLen - 1];
    5817          10 :         if (chLast == 'W' || chLast == 'E' || chLast == 'N' || chLast == 'S')
    5818             :         {
    5819           0 :             double dfDeg = CPLAtof(pszStr);
    5820           0 :             double dfMin = 0.0;
    5821           0 :             double dfSec = 0.0;
    5822           0 :             const char *pszNext = strchr(pszStr, ' ');
    5823           0 :             if (pszNext)
    5824           0 :                 pszNext++;
    5825           0 :             if (pszNext)
    5826           0 :                 dfMin = CPLAtof(pszNext);
    5827           0 :             if (pszNext)
    5828           0 :                 pszNext = strchr(pszNext, ' ');
    5829           0 :             if (pszNext)
    5830           0 :                 pszNext++;
    5831           0 :             if (pszNext)
    5832           0 :                 dfSec = CPLAtof(pszNext);
    5833           0 :             double dfVal = dfDeg + dfMin / 60 + dfSec / 3600;
    5834           0 :             if (chLast == 'W' || chLast == 'S')
    5835           0 :                 return -dfVal;
    5836             :             else
    5837           0 :                 return dfVal;
    5838             :         }
    5839          10 :         return CPLAtof(pszStr);
    5840             :     }
    5841             :     else
    5842             :     {
    5843           0 :         CPLError(CE_Warning, CPLE_AppDefined, "Unexpected type : %s",
    5844           0 :                  poObj->GetTypeName());
    5845           0 :         return 0;
    5846             :     }
    5847             : }
    5848             : 
    5849             : /************************************************************************/
    5850             : /*                                Get()                                 */
    5851             : /************************************************************************/
    5852             : 
    5853           0 : static double Get(GDALPDFDictionary *poDict, const char *pszName)
    5854             : {
    5855           0 :     GDALPDFObject *poObj = poDict->Get(pszName);
    5856           0 :     if (poObj != nullptr)
    5857           0 :         return Get(poObj);
    5858           0 :     CPLError(CE_Failure, CPLE_AppDefined, "Cannot find parameter %s", pszName);
    5859           0 :     return 0;
    5860             : }
    5861             : 
    5862             : /************************************************************************/
    5863             : /*                     ParseLGIDictDictFirstPass()                      */
    5864             : /************************************************************************/
    5865             : 
    5866           5 : int PDFDataset::ParseLGIDictDictFirstPass(GDALPDFDictionary *poLGIDict,
    5867             :                                           int *pbIsBestCandidate)
    5868             : {
    5869           5 :     if (pbIsBestCandidate)
    5870           0 :         *pbIsBestCandidate = FALSE;
    5871             : 
    5872           5 :     if (poLGIDict == nullptr)
    5873           0 :         return FALSE;
    5874             : 
    5875             :     /* -------------------------------------------------------------------- */
    5876             :     /*      Extract Type attribute                                          */
    5877             :     /* -------------------------------------------------------------------- */
    5878           5 :     GDALPDFObject *poType = poLGIDict->Get("Type");
    5879           5 :     if (poType == nullptr)
    5880             :     {
    5881           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5882             :                  "Cannot find Type of LGIDict object");
    5883           0 :         return FALSE;
    5884             :     }
    5885             : 
    5886           5 :     if (poType->GetType() != PDFObjectType_Name)
    5887             :     {
    5888           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5889             :                  "Invalid type for Type of LGIDict object");
    5890           0 :         return FALSE;
    5891             :     }
    5892             : 
    5893           5 :     if (strcmp(poType->GetName().c_str(), "LGIDict") != 0)
    5894             :     {
    5895           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5896             :                  "Invalid value for Type of LGIDict object : %s",
    5897           0 :                  poType->GetName().c_str());
    5898           0 :         return FALSE;
    5899             :     }
    5900             : 
    5901             :     /* -------------------------------------------------------------------- */
    5902             :     /*      Extract Version attribute                                       */
    5903             :     /* -------------------------------------------------------------------- */
    5904           5 :     GDALPDFObject *poVersion = poLGIDict->Get("Version");
    5905           5 :     if (poVersion == nullptr)
    5906             :     {
    5907           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5908             :                  "Cannot find Version of LGIDict object");
    5909           0 :         return FALSE;
    5910             :     }
    5911             : 
    5912           5 :     if (poVersion->GetType() == PDFObjectType_String)
    5913             :     {
    5914             :         /* OGC best practice is 2.1 */
    5915           5 :         CPLDebug("PDF", "LGIDict Version : %s", poVersion->GetString().c_str());
    5916             :     }
    5917           0 :     else if (poVersion->GetType() == PDFObjectType_Int)
    5918             :     {
    5919             :         /* Old TerraGo is 2 */
    5920           0 :         CPLDebug("PDF", "LGIDict Version : %d", poVersion->GetInt());
    5921             :     }
    5922             : 
    5923             :     /* USGS PDF maps have several LGIDict. Keep the one whose description */
    5924             :     /* is "Map Layers" by default */
    5925             :     const char *pszNeatlineToSelect =
    5926           5 :         GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
    5927             : 
    5928             :     /* -------------------------------------------------------------------- */
    5929             :     /*      Extract Neatline attribute                                      */
    5930             :     /* -------------------------------------------------------------------- */
    5931           5 :     GDALPDFObject *poNeatline = poLGIDict->Get("Neatline");
    5932           5 :     if (poNeatline != nullptr && poNeatline->GetType() == PDFObjectType_Array)
    5933             :     {
    5934           5 :         int nLength = poNeatline->GetArray()->GetLength();
    5935           5 :         if ((nLength % 2) != 0 || nLength < 4)
    5936             :         {
    5937           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5938             :                      "Invalid length for Neatline");
    5939           0 :             return FALSE;
    5940             :         }
    5941             : 
    5942           5 :         GDALPDFObject *poDescription = poLGIDict->Get("Description");
    5943           5 :         bool bIsAskedNeatline = false;
    5944          10 :         if (poDescription != nullptr &&
    5945           5 :             poDescription->GetType() == PDFObjectType_String)
    5946             :         {
    5947           5 :             CPLDebug("PDF", "Description = %s",
    5948           5 :                      poDescription->GetString().c_str());
    5949             : 
    5950           5 :             if (EQUAL(poDescription->GetString().c_str(), pszNeatlineToSelect))
    5951             :             {
    5952           0 :                 m_dfMaxArea = 1e300;
    5953           0 :                 bIsAskedNeatline = true;
    5954             :             }
    5955             :         }
    5956             : 
    5957           5 :         if (!bIsAskedNeatline)
    5958             :         {
    5959           5 :             double dfMinX = 0.0;
    5960           5 :             double dfMinY = 0.0;
    5961           5 :             double dfMaxX = 0.0;
    5962           5 :             double dfMaxY = 0.0;
    5963          25 :             for (int i = 0; i < nLength; i += 2)
    5964             :             {
    5965          20 :                 double dfX = Get(poNeatline, i);
    5966          20 :                 double dfY = Get(poNeatline, i + 1);
    5967          20 :                 if (i == 0 || dfX < dfMinX)
    5968           5 :                     dfMinX = dfX;
    5969          20 :                 if (i == 0 || dfY < dfMinY)
    5970          10 :                     dfMinY = dfY;
    5971          20 :                 if (i == 0 || dfX > dfMaxX)
    5972          10 :                     dfMaxX = dfX;
    5973          20 :                 if (i == 0 || dfY > dfMaxY)
    5974           5 :                     dfMaxY = dfY;
    5975             :             }
    5976           5 :             double dfArea = (dfMaxX - dfMinX) * (dfMaxY - dfMinY);
    5977           5 :             if (dfArea < m_dfMaxArea)
    5978             :             {
    5979           0 :                 CPLDebug("PDF", "Not the largest neatline. Skipping it");
    5980           0 :                 return TRUE;
    5981             :             }
    5982             : 
    5983           5 :             CPLDebug("PDF", "This is the largest neatline for now");
    5984           5 :             m_dfMaxArea = dfArea;
    5985             :         }
    5986             :         else
    5987           0 :             CPLDebug("PDF", "The \"%s\" registration will be selected",
    5988             :                      pszNeatlineToSelect);
    5989             : 
    5990           5 :         if (pbIsBestCandidate)
    5991           0 :             *pbIsBestCandidate = TRUE;
    5992             : 
    5993           5 :         delete m_poNeatLine;
    5994           5 :         m_poNeatLine = new OGRPolygon();
    5995           5 :         OGRLinearRing *poRing = new OGRLinearRing();
    5996           5 :         if (nLength == 4)
    5997             :         {
    5998             :             /* 2 points only ? They are the bounding box */
    5999           0 :             double dfX1 = Get(poNeatline, 0);
    6000           0 :             double dfY1 = Get(poNeatline, 1);
    6001           0 :             double dfX2 = Get(poNeatline, 2);
    6002           0 :             double dfY2 = Get(poNeatline, 3);
    6003           0 :             poRing->addPoint(dfX1, dfY1);
    6004           0 :             poRing->addPoint(dfX2, dfY1);
    6005           0 :             poRing->addPoint(dfX2, dfY2);
    6006           0 :             poRing->addPoint(dfX1, dfY2);
    6007             :         }
    6008             :         else
    6009             :         {
    6010          25 :             for (int i = 0; i < nLength; i += 2)
    6011             :             {
    6012          20 :                 double dfX = Get(poNeatline, i);
    6013          20 :                 double dfY = Get(poNeatline, i + 1);
    6014          20 :                 poRing->addPoint(dfX, dfY);
    6015             :             }
    6016             :         }
    6017           5 :         poRing->closeRings();
    6018           5 :         m_poNeatLine->addRingDirectly(poRing);
    6019             :     }
    6020             : 
    6021           5 :     return TRUE;
    6022             : }
    6023             : 
    6024             : /************************************************************************/
    6025             : /*                     ParseLGIDictDictSecondPass()                     */
    6026             : /************************************************************************/
    6027             : 
    6028           5 : int PDFDataset::ParseLGIDictDictSecondPass(GDALPDFDictionary *poLGIDict)
    6029             : {
    6030             :     int i;
    6031             : 
    6032             :     /* -------------------------------------------------------------------- */
    6033             :     /*      Extract Description attribute                                   */
    6034             :     /* -------------------------------------------------------------------- */
    6035           5 :     GDALPDFObject *poDescription = poLGIDict->Get("Description");
    6036          10 :     if (poDescription != nullptr &&
    6037           5 :         poDescription->GetType() == PDFObjectType_String)
    6038             :     {
    6039           5 :         CPLDebug("PDF", "Description = %s", poDescription->GetString().c_str());
    6040             :     }
    6041             : 
    6042             :     /* -------------------------------------------------------------------- */
    6043             :     /*      Extract CTM attribute                                           */
    6044             :     /* -------------------------------------------------------------------- */
    6045           5 :     GDALPDFObject *poCTM = poLGIDict->Get("CTM");
    6046           5 :     m_bHasCTM = false;
    6047          10 :     if (poCTM != nullptr && poCTM->GetType() == PDFObjectType_Array &&
    6048           5 :         CPLTestBool(CPLGetConfigOption("PDF_USE_CTM", "YES")))
    6049             :     {
    6050           5 :         int nLength = poCTM->GetArray()->GetLength();
    6051           5 :         if (nLength != 6)
    6052             :         {
    6053           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for CTM");
    6054           0 :             return FALSE;
    6055             :         }
    6056             : 
    6057           5 :         m_bHasCTM = true;
    6058          35 :         for (i = 0; i < nLength; i++)
    6059             :         {
    6060          30 :             m_adfCTM[i] = Get(poCTM, i);
    6061             :             /* Nullify rotation terms that are significantly smaller than */
    6062             :             /* scaling terms. */
    6063          40 :             if ((i == 1 || i == 2) &&
    6064          10 :                 fabs(m_adfCTM[i]) < fabs(m_adfCTM[0]) * 1e-10)
    6065          10 :                 m_adfCTM[i] = 0;
    6066          30 :             CPLDebug("PDF", "CTM[%d] = %.16g", i, m_adfCTM[i]);
    6067             :         }
    6068             :     }
    6069             : 
    6070             :     /* -------------------------------------------------------------------- */
    6071             :     /*      Extract Registration attribute                                  */
    6072             :     /* -------------------------------------------------------------------- */
    6073           5 :     GDALPDFObject *poRegistration = poLGIDict->Get("Registration");
    6074           5 :     if (poRegistration != nullptr &&
    6075           0 :         poRegistration->GetType() == PDFObjectType_Array)
    6076             :     {
    6077           0 :         GDALPDFArray *poRegistrationArray = poRegistration->GetArray();
    6078           0 :         int nLength = poRegistrationArray->GetLength();
    6079           0 :         if (nLength > 4 || (!m_bHasCTM && nLength >= 2) ||
    6080           0 :             CPLTestBool(CPLGetConfigOption("PDF_REPORT_GCPS", "NO")))
    6081             :         {
    6082           0 :             m_nGCPCount = 0;
    6083           0 :             m_pasGCPList =
    6084           0 :                 static_cast<GDAL_GCP *>(CPLCalloc(sizeof(GDAL_GCP), nLength));
    6085             : 
    6086           0 :             for (i = 0; i < nLength; i++)
    6087             :             {
    6088           0 :                 GDALPDFObject *poGCP = poRegistrationArray->Get(i);
    6089           0 :                 if (poGCP != nullptr &&
    6090           0 :                     poGCP->GetType() == PDFObjectType_Array &&
    6091           0 :                     poGCP->GetArray()->GetLength() == 4)
    6092             :                 {
    6093           0 :                     double dfUserX = Get(poGCP, 0);
    6094           0 :                     double dfUserY = Get(poGCP, 1);
    6095           0 :                     double dfX = Get(poGCP, 2);
    6096           0 :                     double dfY = Get(poGCP, 3);
    6097           0 :                     CPLDebug("PDF", "GCP[%d].userX = %.16g", i, dfUserX);
    6098           0 :                     CPLDebug("PDF", "GCP[%d].userY = %.16g", i, dfUserY);
    6099           0 :                     CPLDebug("PDF", "GCP[%d].x = %.16g", i, dfX);
    6100           0 :                     CPLDebug("PDF", "GCP[%d].y = %.16g", i, dfY);
    6101             : 
    6102             :                     char szID[32];
    6103           0 :                     snprintf(szID, sizeof(szID), "%d", m_nGCPCount + 1);
    6104           0 :                     m_pasGCPList[m_nGCPCount].pszId = CPLStrdup(szID);
    6105           0 :                     m_pasGCPList[m_nGCPCount].pszInfo = CPLStrdup("");
    6106           0 :                     m_pasGCPList[m_nGCPCount].dfGCPPixel = dfUserX;
    6107           0 :                     m_pasGCPList[m_nGCPCount].dfGCPLine = dfUserY;
    6108           0 :                     m_pasGCPList[m_nGCPCount].dfGCPX = dfX;
    6109           0 :                     m_pasGCPList[m_nGCPCount].dfGCPY = dfY;
    6110           0 :                     m_nGCPCount++;
    6111             :                 }
    6112             :             }
    6113             : 
    6114           0 :             if (m_nGCPCount == 0)
    6115             :             {
    6116           0 :                 CPLFree(m_pasGCPList);
    6117           0 :                 m_pasGCPList = nullptr;
    6118             :             }
    6119             :         }
    6120             :     }
    6121             : 
    6122           5 :     if (!m_bHasCTM && m_nGCPCount == 0)
    6123             :     {
    6124           0 :         CPLDebug("PDF", "Neither CTM nor Registration found");
    6125           0 :         return FALSE;
    6126             :     }
    6127             : 
    6128             :     /* -------------------------------------------------------------------- */
    6129             :     /*      Extract Projection attribute                                    */
    6130             :     /* -------------------------------------------------------------------- */
    6131           5 :     GDALPDFObject *poProjection = poLGIDict->Get("Projection");
    6132          10 :     if (poProjection == nullptr ||
    6133           5 :         poProjection->GetType() != PDFObjectType_Dictionary)
    6134             :     {
    6135           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Could not find Projection");
    6136           0 :         return FALSE;
    6137             :     }
    6138             : 
    6139           5 :     return ParseProjDict(poProjection->GetDictionary());
    6140             : }
    6141             : 
    6142             : /************************************************************************/
    6143             : /*                           ParseProjDict()                            */
    6144             : /************************************************************************/
    6145             : 
    6146           5 : int PDFDataset::ParseProjDict(GDALPDFDictionary *poProjDict)
    6147             : {
    6148           5 :     if (poProjDict == nullptr)
    6149           0 :         return FALSE;
    6150          10 :     OGRSpatialReference oSRS;
    6151           5 :     oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6152             : 
    6153             :     /* -------------------------------------------------------------------- */
    6154             :     /*      Extract WKT attribute (GDAL extension)                          */
    6155             :     /* -------------------------------------------------------------------- */
    6156           5 :     GDALPDFObject *poWKT = poProjDict->Get("WKT");
    6157           5 :     if (poWKT != nullptr && poWKT->GetType() == PDFObjectType_String &&
    6158           0 :         CPLTestBool(CPLGetConfigOption("GDAL_PDF_OGC_BP_READ_WKT", "TRUE")))
    6159             :     {
    6160           0 :         CPLDebug("PDF", "Found WKT attribute (GDAL extension). Using it");
    6161           0 :         const char *pszWKTRead = poWKT->GetString().c_str();
    6162           0 :         if (pszWKTRead[0] != 0)
    6163           0 :             m_oSRS.importFromWkt(pszWKTRead);
    6164           0 :         return TRUE;
    6165             :     }
    6166             : 
    6167             :     /* -------------------------------------------------------------------- */
    6168             :     /*      Extract Type attribute                                          */
    6169             :     /* -------------------------------------------------------------------- */
    6170           5 :     GDALPDFObject *poType = poProjDict->Get("Type");
    6171           5 :     if (poType == nullptr)
    6172             :     {
    6173           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6174             :                  "Cannot find Type of Projection object");
    6175           0 :         return FALSE;
    6176             :     }
    6177             : 
    6178           5 :     if (poType->GetType() != PDFObjectType_Name)
    6179             :     {
    6180           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6181             :                  "Invalid type for Type of Projection object");
    6182           0 :         return FALSE;
    6183             :     }
    6184             : 
    6185           5 :     if (strcmp(poType->GetName().c_str(), "Projection") != 0)
    6186             :     {
    6187           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6188             :                  "Invalid value for Type of Projection object : %s",
    6189           0 :                  poType->GetName().c_str());
    6190           0 :         return FALSE;
    6191             :     }
    6192             : 
    6193             :     /* -------------------------------------------------------------------- */
    6194             :     /*      Extract Datum attribute                                         */
    6195             :     /* -------------------------------------------------------------------- */
    6196           5 :     int bIsWGS84 = FALSE;
    6197           5 :     int bIsNAD83 = FALSE;
    6198             :     /* int bIsNAD27 = FALSE; */
    6199             : 
    6200           5 :     GDALPDFObject *poDatum = poProjDict->Get("Datum");
    6201           5 :     if (poDatum != nullptr)
    6202             :     {
    6203           5 :         if (poDatum->GetType() == PDFObjectType_String)
    6204             :         {
    6205             :             /* Using Annex A of
    6206             :              * http://portal.opengeospatial.org/files/?artifact_id=40537 */
    6207           5 :             const char *pszDatum = poDatum->GetString().c_str();
    6208           5 :             CPLDebug("PDF", "Datum = %s", pszDatum);
    6209           5 :             if (EQUAL(pszDatum, "WE") || EQUAL(pszDatum, "WGE"))
    6210             :             {
    6211           5 :                 bIsWGS84 = TRUE;
    6212           5 :                 oSRS.SetWellKnownGeogCS("WGS84");
    6213             :             }
    6214           0 :             else if (EQUAL(pszDatum, "NAR") || STARTS_WITH_CI(pszDatum, "NAR-"))
    6215             :             {
    6216           0 :                 bIsNAD83 = TRUE;
    6217           0 :                 oSRS.SetWellKnownGeogCS("NAD83");
    6218             :             }
    6219           0 :             else if (EQUAL(pszDatum, "NAS") || STARTS_WITH_CI(pszDatum, "NAS-"))
    6220             :             {
    6221             :                 /* bIsNAD27 = TRUE; */
    6222           0 :                 oSRS.SetWellKnownGeogCS("NAD27");
    6223             :             }
    6224           0 :             else if (EQUAL(pszDatum, "HEN")) /* HERAT North, Afghanistan */
    6225             :             {
    6226           0 :                 oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
    6227             :                                "unknown" /*const char * pszDatumName */,
    6228             :                                "International 1924", 6378388, 297);
    6229           0 :                 oSRS.SetTOWGS84(-333, -222, 114);
    6230             :             }
    6231           0 :             else if (EQUAL(pszDatum, "ING-A")) /* INDIAN 1960, Vietnam 16N */
    6232             :             {
    6233           0 :                 oSRS.importFromEPSG(4131);
    6234             :             }
    6235           0 :             else if (EQUAL(pszDatum, "GDS")) /* Geocentric Datum of Australia */
    6236             :             {
    6237           0 :                 oSRS.importFromEPSG(4283);
    6238             :             }
    6239           0 :             else if (STARTS_WITH_CI(pszDatum, "OHA-")) /* Old Hawaiian */
    6240             :             {
    6241           0 :                 oSRS.importFromEPSG(4135); /* matches OHA-M (Mean) */
    6242           0 :                 if (!EQUAL(pszDatum, "OHA-M"))
    6243             :                 {
    6244           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    6245             :                              "Using OHA-M (Old Hawaiian Mean) definition for "
    6246             :                              "%s. Potential issue with datum shift parameters",
    6247             :                              pszDatum);
    6248           0 :                     OGR_SRSNode *poNode = oSRS.GetRoot();
    6249           0 :                     int iChild = poNode->FindChild("AUTHORITY");
    6250           0 :                     if (iChild != -1)
    6251           0 :                         poNode->DestroyChild(iChild);
    6252           0 :                     iChild = poNode->FindChild("DATUM");
    6253           0 :                     if (iChild != -1)
    6254             :                     {
    6255           0 :                         poNode = poNode->GetChild(iChild);
    6256           0 :                         iChild = poNode->FindChild("AUTHORITY");
    6257           0 :                         if (iChild != -1)
    6258           0 :                             poNode->DestroyChild(iChild);
    6259             :                     }
    6260             :                 }
    6261             :             }
    6262             :             else
    6263             :             {
    6264           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    6265             :                          "Unhandled (yet) value for Datum : %s. Defaulting to "
    6266             :                          "WGS84...",
    6267             :                          pszDatum);
    6268           0 :                 oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
    6269             :                                "unknown" /*const char * pszDatumName */,
    6270             :                                "unknown", 6378137, 298.257223563);
    6271             :             }
    6272             :         }
    6273           0 :         else if (poDatum->GetType() == PDFObjectType_Dictionary)
    6274             :         {
    6275           0 :             GDALPDFDictionary *poDatumDict = poDatum->GetDictionary();
    6276             : 
    6277           0 :             GDALPDFObject *poDatumDescription = poDatumDict->Get("Description");
    6278           0 :             const char *pszDatumDescription = "unknown";
    6279           0 :             if (poDatumDescription != nullptr &&
    6280           0 :                 poDatumDescription->GetType() == PDFObjectType_String)
    6281           0 :                 pszDatumDescription = poDatumDescription->GetString().c_str();
    6282           0 :             CPLDebug("PDF", "Datum.Description = %s", pszDatumDescription);
    6283             : 
    6284           0 :             GDALPDFObject *poEllipsoid = poDatumDict->Get("Ellipsoid");
    6285           0 :             if (poEllipsoid == nullptr ||
    6286           0 :                 !(poEllipsoid->GetType() == PDFObjectType_String ||
    6287           0 :                   poEllipsoid->GetType() == PDFObjectType_Dictionary))
    6288             :             {
    6289           0 :                 CPLError(
    6290             :                     CE_Warning, CPLE_AppDefined,
    6291             :                     "Cannot find Ellipsoid in Datum. Defaulting to WGS84...");
    6292           0 :                 oSRS.SetGeogCS("unknown", pszDatumDescription, "unknown",
    6293             :                                6378137, 298.257223563);
    6294             :             }
    6295           0 :             else if (poEllipsoid->GetType() == PDFObjectType_String)
    6296             :             {
    6297           0 :                 const char *pszEllipsoid = poEllipsoid->GetString().c_str();
    6298           0 :                 CPLDebug("PDF", "Datum.Ellipsoid = %s", pszEllipsoid);
    6299           0 :                 if (EQUAL(pszEllipsoid, "WE"))
    6300             :                 {
    6301           0 :                     oSRS.SetGeogCS("unknown", pszDatumDescription, "WGS 84",
    6302             :                                    6378137, 298.257223563);
    6303             :                 }
    6304             :                 else
    6305             :                 {
    6306           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    6307             :                              "Unhandled (yet) value for Ellipsoid : %s. "
    6308             :                              "Defaulting to WGS84...",
    6309             :                              pszEllipsoid);
    6310           0 :                     oSRS.SetGeogCS("unknown", pszDatumDescription, pszEllipsoid,
    6311             :                                    6378137, 298.257223563);
    6312             :                 }
    6313             :             }
    6314             :             else  // if (poEllipsoid->GetType() == PDFObjectType_Dictionary)
    6315             :             {
    6316             :                 GDALPDFDictionary *poEllipsoidDict =
    6317           0 :                     poEllipsoid->GetDictionary();
    6318             : 
    6319             :                 GDALPDFObject *poEllipsoidDescription =
    6320           0 :                     poEllipsoidDict->Get("Description");
    6321           0 :                 const char *pszEllipsoidDescription = "unknown";
    6322           0 :                 if (poEllipsoidDescription != nullptr &&
    6323           0 :                     poEllipsoidDescription->GetType() == PDFObjectType_String)
    6324             :                     pszEllipsoidDescription =
    6325           0 :                         poEllipsoidDescription->GetString().c_str();
    6326           0 :                 CPLDebug("PDF", "Datum.Ellipsoid.Description = %s",
    6327             :                          pszEllipsoidDescription);
    6328             : 
    6329           0 :                 double dfSemiMajor = Get(poEllipsoidDict, "SemiMajorAxis");
    6330           0 :                 CPLDebug("PDF", "Datum.Ellipsoid.SemiMajorAxis = %.16g",
    6331             :                          dfSemiMajor);
    6332           0 :                 double dfInvFlattening = -1.0;
    6333             : 
    6334           0 :                 if (poEllipsoidDict->Get("InvFlattening"))
    6335             :                 {
    6336           0 :                     dfInvFlattening = Get(poEllipsoidDict, "InvFlattening");
    6337           0 :                     CPLDebug("PDF", "Datum.Ellipsoid.InvFlattening = %.16g",
    6338             :                              dfInvFlattening);
    6339             :                 }
    6340           0 :                 else if (poEllipsoidDict->Get("SemiMinorAxis"))
    6341             :                 {
    6342           0 :                     double dfSemiMinor = Get(poEllipsoidDict, "SemiMinorAxis");
    6343           0 :                     CPLDebug("PDF", "Datum.Ellipsoid.SemiMinorAxis = %.16g",
    6344             :                              dfSemiMinor);
    6345             :                     dfInvFlattening =
    6346           0 :                         OSRCalcInvFlattening(dfSemiMajor, dfSemiMinor);
    6347             :                 }
    6348             : 
    6349           0 :                 if (dfSemiMajor != 0.0 && dfInvFlattening != -1.0)
    6350             :                 {
    6351           0 :                     oSRS.SetGeogCS("unknown", pszDatumDescription,
    6352             :                                    pszEllipsoidDescription, dfSemiMajor,
    6353             :                                    dfInvFlattening);
    6354             :                 }
    6355             :                 else
    6356             :                 {
    6357           0 :                     CPLError(
    6358             :                         CE_Warning, CPLE_AppDefined,
    6359             :                         "Invalid Ellipsoid object. Defaulting to WGS84...");
    6360           0 :                     oSRS.SetGeogCS("unknown", pszDatumDescription,
    6361             :                                    pszEllipsoidDescription, 6378137,
    6362             :                                    298.257223563);
    6363             :                 }
    6364             :             }
    6365             : 
    6366           0 :             GDALPDFObject *poTOWGS84 = poDatumDict->Get("ToWGS84");
    6367           0 :             if (poTOWGS84 != nullptr &&
    6368           0 :                 poTOWGS84->GetType() == PDFObjectType_Dictionary)
    6369             :             {
    6370           0 :                 GDALPDFDictionary *poTOWGS84Dict = poTOWGS84->GetDictionary();
    6371           0 :                 double dx = Get(poTOWGS84Dict, "dx");
    6372           0 :                 double dy = Get(poTOWGS84Dict, "dy");
    6373           0 :                 double dz = Get(poTOWGS84Dict, "dz");
    6374           0 :                 if (poTOWGS84Dict->Get("rx") && poTOWGS84Dict->Get("ry") &&
    6375           0 :                     poTOWGS84Dict->Get("rz") && poTOWGS84Dict->Get("sf"))
    6376             :                 {
    6377           0 :                     double rx = Get(poTOWGS84Dict, "rx");
    6378           0 :                     double ry = Get(poTOWGS84Dict, "ry");
    6379           0 :                     double rz = Get(poTOWGS84Dict, "rz");
    6380           0 :                     double sf = Get(poTOWGS84Dict, "sf");
    6381           0 :                     oSRS.SetTOWGS84(dx, dy, dz, rx, ry, rz, sf);
    6382             :                 }
    6383             :                 else
    6384             :                 {
    6385           0 :                     oSRS.SetTOWGS84(dx, dy, dz);
    6386             :                 }
    6387             :             }
    6388             :         }
    6389             :     }
    6390             : 
    6391             :     /* -------------------------------------------------------------------- */
    6392             :     /*      Extract Hemisphere attribute                                    */
    6393             :     /* -------------------------------------------------------------------- */
    6394          10 :     CPLString osHemisphere;
    6395           5 :     GDALPDFObject *poHemisphere = poProjDict->Get("Hemisphere");
    6396           5 :     if (poHemisphere != nullptr &&
    6397           0 :         poHemisphere->GetType() == PDFObjectType_String)
    6398             :     {
    6399           0 :         osHemisphere = poHemisphere->GetString();
    6400             :     }
    6401             : 
    6402             :     /* -------------------------------------------------------------------- */
    6403             :     /*      Extract ProjectionType attribute                                */
    6404             :     /* -------------------------------------------------------------------- */
    6405           5 :     GDALPDFObject *poProjectionType = poProjDict->Get("ProjectionType");
    6406          10 :     if (poProjectionType == nullptr ||
    6407           5 :         poProjectionType->GetType() != PDFObjectType_String)
    6408             :     {
    6409           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6410             :                  "Cannot find ProjectionType of Projection object");
    6411           0 :         return FALSE;
    6412             :     }
    6413          10 :     CPLString osProjectionType(poProjectionType->GetString());
    6414           5 :     CPLDebug("PDF", "Projection.ProjectionType = %s", osProjectionType.c_str());
    6415             : 
    6416             :     /* Unhandled: NONE, GEODETIC */
    6417             : 
    6418           5 :     if (EQUAL(osProjectionType, "GEOGRAPHIC"))
    6419             :     {
    6420             :         /* Nothing to do */
    6421             :     }
    6422             : 
    6423             :     /* Unhandled: LOCAL CARTESIAN, MG (MGRS) */
    6424             : 
    6425           0 :     else if (EQUAL(osProjectionType, "UT")) /* UTM */
    6426             :     {
    6427           0 :         const double dfZone = Get(poProjDict, "Zone");
    6428           0 :         if (dfZone >= 1 && dfZone <= 60)
    6429             :         {
    6430           0 :             int nZone = static_cast<int>(dfZone);
    6431           0 :             int bNorth = EQUAL(osHemisphere, "N");
    6432           0 :             if (bIsWGS84)
    6433           0 :                 oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
    6434             :             else
    6435           0 :                 oSRS.SetUTM(nZone, bNorth);
    6436             :         }
    6437             :     }
    6438             : 
    6439           0 :     else if (EQUAL(osProjectionType,
    6440             :                    "UP")) /* Universal Polar Stereographic (UPS) */
    6441             :     {
    6442           0 :         int bNorth = EQUAL(osHemisphere, "N");
    6443           0 :         if (bIsWGS84)
    6444           0 :             oSRS.importFromEPSG((bNorth) ? 32661 : 32761);
    6445             :         else
    6446           0 :             oSRS.SetPS((bNorth) ? 90 : -90, 0, 0.994, 200000, 200000);
    6447             :     }
    6448             : 
    6449           0 :     else if (EQUAL(osProjectionType, "SPCS")) /* State Plane */
    6450             :     {
    6451           0 :         const double dfZone = Get(poProjDict, "Zone");
    6452           0 :         if (dfZone >= 0 && dfZone <= INT_MAX)
    6453             :         {
    6454           0 :             int nZone = static_cast<int>(dfZone);
    6455           0 :             oSRS.SetStatePlane(nZone, bIsNAD83);
    6456             :         }
    6457             :     }
    6458             : 
    6459           0 :     else if (EQUAL(osProjectionType, "AC")) /* Albers Equal Area Conic */
    6460             :     {
    6461           0 :         double dfStdP1 = Get(poProjDict, "StandardParallelOne");
    6462           0 :         double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
    6463           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6464           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6465           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6466           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6467           0 :         oSRS.SetACEA(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
    6468             :                      dfFalseEasting, dfFalseNorthing);
    6469             :     }
    6470             : 
    6471           0 :     else if (EQUAL(osProjectionType, "AL")) /* Azimuthal Equidistant */
    6472             :     {
    6473           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6474           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6475           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6476           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6477           0 :         oSRS.SetAE(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
    6478             :     }
    6479             : 
    6480           0 :     else if (EQUAL(osProjectionType, "BF")) /* Bonne */
    6481             :     {
    6482           0 :         double dfStdP1 = Get(poProjDict, "OriginLatitude");
    6483           0 :         double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
    6484           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6485           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6486           0 :         oSRS.SetBonne(dfStdP1, dfCentralMeridian, dfFalseEasting,
    6487             :                       dfFalseNorthing);
    6488             :     }
    6489             : 
    6490           0 :     else if (EQUAL(osProjectionType, "CS")) /* Cassini */
    6491             :     {
    6492           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6493           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6494           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6495           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6496           0 :         oSRS.SetCS(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
    6497             :     }
    6498             : 
    6499           0 :     else if (EQUAL(osProjectionType, "LI")) /* Cylindrical Equal Area */
    6500             :     {
    6501           0 :         double dfStdP1 = Get(poProjDict, "OriginLatitude");
    6502           0 :         double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
    6503           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6504           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6505           0 :         oSRS.SetCEA(dfStdP1, dfCentralMeridian, dfFalseEasting,
    6506             :                     dfFalseNorthing);
    6507             :     }
    6508             : 
    6509           0 :     else if (EQUAL(osProjectionType, "EF")) /* Eckert IV */
    6510             :     {
    6511           0 :         double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
    6512           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6513           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6514           0 :         oSRS.SetEckertIV(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
    6515             :     }
    6516             : 
    6517           0 :     else if (EQUAL(osProjectionType, "ED")) /* Eckert VI */
    6518             :     {
    6519           0 :         double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
    6520           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6521           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6522           0 :         oSRS.SetEckertVI(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
    6523             :     }
    6524             : 
    6525           0 :     else if (EQUAL(osProjectionType, "CP")) /* Equidistant Cylindrical */
    6526             :     {
    6527           0 :         double dfCenterLat = Get(poProjDict, "StandardParallel");
    6528           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6529           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6530           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6531           0 :         oSRS.SetEquirectangular(dfCenterLat, dfCenterLong, dfFalseEasting,
    6532             :                                 dfFalseNorthing);
    6533             :     }
    6534             : 
    6535           0 :     else if (EQUAL(osProjectionType, "GN")) /* Gnomonic */
    6536             :     {
    6537           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6538           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6539           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6540           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6541           0 :         oSRS.SetGnomonic(dfCenterLat, dfCenterLong, dfFalseEasting,
    6542             :                          dfFalseNorthing);
    6543             :     }
    6544             : 
    6545           0 :     else if (EQUAL(osProjectionType, "LE")) /* Lambert Conformal Conic */
    6546             :     {
    6547           0 :         double dfStdP1 = Get(poProjDict, "StandardParallelOne");
    6548           0 :         double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
    6549           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6550           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6551           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6552           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6553           0 :         oSRS.SetLCC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong, dfFalseEasting,
    6554             :                     dfFalseNorthing);
    6555             :     }
    6556             : 
    6557           0 :     else if (EQUAL(osProjectionType, "MC")) /* Mercator */
    6558             :     {
    6559             : #ifdef not_supported
    6560             :         if (poProjDict->Get("StandardParallelOne") == nullptr)
    6561             : #endif
    6562             :         {
    6563           0 :             double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6564           0 :             double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6565           0 :             double dfScale = Get(poProjDict, "ScaleFactor");
    6566           0 :             double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6567           0 :             double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6568           0 :             oSRS.SetMercator(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
    6569             :                              dfFalseNorthing);
    6570             :         }
    6571             : #ifdef not_supported
    6572             :         else
    6573             :         {
    6574             :             double dfStdP1 = Get(poProjDict, "StandardParallelOne");
    6575             :             double dfCenterLat = poProjDict->Get("OriginLatitude")
    6576             :                                      ? Get(poProjDict, "OriginLatitude")
    6577             :                                      : 0;
    6578             :             double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6579             :             double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6580             :             double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6581             :             oSRS.SetMercator2SP(dfStdP1, dfCenterLat, dfCenterLong,
    6582             :                                 dfFalseEasting, dfFalseNorthing);
    6583             :         }
    6584             : #endif
    6585             :     }
    6586             : 
    6587           0 :     else if (EQUAL(osProjectionType, "MH")) /* Miller Cylindrical */
    6588             :     {
    6589           0 :         double dfCenterLat = 0 /* ? */;
    6590           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6591           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6592           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6593           0 :         oSRS.SetMC(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
    6594             :     }
    6595             : 
    6596           0 :     else if (EQUAL(osProjectionType, "MP")) /* Mollweide */
    6597             :     {
    6598           0 :         double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
    6599           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6600           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6601           0 :         oSRS.SetMollweide(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
    6602             :     }
    6603             : 
    6604             :     /* Unhandled:  "NY" : Ney's (Modified Lambert Conformal Conic) */
    6605             : 
    6606           0 :     else if (EQUAL(osProjectionType, "NT")) /* New Zealand Map Grid */
    6607             :     {
    6608             :         /* No parameter specified in the PDF, so let's take the ones of
    6609             :          * EPSG:27200 */
    6610           0 :         double dfCenterLat = -41;
    6611           0 :         double dfCenterLong = 173;
    6612           0 :         double dfFalseEasting = 2510000;
    6613           0 :         double dfFalseNorthing = 6023150;
    6614           0 :         oSRS.SetNZMG(dfCenterLat, dfCenterLong, dfFalseEasting,
    6615             :                      dfFalseNorthing);
    6616             :     }
    6617             : 
    6618           0 :     else if (EQUAL(osProjectionType, "OC")) /* Oblique Mercator */
    6619             :     {
    6620           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6621           0 :         double dfLat1 = Get(poProjDict, "LatitudeOne");
    6622           0 :         double dfLong1 = Get(poProjDict, "LongitudeOne");
    6623           0 :         double dfLat2 = Get(poProjDict, "LatitudeTwo");
    6624           0 :         double dfLong2 = Get(poProjDict, "LongitudeTwo");
    6625           0 :         double dfScale = Get(poProjDict, "ScaleFactor");
    6626           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6627           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6628           0 :         oSRS.SetHOM2PNO(dfCenterLat, dfLat1, dfLong1, dfLat2, dfLong2, dfScale,
    6629             :                         dfFalseEasting, dfFalseNorthing);
    6630             :     }
    6631             : 
    6632           0 :     else if (EQUAL(osProjectionType, "OD")) /* Orthographic */
    6633             :     {
    6634           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6635           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6636           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6637           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6638           0 :         oSRS.SetOrthographic(dfCenterLat, dfCenterLong, dfFalseEasting,
    6639             :                              dfFalseNorthing);
    6640             :     }
    6641             : 
    6642           0 :     else if (EQUAL(osProjectionType, "PG")) /* Polar Stereographic */
    6643             :     {
    6644           0 :         double dfCenterLat = Get(poProjDict, "LatitudeTrueScale");
    6645           0 :         double dfCenterLong = Get(poProjDict, "LongitudeDownFromPole");
    6646           0 :         double dfScale = 1.0;
    6647           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6648           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6649           0 :         oSRS.SetPS(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
    6650             :                    dfFalseNorthing);
    6651             :     }
    6652             : 
    6653           0 :     else if (EQUAL(osProjectionType, "PH")) /* Polyconic */
    6654             :     {
    6655           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6656           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6657           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6658           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6659           0 :         oSRS.SetPolyconic(dfCenterLat, dfCenterLong, dfFalseEasting,
    6660             :                           dfFalseNorthing);
    6661             :     }
    6662             : 
    6663           0 :     else if (EQUAL(osProjectionType, "SA")) /* Sinusoidal */
    6664             :     {
    6665           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6666           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6667           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6668           0 :         oSRS.SetSinusoidal(dfCenterLong, dfFalseEasting, dfFalseNorthing);
    6669             :     }
    6670             : 
    6671           0 :     else if (EQUAL(osProjectionType, "SD")) /* Stereographic */
    6672             :     {
    6673           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6674           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6675           0 :         double dfScale = 1.0;
    6676           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6677           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6678           0 :         oSRS.SetStereographic(dfCenterLat, dfCenterLong, dfScale,
    6679             :                               dfFalseEasting, dfFalseNorthing);
    6680             :     }
    6681             : 
    6682           0 :     else if (EQUAL(osProjectionType, "TC")) /* Transverse Mercator */
    6683             :     {
    6684           0 :         double dfCenterLat = Get(poProjDict, "OriginLatitude");
    6685           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6686           0 :         double dfScale = Get(poProjDict, "ScaleFactor");
    6687           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6688           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6689           0 :         if (dfCenterLat == 0.0 && dfScale == 0.9996 && dfCenterLong >= -180 &&
    6690           0 :             dfCenterLong <= 180 && dfFalseEasting == 500000 &&
    6691           0 :             (dfFalseNorthing == 0.0 || dfFalseNorthing == 10000000.0))
    6692             :         {
    6693           0 :             const int nZone =
    6694           0 :                 static_cast<int>(floor((dfCenterLong + 180.0) / 6.0) + 1);
    6695           0 :             int bNorth = dfFalseNorthing == 0;
    6696           0 :             if (bIsWGS84)
    6697           0 :                 oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
    6698           0 :             else if (bIsNAD83 && bNorth)
    6699           0 :                 oSRS.importFromEPSG(26900 + nZone);
    6700             :             else
    6701           0 :                 oSRS.SetUTM(nZone, bNorth);
    6702             :         }
    6703             :         else
    6704             :         {
    6705           0 :             oSRS.SetTM(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
    6706             :                        dfFalseNorthing);
    6707             :         }
    6708             :     }
    6709             : 
    6710             :     /* Unhandled TX : Transverse Cylindrical Equal Area */
    6711             : 
    6712           0 :     else if (EQUAL(osProjectionType, "VA")) /* Van der Grinten */
    6713             :     {
    6714           0 :         double dfCenterLong = Get(poProjDict, "CentralMeridian");
    6715           0 :         double dfFalseEasting = Get(poProjDict, "FalseEasting");
    6716           0 :         double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
    6717           0 :         oSRS.SetVDG(dfCenterLong, dfFalseEasting, dfFalseNorthing);
    6718             :     }
    6719             : 
    6720             :     else
    6721             :     {
    6722           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6723             :                  "Unhandled (yet) value for ProjectionType : %s",
    6724             :                  osProjectionType.c_str());
    6725           0 :         return FALSE;
    6726             :     }
    6727             : 
    6728             :     /* -------------------------------------------------------------------- */
    6729             :     /*      Extract Units attribute                                         */
    6730             :     /* -------------------------------------------------------------------- */
    6731           5 :     CPLString osUnits;
    6732           5 :     GDALPDFObject *poUnits = poProjDict->Get("Units");
    6733           5 :     if (poUnits != nullptr && poUnits->GetType() == PDFObjectType_String &&
    6734           0 :         !EQUAL(osProjectionType, "GEOGRAPHIC"))
    6735             :     {
    6736           0 :         osUnits = poUnits->GetString();
    6737           0 :         CPLDebug("PDF", "Projection.Units = %s", osUnits.c_str());
    6738             : 
    6739             :         // This is super weird. The false easting/northing of the SRS
    6740             :         // are expressed in the unit, but the geotransform is expressed in
    6741             :         // meters. Hence this hack to have an equivalent SRS definition, but
    6742             :         // with linear units converted in meters.
    6743           0 :         if (EQUAL(osUnits, "M"))
    6744           0 :             oSRS.SetLinearUnits("Meter", 1.0);
    6745           0 :         else if (EQUAL(osUnits, "FT"))
    6746             :         {
    6747           0 :             oSRS.SetLinearUnits("foot", 0.3048);
    6748           0 :             oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
    6749             :         }
    6750           0 :         else if (EQUAL(osUnits, "USSF"))
    6751             :         {
    6752           0 :             oSRS.SetLinearUnits(SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV));
    6753           0 :             oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
    6754             :         }
    6755             :         else
    6756           0 :             CPLError(CE_Warning, CPLE_AppDefined, "Unhandled unit: %s",
    6757             :                      osUnits.c_str());
    6758             :     }
    6759             : 
    6760             :     /* -------------------------------------------------------------------- */
    6761             :     /*      Export SpatialRef                                               */
    6762             :     /* -------------------------------------------------------------------- */
    6763           5 :     m_oSRS = std::move(oSRS);
    6764             : 
    6765           5 :     return TRUE;
    6766             : }
    6767             : 
    6768             : /************************************************************************/
    6769             : /*                              ParseVP()                               */
    6770             : /************************************************************************/
    6771             : 
    6772         155 : int PDFDataset::ParseVP(GDALPDFObject *poVP, double dfMediaBoxWidth,
    6773             :                         double dfMediaBoxHeight)
    6774             : {
    6775             :     int i;
    6776             : 
    6777         155 :     if (poVP->GetType() != PDFObjectType_Array)
    6778           0 :         return FALSE;
    6779             : 
    6780         155 :     GDALPDFArray *poVPArray = poVP->GetArray();
    6781             : 
    6782         155 :     int nLength = poVPArray->GetLength();
    6783         155 :     CPLDebug("PDF", "VP length = %d", nLength);
    6784         155 :     if (nLength < 1)
    6785           0 :         return FALSE;
    6786             : 
    6787             :     /* -------------------------------------------------------------------- */
    6788             :     /*      Find the largest BBox                                           */
    6789             :     /* -------------------------------------------------------------------- */
    6790             :     const char *pszNeatlineToSelect =
    6791         155 :         GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
    6792             : 
    6793         155 :     int iLargest = 0;
    6794         155 :     int iRequestedVP = -1;
    6795         155 :     double dfLargestArea = 0;
    6796             : 
    6797         321 :     for (i = 0; i < nLength; i++)
    6798             :     {
    6799         166 :         GDALPDFObject *poVPElt = poVPArray->Get(i);
    6800         332 :         if (poVPElt == nullptr ||
    6801         166 :             poVPElt->GetType() != PDFObjectType_Dictionary)
    6802             :         {
    6803           0 :             return FALSE;
    6804             :         }
    6805             : 
    6806         166 :         GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
    6807             : 
    6808         166 :         GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
    6809         332 :         if (poMeasure == nullptr ||
    6810         166 :             poMeasure->GetType() != PDFObjectType_Dictionary)
    6811             :         {
    6812           0 :             continue;
    6813             :         }
    6814             :         /* --------------------------------------------------------------------
    6815             :          */
    6816             :         /*      Extract Subtype attribute */
    6817             :         /* --------------------------------------------------------------------
    6818             :          */
    6819         166 :         GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
    6820         166 :         GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
    6821         166 :         if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
    6822             :         {
    6823           0 :             continue;
    6824             :         }
    6825             : 
    6826         166 :         CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
    6827         166 :         if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
    6828             :         {
    6829           0 :             continue;
    6830             :         }
    6831             : 
    6832         166 :         GDALPDFObject *poName = poVPEltDict->Get("Name");
    6833         166 :         if (poName != nullptr && poName->GetType() == PDFObjectType_String)
    6834             :         {
    6835         164 :             CPLDebug("PDF", "Name = %s", poName->GetString().c_str());
    6836         164 :             if (EQUAL(poName->GetString().c_str(), pszNeatlineToSelect))
    6837             :             {
    6838           0 :                 iRequestedVP = i;
    6839             :             }
    6840             :         }
    6841             : 
    6842         166 :         GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
    6843         166 :         if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
    6844             :         {
    6845           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
    6846           0 :             return FALSE;
    6847             :         }
    6848             : 
    6849         166 :         int nBboxLength = poBBox->GetArray()->GetLength();
    6850         166 :         if (nBboxLength != 4)
    6851             :         {
    6852           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6853             :                      "Invalid length for Bbox object");
    6854           0 :             return FALSE;
    6855             :         }
    6856             : 
    6857             :         double adfBBox[4];
    6858         166 :         adfBBox[0] = Get(poBBox, 0);
    6859         166 :         adfBBox[1] = Get(poBBox, 1);
    6860         166 :         adfBBox[2] = Get(poBBox, 2);
    6861         166 :         adfBBox[3] = Get(poBBox, 3);
    6862         166 :         double dfArea =
    6863         166 :             fabs(adfBBox[2] - adfBBox[0]) * fabs(adfBBox[3] - adfBBox[1]);
    6864         166 :         if (dfArea > dfLargestArea)
    6865             :         {
    6866         155 :             iLargest = i;
    6867         155 :             dfLargestArea = dfArea;
    6868             :         }
    6869             :     }
    6870             : 
    6871         155 :     if (nLength > 1)
    6872             :     {
    6873          11 :         CPLDebug("PDF", "Largest BBox in VP array is element %d", iLargest);
    6874             :     }
    6875             : 
    6876         155 :     GDALPDFObject *poVPElt = nullptr;
    6877             : 
    6878         155 :     if (iRequestedVP > -1)
    6879             :     {
    6880           0 :         CPLDebug("PDF", "Requested NEATLINE BBox in VP array is element %d",
    6881             :                  iRequestedVP);
    6882           0 :         poVPElt = poVPArray->Get(iRequestedVP);
    6883             :     }
    6884             :     else
    6885             :     {
    6886         155 :         poVPElt = poVPArray->Get(iLargest);
    6887             :     }
    6888             : 
    6889         155 :     if (poVPElt == nullptr || poVPElt->GetType() != PDFObjectType_Dictionary)
    6890             :     {
    6891           0 :         return FALSE;
    6892             :     }
    6893             : 
    6894         155 :     GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
    6895             : 
    6896         155 :     GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
    6897         155 :     if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
    6898             :     {
    6899           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
    6900           0 :         return FALSE;
    6901             :     }
    6902             : 
    6903         155 :     int nBboxLength = poBBox->GetArray()->GetLength();
    6904         155 :     if (nBboxLength != 4)
    6905             :     {
    6906           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for Bbox object");
    6907           0 :         return FALSE;
    6908             :     }
    6909             : 
    6910         155 :     double dfULX = Get(poBBox, 0);
    6911         155 :     double dfULY = dfMediaBoxHeight - Get(poBBox, 1);
    6912         155 :     double dfLRX = Get(poBBox, 2);
    6913         155 :     double dfLRY = dfMediaBoxHeight - Get(poBBox, 3);
    6914             : 
    6915             :     /* -------------------------------------------------------------------- */
    6916             :     /*      Extract Measure attribute                                       */
    6917             :     /* -------------------------------------------------------------------- */
    6918         155 :     GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
    6919         310 :     if (poMeasure == nullptr ||
    6920         155 :         poMeasure->GetType() != PDFObjectType_Dictionary)
    6921             :     {
    6922           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Measure object");
    6923           0 :         return FALSE;
    6924             :     }
    6925             : 
    6926         155 :     int bRet = ParseMeasure(poMeasure, dfMediaBoxWidth, dfMediaBoxHeight, dfULX,
    6927             :                             dfULY, dfLRX, dfLRY);
    6928             : 
    6929             :     /* -------------------------------------------------------------------- */
    6930             :     /*      Extract PointData attribute                                     */
    6931             :     /* -------------------------------------------------------------------- */
    6932         155 :     GDALPDFObject *poPointData = poVPEltDict->Get("PtData");
    6933         155 :     if (poPointData != nullptr &&
    6934           0 :         poPointData->GetType() == PDFObjectType_Dictionary)
    6935             :     {
    6936           0 :         CPLDebug("PDF", "Found PointData");
    6937             :     }
    6938             : 
    6939         155 :     return bRet;
    6940             : }
    6941             : 
    6942             : /************************************************************************/
    6943             : /*                            ParseMeasure()                            */
    6944             : /************************************************************************/
    6945             : 
    6946         155 : int PDFDataset::ParseMeasure(GDALPDFObject *poMeasure, double dfMediaBoxWidth,
    6947             :                              double dfMediaBoxHeight, double dfULX,
    6948             :                              double dfULY, double dfLRX, double dfLRY)
    6949             : {
    6950         155 :     GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
    6951             : 
    6952             :     /* -------------------------------------------------------------------- */
    6953             :     /*      Extract Subtype attribute                                       */
    6954             :     /* -------------------------------------------------------------------- */
    6955         155 :     GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
    6956         155 :     if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
    6957             :     {
    6958           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Subtype object");
    6959           0 :         return FALSE;
    6960             :     }
    6961             : 
    6962         155 :     CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
    6963         155 :     if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
    6964           0 :         return FALSE;
    6965             : 
    6966             :     /* -------------------------------------------------------------------- */
    6967             :     /*      Extract Bounds attribute (optional)                             */
    6968             :     /* -------------------------------------------------------------------- */
    6969             : 
    6970             :     /* http://acrobatusers.com/sites/default/files/gallery_pictures/SEVERODVINSK.pdf
    6971             :      */
    6972             :     /* has lgit:LPTS, lgit:GPTS and lgit:Bounds that have more precision than */
    6973             :     /* LPTS, GPTS and Bounds. Use those ones */
    6974             : 
    6975         155 :     GDALPDFObject *poBounds = poMeasureDict->Get("lgit:Bounds");
    6976         155 :     if (poBounds != nullptr && poBounds->GetType() == PDFObjectType_Array)
    6977             :     {
    6978           0 :         CPLDebug("PDF", "Using lgit:Bounds");
    6979             :     }
    6980         308 :     else if ((poBounds = poMeasureDict->Get("Bounds")) == nullptr ||
    6981         153 :              poBounds->GetType() != PDFObjectType_Array)
    6982             :     {
    6983           2 :         poBounds = nullptr;
    6984             :     }
    6985             : 
    6986         155 :     if (poBounds != nullptr)
    6987             :     {
    6988         153 :         int nBoundsLength = poBounds->GetArray()->GetLength();
    6989         153 :         if (nBoundsLength == 8)
    6990             :         {
    6991             :             double adfBounds[8];
    6992        1296 :             for (int i = 0; i < 8; i++)
    6993             :             {
    6994        1152 :                 adfBounds[i] = Get(poBounds, i);
    6995        1152 :                 CPLDebug("PDF", "Bounds[%d] = %f", i, adfBounds[i]);
    6996             :             }
    6997             : 
    6998             :             // TODO we should use it to restrict the neatline but
    6999             :             // I have yet to set a sample where bounds are not the four
    7000             :             // corners of the unit square.
    7001             :         }
    7002             :     }
    7003             : 
    7004             :     /* -------------------------------------------------------------------- */
    7005             :     /*      Extract GPTS attribute                                          */
    7006             :     /* -------------------------------------------------------------------- */
    7007         155 :     GDALPDFObject *poGPTS = poMeasureDict->Get("lgit:GPTS");
    7008         155 :     if (poGPTS != nullptr && poGPTS->GetType() == PDFObjectType_Array)
    7009             :     {
    7010           0 :         CPLDebug("PDF", "Using lgit:GPTS");
    7011             :     }
    7012         310 :     else if ((poGPTS = poMeasureDict->Get("GPTS")) == nullptr ||
    7013         155 :              poGPTS->GetType() != PDFObjectType_Array)
    7014             :     {
    7015           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GPTS object");
    7016           0 :         return FALSE;
    7017             :     }
    7018             : 
    7019         155 :     int nGPTSLength = poGPTS->GetArray()->GetLength();
    7020         155 :     if ((nGPTSLength % 2) != 0 || nGPTSLength < 6)
    7021             :     {
    7022           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for GPTS object");
    7023           0 :         return FALSE;
    7024             :     }
    7025             : 
    7026         310 :     std::vector<double> adfGPTS(nGPTSLength);
    7027        1395 :     for (int i = 0; i < nGPTSLength; i++)
    7028             :     {
    7029        1240 :         adfGPTS[i] = Get(poGPTS, i);
    7030        1240 :         CPLDebug("PDF", "GPTS[%d] = %.18f", i, adfGPTS[i]);
    7031             :     }
    7032             : 
    7033             :     /* -------------------------------------------------------------------- */
    7034             :     /*      Extract LPTS attribute                                          */
    7035             :     /* -------------------------------------------------------------------- */
    7036         155 :     GDALPDFObject *poLPTS = poMeasureDict->Get("lgit:LPTS");
    7037         155 :     if (poLPTS != nullptr && poLPTS->GetType() == PDFObjectType_Array)
    7038             :     {
    7039           0 :         CPLDebug("PDF", "Using lgit:LPTS");
    7040             :     }
    7041         310 :     else if ((poLPTS = poMeasureDict->Get("LPTS")) == nullptr ||
    7042         155 :              poLPTS->GetType() != PDFObjectType_Array)
    7043             :     {
    7044           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find LPTS object");
    7045           0 :         return FALSE;
    7046             :     }
    7047             : 
    7048         155 :     int nLPTSLength = poLPTS->GetArray()->GetLength();
    7049         155 :     if (nLPTSLength != nGPTSLength)
    7050             :     {
    7051           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for LPTS object");
    7052           0 :         return FALSE;
    7053             :     }
    7054             : 
    7055         310 :     std::vector<double> adfLPTS(nLPTSLength);
    7056        1395 :     for (int i = 0; i < nLPTSLength; i++)
    7057             :     {
    7058        1240 :         adfLPTS[i] = Get(poLPTS, i);
    7059        1240 :         CPLDebug("PDF", "LPTS[%d] = %f", i, adfLPTS[i]);
    7060             :     }
    7061             : 
    7062             :     /* -------------------------------------------------------------------- */
    7063             :     /*      Extract GCS attribute                                           */
    7064             :     /* -------------------------------------------------------------------- */
    7065         155 :     GDALPDFObject *poGCS = poMeasureDict->Get("GCS");
    7066         155 :     if (poGCS == nullptr || poGCS->GetType() != PDFObjectType_Dictionary)
    7067             :     {
    7068           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS object");
    7069           0 :         return FALSE;
    7070             :     }
    7071             : 
    7072         155 :     GDALPDFDictionary *poGCSDict = poGCS->GetDictionary();
    7073             : 
    7074             :     /* -------------------------------------------------------------------- */
    7075             :     /*      Extract GCS.Type attribute                                      */
    7076             :     /* -------------------------------------------------------------------- */
    7077         155 :     GDALPDFObject *poGCSType = poGCSDict->Get("Type");
    7078         155 :     if (poGCSType == nullptr || poGCSType->GetType() != PDFObjectType_Name)
    7079             :     {
    7080           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS.Type object");
    7081           0 :         return FALSE;
    7082             :     }
    7083             : 
    7084         155 :     CPLDebug("PDF", "GCS.Type = %s", poGCSType->GetName().c_str());
    7085             : 
    7086             :     /* -------------------------------------------------------------------- */
    7087             :     /*      Extract EPSG attribute                                          */
    7088             :     /* -------------------------------------------------------------------- */
    7089         155 :     GDALPDFObject *poEPSG = poGCSDict->Get("EPSG");
    7090         155 :     int nEPSGCode = 0;
    7091         155 :     if (poEPSG != nullptr && poEPSG->GetType() == PDFObjectType_Int)
    7092             :     {
    7093         129 :         nEPSGCode = poEPSG->GetInt();
    7094         129 :         CPLDebug("PDF", "GCS.EPSG = %d", nEPSGCode);
    7095             :     }
    7096             : 
    7097             :     /* -------------------------------------------------------------------- */
    7098             :     /*      Extract GCS.WKT attribute                                       */
    7099             :     /* -------------------------------------------------------------------- */
    7100         155 :     GDALPDFObject *poGCSWKT = poGCSDict->Get("WKT");
    7101         155 :     if (poGCSWKT != nullptr && poGCSWKT->GetType() != PDFObjectType_String)
    7102             :     {
    7103           0 :         poGCSWKT = nullptr;
    7104             :     }
    7105             : 
    7106         155 :     if (poGCSWKT != nullptr)
    7107         153 :         CPLDebug("PDF", "GCS.WKT = %s", poGCSWKT->GetString().c_str());
    7108             : 
    7109         155 :     if (nEPSGCode <= 0 && poGCSWKT == nullptr)
    7110             :     {
    7111           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    7112             :                  "Cannot find GCS.WKT or GCS.EPSG objects");
    7113           0 :         return FALSE;
    7114             :     }
    7115             : 
    7116         155 :     if (poGCSWKT != nullptr)
    7117             :     {
    7118         153 :         m_oSRS.importFromWkt(poGCSWKT->GetString().c_str());
    7119             :     }
    7120             : 
    7121         155 :     bool bSRSOK = false;
    7122         155 :     if (nEPSGCode != 0)
    7123             :     {
    7124             :         // At time of writing EPSG CRS codes are <= 32767.
    7125             :         // The usual practice is that codes >= 100000 are in the ESRI namespace
    7126             :         // instead
    7127         129 :         if (nEPSGCode >= 100000)
    7128             :         {
    7129           4 :             CPLErrorHandlerPusher oHandler(CPLQuietErrorHandler);
    7130           4 :             OGRSpatialReference oSRS_ESRI;
    7131           2 :             oSRS_ESRI.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    7132           2 :             if (oSRS_ESRI.SetFromUserInput(CPLSPrintf("ESRI:%d", nEPSGCode)) ==
    7133             :                 OGRERR_NONE)
    7134             :             {
    7135           2 :                 bSRSOK = true;
    7136             : 
    7137             :                 // Check consistency of ESRI:xxxx and WKT definitions
    7138           2 :                 if (poGCSWKT != nullptr)
    7139             :                 {
    7140           3 :                     if (!m_oSRS.GetName() ||
    7141           1 :                         (!EQUAL(oSRS_ESRI.GetName(), m_oSRS.GetName()) &&
    7142           0 :                          !oSRS_ESRI.IsSame(&m_oSRS)))
    7143             :                     {
    7144           1 :                         CPLDebug("PDF",
    7145             :                                  "Definition from ESRI:%d and WKT=%s do not "
    7146             :                                  "match. Using WKT string",
    7147           1 :                                  nEPSGCode, poGCSWKT->GetString().c_str());
    7148           1 :                         bSRSOK = false;
    7149             :                     }
    7150             :                 }
    7151           2 :                 if (bSRSOK)
    7152             :                 {
    7153           1 :                     m_oSRS = std::move(oSRS_ESRI);
    7154             :                 }
    7155             :             }
    7156             :         }
    7157         127 :         else if (m_oSRS.importFromEPSG(nEPSGCode) == OGRERR_NONE)
    7158             :         {
    7159         127 :             bSRSOK = true;
    7160             :         }
    7161             :     }
    7162             : 
    7163         155 :     if (!bSRSOK)
    7164             :     {
    7165          27 :         if (poGCSWKT == nullptr)
    7166             :         {
    7167           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    7168             :                      "Cannot resolve EPSG object, and GCS.WKT not found");
    7169           0 :             return FALSE;
    7170             :         }
    7171             : 
    7172          27 :         if (m_oSRS.importFromWkt(poGCSWKT->GetString().c_str()) != OGRERR_NONE)
    7173             :         {
    7174           1 :             m_oSRS.Clear();
    7175           1 :             return FALSE;
    7176             :         }
    7177             :     }
    7178             : 
    7179             :     /* -------------------------------------------------------------------- */
    7180             :     /*      Compute geotransform                                            */
    7181             :     /* -------------------------------------------------------------------- */
    7182         154 :     OGRSpatialReference *poSRSGeog = m_oSRS.CloneGeogCS();
    7183             : 
    7184             :     /* Files found at
    7185             :      * http://carto.iict.ch/blog/publications-cartographiques-au-format-geospatial-pdf/
    7186             :      */
    7187             :     /* are in a PROJCS. However the coordinates in GPTS array are not in (lat,
    7188             :      * long) as required by the */
    7189             :     /* ISO 32000 supplement spec, but in (northing, easting). Adobe reader is
    7190             :      * able to understand that, */
    7191             :     /* so let's also try to do it with a heuristics. */
    7192             : 
    7193         154 :     bool bReproject = true;
    7194         154 :     if (m_oSRS.IsProjected())
    7195             :     {
    7196         560 :         for (int i = 0; i < nGPTSLength / 2; i++)
    7197             :         {
    7198         448 :             if (fabs(adfGPTS[2 * i]) > 91 || fabs(adfGPTS[2 * i + 1]) > 361)
    7199             :             {
    7200           0 :                 CPLDebug("PDF", "GPTS coordinates seems to be in (northing, "
    7201             :                                 "easting), which is non-standard");
    7202           0 :                 bReproject = false;
    7203           0 :                 break;
    7204             :             }
    7205             :         }
    7206             :     }
    7207             : 
    7208         154 :     OGRCoordinateTransformation *poCT = nullptr;
    7209         154 :     if (bReproject)
    7210             :     {
    7211         154 :         poCT = OGRCreateCoordinateTransformation(poSRSGeog, &m_oSRS);
    7212         154 :         if (poCT == nullptr)
    7213             :         {
    7214           0 :             delete poSRSGeog;
    7215           0 :             m_oSRS.Clear();
    7216           0 :             return FALSE;
    7217             :         }
    7218             :     }
    7219             : 
    7220         308 :     std::vector<GDAL_GCP> asGCPS(nGPTSLength / 2);
    7221             : 
    7222             :     /* Create NEATLINE */
    7223         154 :     OGRLinearRing *poRing = nullptr;
    7224         154 :     if (nGPTSLength == 8)
    7225             :     {
    7226         154 :         m_poNeatLine = new OGRPolygon();
    7227         154 :         poRing = new OGRLinearRing();
    7228         154 :         m_poNeatLine->addRingDirectly(poRing);
    7229             :     }
    7230             : 
    7231         770 :     for (int i = 0; i < nGPTSLength / 2; i++)
    7232             :     {
    7233             :         /* We probably assume LPTS is 0 or 1 */
    7234        1232 :         asGCPS[i].dfGCPPixel =
    7235         616 :             (dfULX * (1 - adfLPTS[2 * i + 0]) + dfLRX * adfLPTS[2 * i + 0]) /
    7236         616 :             dfMediaBoxWidth * nRasterXSize;
    7237        1232 :         asGCPS[i].dfGCPLine =
    7238         616 :             (dfULY * (1 - adfLPTS[2 * i + 1]) + dfLRY * adfLPTS[2 * i + 1]) /
    7239         616 :             dfMediaBoxHeight * nRasterYSize;
    7240             : 
    7241         616 :         double lat = adfGPTS[2 * i];
    7242         616 :         double lon = adfGPTS[2 * i + 1];
    7243         616 :         double x = lon;
    7244         616 :         double y = lat;
    7245         616 :         if (bReproject)
    7246             :         {
    7247         616 :             if (!poCT->Transform(1, &x, &y, nullptr))
    7248             :             {
    7249           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    7250             :                          "Cannot reproject (%f, %f)", lon, lat);
    7251           0 :                 delete poSRSGeog;
    7252           0 :                 delete poCT;
    7253           0 :                 m_oSRS.Clear();
    7254           0 :                 return FALSE;
    7255             :             }
    7256             :         }
    7257             : 
    7258         616 :         x = ROUND_IF_CLOSE(x);
    7259         616 :         y = ROUND_IF_CLOSE(y);
    7260             : 
    7261         616 :         asGCPS[i].dfGCPX = x;
    7262         616 :         asGCPS[i].dfGCPY = y;
    7263             : 
    7264         616 :         if (poRing)
    7265         616 :             poRing->addPoint(x, y);
    7266             :     }
    7267             : 
    7268         154 :     delete poSRSGeog;
    7269         154 :     delete poCT;
    7270             : 
    7271         154 :     if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
    7272             :                                 FALSE))
    7273             :     {
    7274           0 :         CPLDebug("PDF",
    7275             :                  "Could not compute GT with exact match. Try with approximate");
    7276           0 :         if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
    7277             :                                     TRUE))
    7278             :         {
    7279           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    7280             :                      "Could not compute GT with approximate match.");
    7281           0 :             return FALSE;
    7282             :         }
    7283             :     }
    7284         154 :     m_bGeoTransformValid = true;
    7285             : 
    7286             :     // If the non scaling terms of the geotransform are significantly smaller
    7287             :     // than the pixel size, then nullify them as being just artifacts of
    7288             :     //  reprojection and GDALGCPsToGeoTransform() numerical imprecisions.
    7289         154 :     const double dfPixelSize = std::min(fabs(m_gt.xscale), fabs(m_gt.yscale));
    7290             :     const double dfRotationShearTerm =
    7291         154 :         std::max(fabs(m_gt.xrot), fabs(m_gt.yrot));
    7292         161 :     if (dfRotationShearTerm < 1e-5 * dfPixelSize ||
    7293           7 :         (m_bUseLib.test(PDFLIB_PDFIUM) &&
    7294         154 :          std::min(fabs(m_gt.xrot), fabs(m_gt.yrot)) < 1e-5 * dfPixelSize))
    7295             :     {
    7296         147 :         dfLRX =
    7297         147 :             m_gt.xorig + nRasterXSize * m_gt.xscale + nRasterYSize * m_gt.xrot;
    7298         147 :         dfLRY =
    7299         147 :             m_gt.yorig + nRasterXSize * m_gt.yrot + nRasterYSize * m_gt.yscale;
    7300         147 :         m_gt.xscale = (dfLRX - m_gt.xorig) / nRasterXSize;
    7301         147 :         m_gt.yscale = (dfLRY - m_gt.yorig) / nRasterYSize;
    7302         147 :         m_gt.xrot = m_gt.yrot = 0;
    7303             :     }
    7304             : 
    7305         154 :     return TRUE;
    7306             : }
    7307             : 
    7308             : /************************************************************************/
    7309             : /*                           GetSpatialRef()                            */
    7310             : /************************************************************************/
    7311             : 
    7312         225 : const OGRSpatialReference *PDFDataset::GetSpatialRef() const
    7313             : {
    7314         225 :     const auto poSRS = GDALPamDataset::GetSpatialRef();
    7315         225 :     if (poSRS)
    7316         200 :         return poSRS;
    7317             : 
    7318          25 :     if (!m_oSRS.IsEmpty() && m_bGeoTransformValid)
    7319          24 :         return &m_oSRS;
    7320           1 :     return nullptr;
    7321             : }
    7322             : 
    7323             : /************************************************************************/
    7324             : /*                          GetGeoTransform()                           */
    7325             : /************************************************************************/
    7326             : 
    7327          23 : CPLErr PDFDataset::GetGeoTransform(GDALGeoTransform &gt) const
    7328             : 
    7329             : {
    7330          23 :     if (GDALPamDataset::GetGeoTransform(gt) == CE_None)
    7331             :     {
    7332           3 :         return CE_None;
    7333             :     }
    7334             : 
    7335          20 :     gt = m_gt;
    7336          20 :     return ((m_bGeoTransformValid) ? CE_None : CE_Failure);
    7337             : }
    7338             : 
    7339             : /************************************************************************/
    7340             : /*                           SetSpatialRef()                            */
    7341             : /************************************************************************/
    7342             : 
    7343           6 : CPLErr PDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    7344             : {
    7345           6 :     if (eAccess == GA_ReadOnly)
    7346           2 :         GDALPamDataset::SetSpatialRef(poSRS);
    7347             : 
    7348           6 :     m_oSRS.Clear();
    7349           6 :     if (poSRS)
    7350           5 :         m_oSRS = *poSRS;
    7351           6 :     m_bProjDirty = true;
    7352           6 :     return CE_None;
    7353             : }
    7354             : 
    7355             : /************************************************************************/
    7356             : /*                          SetGeoTransform()                           */
    7357             : /************************************************************************/
    7358             : 
    7359           5 : CPLErr PDFDataset::SetGeoTransform(const GDALGeoTransform &gt)
    7360             : {
    7361           5 :     if (eAccess == GA_ReadOnly)
    7362           2 :         GDALPamDataset::SetGeoTransform(gt);
    7363             : 
    7364           5 :     m_gt = gt;
    7365           5 :     m_bGeoTransformValid = true;
    7366           5 :     m_bProjDirty = true;
    7367             : 
    7368             :     /* Reset NEATLINE if not explicitly set by the user */
    7369           5 :     if (!m_bNeatLineDirty)
    7370           5 :         SetMetadataItem("NEATLINE", nullptr);
    7371           5 :     return CE_None;
    7372             : }
    7373             : 
    7374             : /************************************************************************/
    7375             : /*                       GetMetadataDomainList()                        */
    7376             : /************************************************************************/
    7377             : 
    7378           1 : char **PDFDataset::GetMetadataDomainList()
    7379             : {
    7380           1 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    7381             :                                    TRUE, "xml:XMP", "LAYERS",
    7382           1 :                                    "EMBEDDED_METADATA", nullptr);
    7383             : }
    7384             : 
    7385             : /************************************************************************/
    7386             : /*                            GetMetadata()                             */
    7387             : /************************************************************************/
    7388             : 
    7389        1903 : CSLConstList PDFDataset::GetMetadata(const char *pszDomain)
    7390             : {
    7391        1903 :     if (pszDomain != nullptr && EQUAL(pszDomain, "EMBEDDED_METADATA"))
    7392             :     {
    7393           1 :         char **papszRet = m_oMDMD_PDF.GetMetadata(pszDomain);
    7394           1 :         if (papszRet)
    7395           0 :             return papszRet;
    7396             : 
    7397           1 :         GDALPDFObject *poCatalog = GetCatalog();
    7398           1 :         if (poCatalog == nullptr)
    7399           0 :             return nullptr;
    7400             :         GDALPDFObject *poFirstElt =
    7401           1 :             poCatalog->LookupObject("Names.EmbeddedFiles.Names[0]");
    7402             :         GDALPDFObject *poF =
    7403           1 :             poCatalog->LookupObject("Names.EmbeddedFiles.Names[1].EF.F");
    7404             : 
    7405           1 :         if (poFirstElt == nullptr ||
    7406           1 :             poFirstElt->GetType() != PDFObjectType_String ||
    7407           0 :             poFirstElt->GetString() != "Metadata")
    7408           1 :             return nullptr;
    7409           0 :         if (poF == nullptr || poF->GetType() != PDFObjectType_Dictionary)
    7410           0 :             return nullptr;
    7411           0 :         GDALPDFStream *poStream = poF->GetStream();
    7412           0 :         if (poStream == nullptr)
    7413           0 :             return nullptr;
    7414             : 
    7415           0 :         char *apszMetadata[2] = {nullptr, nullptr};
    7416           0 :         apszMetadata[0] = poStream->GetBytes();
    7417           0 :         m_oMDMD_PDF.SetMetadata(apszMetadata, pszDomain);
    7418           0 :         VSIFree(apszMetadata[0]);
    7419           0 :         return m_oMDMD_PDF.GetMetadata(pszDomain);
    7420             :     }
    7421        1902 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    7422             :     {
    7423         120 :         CSLConstList papszPAMMD = GDALPamDataset::GetMetadata(pszDomain);
    7424         126 :         for (CSLConstList papszIter = papszPAMMD; papszIter && *papszIter;
    7425             :              ++papszIter)
    7426             :         {
    7427           6 :             char *pszKey = nullptr;
    7428           6 :             const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
    7429           6 :             if (pszKey && pszValue)
    7430             :             {
    7431           6 :                 if (m_oMDMD_PDF.GetMetadataItem(pszKey, pszDomain) == nullptr)
    7432           2 :                     m_oMDMD_PDF.SetMetadataItem(pszKey, pszValue, pszDomain);
    7433             :             }
    7434           6 :             CPLFree(pszKey);
    7435             :         }
    7436         120 :         return m_oMDMD_PDF.GetMetadata(pszDomain);
    7437             :     }
    7438        1782 :     if (EQUAL(pszDomain, "LAYERS") || EQUAL(pszDomain, "xml:XMP") ||
    7439        1754 :         EQUAL(pszDomain, "SUBDATASETS"))
    7440             :     {
    7441          29 :         return m_oMDMD_PDF.GetMetadata(pszDomain);
    7442             :     }
    7443        1753 :     return GDALPamDataset::GetMetadata(pszDomain);
    7444             : }
    7445             : 
    7446             : /************************************************************************/
    7447             : /*                            SetMetadata()                             */
    7448             : /************************************************************************/
    7449             : 
    7450          70 : CPLErr PDFDataset::SetMetadata(CSLConstList papszMetadata,
    7451             :                                const char *pszDomain)
    7452             : {
    7453          70 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    7454             :     {
    7455          46 :         char **papszMetadataDup = CSLDuplicate(papszMetadata);
    7456          46 :         m_oMDMD_PDF.SetMetadata(nullptr, pszDomain);
    7457             : 
    7458         145 :         for (char **papszIter = papszMetadataDup; papszIter && *papszIter;
    7459             :              ++papszIter)
    7460             :         {
    7461          99 :             char *pszKey = nullptr;
    7462          99 :             const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
    7463          99 :             if (pszKey && pszValue)
    7464             :             {
    7465          96 :                 SetMetadataItem(pszKey, pszValue, pszDomain);
    7466             :             }
    7467          99 :             CPLFree(pszKey);
    7468             :         }
    7469          46 :         CSLDestroy(papszMetadataDup);
    7470          46 :         return CE_None;
    7471             :     }
    7472          24 :     else if (EQUAL(pszDomain, "xml:XMP"))
    7473             :     {
    7474          22 :         m_bXMPDirty = true;
    7475          22 :         return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
    7476             :     }
    7477           2 :     else if (EQUAL(pszDomain, "SUBDATASETS"))
    7478             :     {
    7479           2 :         return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
    7480             :     }
    7481             :     else
    7482             :     {
    7483           0 :         return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    7484             :     }
    7485             : }
    7486             : 
    7487             : /************************************************************************/
    7488             : /*                          GetMetadataItem()                           */
    7489             : /************************************************************************/
    7490             : 
    7491        1810 : const char *PDFDataset::GetMetadataItem(const char *pszName,
    7492             :                                         const char *pszDomain)
    7493             : {
    7494        1810 :     if (pszDomain != nullptr && EQUAL(pszDomain, "_INTERNAL_") &&
    7495           0 :         pszName != nullptr && EQUAL(pszName, "PDF_LIB"))
    7496             :     {
    7497           0 :         if (m_bUseLib.test(PDFLIB_POPPLER))
    7498           0 :             return "POPPLER";
    7499           0 :         if (m_bUseLib.test(PDFLIB_PODOFO))
    7500           0 :             return "PODOFO";
    7501           0 :         if (m_bUseLib.test(PDFLIB_PDFIUM))
    7502           0 :             return "PDFIUM";
    7503             :     }
    7504        1810 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    7505             : }
    7506             : 
    7507             : /************************************************************************/
    7508             : /*                          SetMetadataItem()                           */
    7509             : /************************************************************************/
    7510             : 
    7511         780 : CPLErr PDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    7512             :                                    const char *pszDomain)
    7513             : {
    7514         780 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    7515             :     {
    7516         732 :         if (EQUAL(pszName, "NEATLINE"))
    7517             :         {
    7518             :             const char *pszOldValue =
    7519         199 :                 m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
    7520         199 :             if ((pszValue == nullptr && pszOldValue != nullptr) ||
    7521         197 :                 (pszValue != nullptr && pszOldValue == nullptr) ||
    7522           1 :                 (pszValue != nullptr && pszOldValue != nullptr &&
    7523           1 :                  strcmp(pszValue, pszOldValue) != 0))
    7524             :             {
    7525         195 :                 m_bProjDirty = true;
    7526         195 :                 m_bNeatLineDirty = true;
    7527             :             }
    7528         199 :             return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
    7529             :         }
    7530             :         else
    7531             :         {
    7532         533 :             if (EQUAL(pszName, "AUTHOR") || EQUAL(pszName, "PRODUCER") ||
    7533         510 :                 EQUAL(pszName, "CREATOR") || EQUAL(pszName, "CREATION_DATE") ||
    7534         456 :                 EQUAL(pszName, "SUBJECT") || EQUAL(pszName, "TITLE") ||
    7535         437 :                 EQUAL(pszName, "KEYWORDS"))
    7536             :             {
    7537         102 :                 if (pszValue == nullptr)
    7538           1 :                     pszValue = "";
    7539             :                 const char *pszOldValue =
    7540         102 :                     m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
    7541         102 :                 if (pszOldValue == nullptr ||
    7542           2 :                     strcmp(pszValue, pszOldValue) != 0)
    7543             :                 {
    7544         102 :                     m_bInfoDirty = true;
    7545             :                 }
    7546         102 :                 return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
    7547         102 :                                                    pszDomain);
    7548             :             }
    7549         431 :             else if (EQUAL(pszName, "DPI"))
    7550             :             {
    7551         429 :                 return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
    7552         429 :                                                    pszDomain);
    7553             :             }
    7554             :             else
    7555             :             {
    7556           2 :                 m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
    7557           2 :                 return GDALPamDataset::SetMetadataItem(pszName, pszValue,
    7558           2 :                                                        pszDomain);
    7559             :             }
    7560             :         }
    7561             :     }
    7562          48 :     else if (EQUAL(pszDomain, "xml:XMP"))
    7563             :     {
    7564           0 :         m_bXMPDirty = true;
    7565           0 :         return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
    7566             :     }
    7567          48 :     else if (EQUAL(pszDomain, "SUBDATASETS"))
    7568             :     {
    7569           0 :         return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
    7570             :     }
    7571             :     else
    7572             :     {
    7573          48 :         return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    7574             :     }
    7575             : }
    7576             : 
    7577             : /************************************************************************/
    7578             : /*                            GetGCPCount()                             */
    7579             : /************************************************************************/
    7580             : 
    7581          11 : int PDFDataset::GetGCPCount()
    7582             : {
    7583          11 :     return m_nGCPCount;
    7584             : }
    7585             : 
    7586             : /************************************************************************/
    7587             : /*                          GetGCPSpatialRef()                          */
    7588             : /************************************************************************/
    7589             : 
    7590           2 : const OGRSpatialReference *PDFDataset::GetGCPSpatialRef() const
    7591             : {
    7592           2 :     if (!m_oSRS.IsEmpty() && m_nGCPCount != 0)
    7593           1 :         return &m_oSRS;
    7594           1 :     return nullptr;
    7595             : }
    7596             : 
    7597             : /************************************************************************/
    7598             : /*                              GetGCPs()                               */
    7599             : /************************************************************************/
    7600             : 
    7601           2 : const GDAL_GCP *PDFDataset::GetGCPs()
    7602             : {
    7603           2 :     return m_pasGCPList;
    7604             : }
    7605             : 
    7606             : /************************************************************************/
    7607             : /*                              SetGCPs()                               */
    7608             : /************************************************************************/
    7609             : 
    7610           1 : CPLErr PDFDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
    7611             :                            const OGRSpatialReference *poSRS)
    7612             : {
    7613             :     const char *pszGEO_ENCODING =
    7614           1 :         CPLGetConfigOption("GDAL_PDF_GEO_ENCODING", "ISO32000");
    7615           1 :     if (nGCPCountIn != 4 && EQUAL(pszGEO_ENCODING, "ISO32000"))
    7616             :     {
    7617           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    7618             :                  "PDF driver only supports writing 4 GCPs when "
    7619             :                  "GDAL_PDF_GEO_ENCODING=ISO32000.");
    7620           0 :         return CE_Failure;
    7621             :     }
    7622             : 
    7623             :     /* Free previous GCPs */
    7624           1 :     GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
    7625           1 :     CPLFree(m_pasGCPList);
    7626             : 
    7627             :     /* Duplicate in GCPs */
    7628           1 :     m_nGCPCount = nGCPCountIn;
    7629           1 :     m_pasGCPList = GDALDuplicateGCPs(m_nGCPCount, pasGCPListIn);
    7630             : 
    7631           1 :     m_oSRS.Clear();
    7632           1 :     if (poSRS)
    7633           1 :         m_oSRS = *poSRS;
    7634             : 
    7635           1 :     m_bProjDirty = true;
    7636             : 
    7637             :     /* Reset NEATLINE if not explicitly set by the user */
    7638           1 :     if (!m_bNeatLineDirty)
    7639           1 :         SetMetadataItem("NEATLINE", nullptr);
    7640             : 
    7641           1 :     return CE_None;
    7642             : }
    7643             : 
    7644             : #endif  // #ifdef HAVE_PDF_READ_SUPPORT
    7645             : 
    7646             : /************************************************************************/
    7647             : /*                            GDALPDFOpen()                             */
    7648             : /************************************************************************/
    7649             : 
    7650          53 : GDALDataset *GDALPDFOpen(
    7651             : #ifdef HAVE_PDF_READ_SUPPORT
    7652             :     const char *pszFilename, GDALAccess eAccess
    7653             : #else
    7654             :     CPL_UNUSED const char *pszFilename, CPL_UNUSED GDALAccess eAccess
    7655             : #endif
    7656             : )
    7657             : {
    7658             : #ifdef HAVE_PDF_READ_SUPPORT
    7659         106 :     GDALOpenInfo oOpenInfo(pszFilename, eAccess);
    7660         106 :     return PDFDataset::Open(&oOpenInfo);
    7661             : #else
    7662             :     return nullptr;
    7663             : #endif
    7664             : }
    7665             : 
    7666             : /************************************************************************/
    7667             : /*                        GDALPDFUnloadDriver()                         */
    7668             : /************************************************************************/
    7669             : 
    7670           8 : static void GDALPDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
    7671             : {
    7672             : #ifdef HAVE_POPPLER
    7673           8 :     if (hGlobalParamsMutex != nullptr)
    7674           3 :         CPLDestroyMutex(hGlobalParamsMutex);
    7675             : #endif
    7676             : #ifdef HAVE_PDFIUM
    7677             :     if (PDFDataset::g_bPdfiumInit)
    7678             :     {
    7679             :         CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
    7680             :         // Destroy every loaded document or page
    7681             :         TMapPdfiumDatasets::iterator itDoc;
    7682             :         TMapPdfiumPages::iterator itPage;
    7683             :         for (itDoc = g_mPdfiumDatasets.begin();
    7684             :              itDoc != g_mPdfiumDatasets.end(); ++itDoc)
    7685             :         {
    7686             :             TPdfiumDocumentStruct *pDoc = itDoc->second;
    7687             :             for (itPage = pDoc->pages.begin(); itPage != pDoc->pages.end();
    7688             :                  ++itPage)
    7689             :             {
    7690             :                 TPdfiumPageStruct *pPage = itPage->second;
    7691             : 
    7692             :                 CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex,
    7693             :                                         PDFIUM_MUTEX_TIMEOUT);
    7694             :                 CPLCreateOrAcquireMutex(&(pPage->readMutex),
    7695             :                                         PDFIUM_MUTEX_TIMEOUT);
    7696             :                 CPLReleaseMutex(pPage->readMutex);
    7697             :                 CPLDestroyMutex(pPage->readMutex);
    7698             :                 FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
    7699             :                 delete pPage;
    7700             :                 CPLReleaseMutex(g_oPdfiumReadMutex);
    7701             :             }  // ~ foreach page
    7702             : 
    7703             :             FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
    7704             :             CPLFree(pDoc->filename);
    7705             :             VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
    7706             :             delete pDoc->psFileAccess;
    7707             :             pDoc->pages.clear();
    7708             : 
    7709             :             delete pDoc;
    7710             :         }  // ~ foreach document
    7711             :         g_mPdfiumDatasets.clear();
    7712             :         FPDF_DestroyLibrary();
    7713             :         PDFDataset::g_bPdfiumInit = FALSE;
    7714             : 
    7715             :         CPLReleaseMutex(g_oPdfiumLoadDocMutex);
    7716             : 
    7717             :         if (g_oPdfiumReadMutex)
    7718             :             CPLDestroyMutex(g_oPdfiumReadMutex);
    7719             :         CPLDestroyMutex(g_oPdfiumLoadDocMutex);
    7720             :     }
    7721             : #endif
    7722           8 : }
    7723             : 
    7724             : /************************************************************************/
    7725             : /*                        PDFSanitizeLayerName()                        */
    7726             : /************************************************************************/
    7727             : 
    7728         660 : CPLString PDFSanitizeLayerName(const char *pszName)
    7729             : {
    7730         660 :     if (!CPLTestBool(CPLGetConfigOption("GDAL_PDF_LAUNDER_LAYER_NAMES", "YES")))
    7731           0 :         return pszName;
    7732             : 
    7733        1320 :     CPLString osName;
    7734       17194 :     for (int i = 0; pszName[i] != '\0'; i++)
    7735             :     {
    7736       16534 :         if (pszName[i] == ' ' || pszName[i] == '.' || pszName[i] == ',')
    7737         976 :             osName += "_";
    7738       15558 :         else if (pszName[i] != '"')
    7739       15558 :             osName += pszName[i];
    7740             :     }
    7741         660 :     if (osName.empty())
    7742           2 :         osName = "unnamed";
    7743         660 :     return osName;
    7744             : }
    7745             : 
    7746             : /************************************************************************/
    7747             : /*                      GDALPDFListLayersAlgorithm                      */
    7748             : /************************************************************************/
    7749             : 
    7750             : #ifdef HAVE_PDF_READ_SUPPORT
    7751             : 
    7752             : class GDALPDFListLayersAlgorithm final : public GDALAlgorithm
    7753             : {
    7754             :   public:
    7755          31 :     GDALPDFListLayersAlgorithm()
    7756          31 :         : GDALAlgorithm("list-layers",
    7757          62 :                         std::string("List layers of a PDF dataset"),
    7758          93 :                         "/drivers/raster/pdf.html")
    7759             :     {
    7760          31 :         AddInputDatasetArg(&m_dataset, GDAL_OF_RASTER | GDAL_OF_VECTOR);
    7761          31 :         AddOutputFormatArg(&m_format).SetDefault(m_format).SetChoices("json",
    7762          31 :                                                                       "text");
    7763          31 :         AddOutputStringArg(&m_output);
    7764          31 :     }
    7765             : 
    7766             :   protected:
    7767             :     bool RunImpl(GDALProgressFunc, void *) override;
    7768             : 
    7769             :   private:
    7770             :     GDALArgDatasetValue m_dataset{};
    7771             :     std::string m_format = "json";
    7772             :     std::string m_output{};
    7773             : };
    7774             : 
    7775           3 : bool GDALPDFListLayersAlgorithm::RunImpl(GDALProgressFunc, void *)
    7776             : {
    7777           3 :     auto poDS = dynamic_cast<PDFDataset *>(m_dataset.GetDatasetRef());
    7778           3 :     if (!poDS)
    7779             :     {
    7780           1 :         ReportError(CE_Failure, CPLE_AppDefined, "%s is not a PDF",
    7781           1 :                     m_dataset.GetName().c_str());
    7782           1 :         return false;
    7783             :     }
    7784           2 :     if (m_format == "json")
    7785             :     {
    7786           2 :         CPLJSonStreamingWriter oWriter(nullptr, nullptr);
    7787           1 :         oWriter.StartArray();
    7788          10 :         for (const auto &[key, value] : cpl::IterateNameValue(
    7789          11 :                  const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
    7790             :         {
    7791           5 :             CPL_IGNORE_RET_VAL(key);
    7792           5 :             oWriter.Add(value);
    7793             :         }
    7794           1 :         oWriter.EndArray();
    7795           1 :         m_output = oWriter.GetString();
    7796           1 :         m_output += '\n';
    7797             :     }
    7798             :     else
    7799             :     {
    7800          10 :         for (const auto &[key, value] : cpl::IterateNameValue(
    7801          11 :                  const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
    7802             :         {
    7803           5 :             CPL_IGNORE_RET_VAL(key);
    7804           5 :             m_output += value;
    7805           5 :             m_output += '\n';
    7806             :         }
    7807             :     }
    7808           2 :     return true;
    7809             : }
    7810             : 
    7811             : /************************************************************************/
    7812             : /*                    GDALPDFInstantiateAlgorithm()                     */
    7813             : /************************************************************************/
    7814             : 
    7815             : static GDALAlgorithm *
    7816          31 : GDALPDFInstantiateAlgorithm(const std::vector<std::string> &aosPath)
    7817             : {
    7818          31 :     if (aosPath.size() == 1 && aosPath[0] == "list-layers")
    7819             :     {
    7820          31 :         return std::make_unique<GDALPDFListLayersAlgorithm>().release();
    7821             :     }
    7822             :     else
    7823             :     {
    7824           0 :         return nullptr;
    7825             :     }
    7826             : }
    7827             : 
    7828             : #endif  // HAVE_PDF_READ_SUPPORT
    7829             : 
    7830             : /************************************************************************/
    7831             : /*                          GDALRegister_PDF()                          */
    7832             : /************************************************************************/
    7833             : 
    7834          17 : void GDALRegister_PDF()
    7835             : 
    7836             : {
    7837          17 :     if (!GDAL_CHECK_VERSION("PDF driver"))
    7838           0 :         return;
    7839             : 
    7840          17 :     if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
    7841           0 :         return;
    7842             : 
    7843          17 :     GDALDriver *poDriver = new GDALDriver();
    7844          17 :     PDFDriverSetCommonMetadata(poDriver);
    7845             : 
    7846             : #ifdef HAVE_PDF_READ_SUPPORT
    7847          17 :     poDriver->pfnOpen = PDFDataset::OpenWrapper;
    7848          17 :     poDriver->pfnInstantiateAlgorithm = GDALPDFInstantiateAlgorithm;
    7849             : #endif  // HAVE_PDF_READ_SUPPORT
    7850             : 
    7851          17 :     poDriver->pfnCreateCopy = GDALPDFCreateCopy;
    7852          17 :     poDriver->pfnCreate = PDFWritableVectorDataset::Create;
    7853          17 :     poDriver->pfnUnloadDriver = GDALPDFUnloadDriver;
    7854             : 
    7855          17 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    7856             : }

Generated by: LCOV version 1.14