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

Generated by: LCOV version 1.14