LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 683 732 93.3 %
Date: 2024-11-21 22:18:42 Functions: 24 25 96.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoTIFF Driver
       4             :  * Purpose:  GDAL GeoTIFF support.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1998, 2002, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys dot com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "gtiffdataset.h"
      15             : #include "gtiffrasterband.h"
      16             : #include "gtiffjpegoverviewds.h"
      17             : 
      18             : #include <cassert>
      19             : 
      20             : #include <algorithm>
      21             : #include <limits>
      22             : #include <memory>
      23             : #include <set>
      24             : #include <string>
      25             : #include <tuple>
      26             : #include <utility>
      27             : 
      28             : #include "cpl_error.h"
      29             : #include "cpl_vsi.h"
      30             : #include "cpl_vsi_virtual.h"
      31             : #include "cpl_worker_thread_pool.h"
      32             : #include "ogr_proj_p.h"  // OSRGetProjTLSContext()
      33             : #include "tif_jxl.h"
      34             : #include "tifvsi.h"
      35             : #include "xtiffio.h"
      36             : 
      37             : static const GTIFFTag asTIFFTags[] = {
      38             :     {"TIFFTAG_DOCUMENTNAME", TIFFTAG_DOCUMENTNAME, GTIFFTAGTYPE_STRING},
      39             :     {"TIFFTAG_IMAGEDESCRIPTION", TIFFTAG_IMAGEDESCRIPTION, GTIFFTAGTYPE_STRING},
      40             :     {"TIFFTAG_SOFTWARE", TIFFTAG_SOFTWARE, GTIFFTAGTYPE_STRING},
      41             :     {"TIFFTAG_DATETIME", TIFFTAG_DATETIME, GTIFFTAGTYPE_STRING},
      42             :     {"TIFFTAG_ARTIST", TIFFTAG_ARTIST, GTIFFTAGTYPE_STRING},
      43             :     {"TIFFTAG_HOSTCOMPUTER", TIFFTAG_HOSTCOMPUTER, GTIFFTAGTYPE_STRING},
      44             :     {"TIFFTAG_COPYRIGHT", TIFFTAG_COPYRIGHT, GTIFFTAGTYPE_STRING},
      45             :     {"TIFFTAG_XRESOLUTION", TIFFTAG_XRESOLUTION, GTIFFTAGTYPE_FLOAT},
      46             :     {"TIFFTAG_YRESOLUTION", TIFFTAG_YRESOLUTION, GTIFFTAGTYPE_FLOAT},
      47             :     // Dealt as special case.
      48             :     {"TIFFTAG_RESOLUTIONUNIT", TIFFTAG_RESOLUTIONUNIT, GTIFFTAGTYPE_SHORT},
      49             :     {"TIFFTAG_MINSAMPLEVALUE", TIFFTAG_MINSAMPLEVALUE, GTIFFTAGTYPE_SHORT},
      50             :     {"TIFFTAG_MAXSAMPLEVALUE", TIFFTAG_MAXSAMPLEVALUE, GTIFFTAGTYPE_SHORT},
      51             : 
      52             :     // GeoTIFF DGIWG tags
      53             :     {"GEO_METADATA", TIFFTAG_GEO_METADATA, GTIFFTAGTYPE_BYTE_STRING},
      54             :     {"TIFF_RSID", TIFFTAG_TIFF_RSID, GTIFFTAGTYPE_STRING},
      55             :     {nullptr, 0, GTIFFTAGTYPE_STRING},
      56             : };
      57             : 
      58             : /************************************************************************/
      59             : /*                            GetTIFFTags()                             */
      60             : /************************************************************************/
      61             : 
      62       24983 : const GTIFFTag *GTiffDataset::GetTIFFTags()
      63             : {
      64       24983 :     return asTIFFTags;
      65             : }
      66             : 
      67             : /************************************************************************/
      68             : /*                            GTiffDataset()                            */
      69             : /************************************************************************/
      70             : 
      71       26050 : GTiffDataset::GTiffDataset()
      72             :     : m_bStreamingIn(false), m_bStreamingOut(false), m_bScanDeferred(true),
      73             :       m_bSingleIFDOpened(false), m_bLoadedBlockDirty(false),
      74             :       m_bWriteError(false), m_bLookedForProjection(false),
      75             :       m_bLookedForMDAreaOrPoint(false), m_bGeoTransformValid(false),
      76             :       m_bCrystalized(true), m_bGeoTIFFInfoChanged(false),
      77             :       m_bForceUnsetGTOrGCPs(false), m_bForceUnsetProjection(false),
      78             :       m_bNoDataChanged(false), m_bNoDataSet(false), m_bNoDataSetAsInt64(false),
      79             :       m_bNoDataSetAsUInt64(false), m_bMetadataChanged(false),
      80             :       m_bColorProfileMetadataChanged(false), m_bForceUnsetRPC(false),
      81             :       m_bNeedsRewrite(false), m_bLoadingOtherBands(false), m_bIsOverview(false),
      82             :       m_bWriteEmptyTiles(true), m_bFillEmptyTilesAtClosing(false),
      83             :       m_bTreatAsSplit(false), m_bTreatAsSplitBitmap(false), m_bClipWarn(false),
      84             :       m_bIMDRPCMetadataLoaded(false), m_bEXIFMetadataLoaded(false),
      85             :       m_bICCMetadataLoaded(false),
      86             :       m_bHasWarnedDisableAggressiveBandCaching(false),
      87             :       m_bDontReloadFirstBlock(false), m_bWebPLossless(false),
      88             :       m_bPromoteTo8Bits(false),
      89             :       m_bDebugDontWriteBlocks(
      90       26066 :           CPLTestBool(CPLGetConfigOption("GTIFF_DONT_WRITE_BLOCKS", "NO"))),
      91             :       m_bIsFinalized(false),
      92             :       m_bIgnoreReadErrors(
      93       26064 :           CPLTestBool(CPLGetConfigOption("GTIFF_IGNORE_READ_ERRORS", "NO"))),
      94       26064 :       m_bDirectIO(CPLTestBool(CPLGetConfigOption("GTIFF_DIRECT_IO", "NO"))),
      95             :       m_bReadGeoTransform(false), m_bLoadPam(false),
      96             :       m_bHasGotSiblingFiles(false),
      97             :       m_bHasIdentifiedAuthorizedGeoreferencingSources(false),
      98             :       m_bLayoutIFDSBeforeData(false), m_bBlockOrderRowMajor(false),
      99             :       m_bLeaderSizeAsUInt4(false), m_bTrailerRepeatedLast4BytesRepeated(false),
     100             :       m_bMaskInterleavedWithImagery(false), m_bKnownIncompatibleEdition(false),
     101             :       m_bWriteKnownIncompatibleEdition(false), m_bHasUsedReadEncodedAPI(false),
     102       78182 :       m_bWriteCOGLayout(false)
     103             : {
     104             :     // CPLDebug("GDAL", "sizeof(GTiffDataset) = %d bytes", static_cast<int>(
     105             :     //     sizeof(GTiffDataset)));
     106             : 
     107             :     const char *pszVirtualMemIO =
     108       26065 :         CPLGetConfigOption("GTIFF_VIRTUAL_MEM_IO", "NO");
     109       26066 :     if (EQUAL(pszVirtualMemIO, "IF_ENOUGH_RAM"))
     110           0 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::IF_ENOUGH_RAM;
     111       26066 :     else if (CPLTestBool(pszVirtualMemIO))
     112          41 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::YES;
     113             : 
     114       26065 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     115       25979 : }
     116             : 
     117             : /************************************************************************/
     118             : /*                           ~GTiffDataset()                            */
     119             : /************************************************************************/
     120             : 
     121       52122 : GTiffDataset::~GTiffDataset()
     122             : 
     123             : {
     124       26060 :     GTiffDataset::Close();
     125       52116 : }
     126             : 
     127             : /************************************************************************/
     128             : /*                              Close()                                 */
     129             : /************************************************************************/
     130             : 
     131       46389 : CPLErr GTiffDataset::Close()
     132             : {
     133       46389 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     134             :     {
     135       26064 :         auto [eErr, bDroppedRef] = Finalize();
     136             : 
     137       26062 :         if (m_pszTmpFilename)
     138             :         {
     139           4 :             VSIUnlink(m_pszTmpFilename);
     140           4 :             CPLFree(m_pszTmpFilename);
     141             :         }
     142             : 
     143       26062 :         if (GDALPamDataset::Close() != CE_None)
     144           0 :             eErr = CE_Failure;
     145       26062 :         return eErr;
     146             :     }
     147       20325 :     return CE_None;
     148             : }
     149             : 
     150             : /************************************************************************/
     151             : /*                             Finalize()                               */
     152             : /************************************************************************/
     153             : 
     154             : // Return a tuple (CPLErr, bool) to indicate respectively if an I/O error has
     155             : // occurred and if a reference to an auxiliary dataset has been dropped.
     156       26144 : std::tuple<CPLErr, bool> GTiffDataset::Finalize()
     157             : {
     158       26144 :     bool bDroppedRef = false;
     159       26144 :     if (m_bIsFinalized)
     160         160 :         return std::tuple(CE_None, bDroppedRef);
     161             : 
     162       26064 :     CPLErr eErr = CE_None;
     163       26064 :     Crystalize();
     164             : 
     165       26064 :     if (m_bColorProfileMetadataChanged)
     166             :     {
     167           2 :         SaveICCProfile(this, nullptr, nullptr, 0);
     168           2 :         m_bColorProfileMetadataChanged = false;
     169             :     }
     170             : 
     171             :     /* -------------------------------------------------------------------- */
     172             :     /*      Handle forcing xml:ESRI data to be written to PAM.              */
     173             :     /* -------------------------------------------------------------------- */
     174       26064 :     if (CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
     175             :     {
     176           7 :         char **papszESRIMD = GTiffDataset::GetMetadata("xml:ESRI");
     177           7 :         if (papszESRIMD)
     178             :         {
     179           5 :             GDALPamDataset::SetMetadata(papszESRIMD, "xml:ESRI");
     180             :         }
     181             :     }
     182             : 
     183       26064 :     if (m_psVirtualMemIOMapping)
     184          11 :         CPLVirtualMemFree(m_psVirtualMemIOMapping);
     185       26064 :     m_psVirtualMemIOMapping = nullptr;
     186             : 
     187             :     /* -------------------------------------------------------------------- */
     188             :     /*      Fill in missing blocks with empty data.                         */
     189             :     /* -------------------------------------------------------------------- */
     190       26064 :     if (m_bFillEmptyTilesAtClosing)
     191             :     {
     192             :         /* --------------------------------------------------------------------
     193             :          */
     194             :         /*  Ensure any blocks write cached by GDAL gets pushed through libtiff.
     195             :          */
     196             :         /* --------------------------------------------------------------------
     197             :          */
     198        5135 :         if (FlushCacheInternal(true, /* at closing */
     199        5135 :                                false /* do not call FlushDirectory */) !=
     200             :             CE_None)
     201             :         {
     202           0 :             eErr = CE_Failure;
     203             :         }
     204             : 
     205        5135 :         if (FillEmptyTiles() != CE_None)
     206             :         {
     207           9 :             eErr = CE_Failure;
     208             :         }
     209        5135 :         m_bFillEmptyTilesAtClosing = false;
     210             :     }
     211             : 
     212             :     /* -------------------------------------------------------------------- */
     213             :     /*      Force a complete flush, including either rewriting(moving)      */
     214             :     /*      of writing in place the current directory.                      */
     215             :     /* -------------------------------------------------------------------- */
     216       26064 :     if (FlushCacheInternal(true /* at closing */, true) != CE_None)
     217             :     {
     218           7 :         eErr = CE_Failure;
     219             :     }
     220             : 
     221             :     // Destroy compression queue
     222       26064 :     if (m_poCompressQueue)
     223             :     {
     224          57 :         m_poCompressQueue->WaitCompletion();
     225             : 
     226         276 :         for (int i = 0; i < static_cast<int>(m_asCompressionJobs.size()); ++i)
     227             :         {
     228         219 :             CPLFree(m_asCompressionJobs[i].pabyBuffer);
     229         219 :             if (m_asCompressionJobs[i].pszTmpFilename)
     230             :             {
     231         219 :                 VSIUnlink(m_asCompressionJobs[i].pszTmpFilename);
     232         219 :                 CPLFree(m_asCompressionJobs[i].pszTmpFilename);
     233             :             }
     234             :         }
     235          57 :         m_poCompressQueue.reset();
     236             :     }
     237             : 
     238             :     /* -------------------------------------------------------------------- */
     239             :     /*      If there is still changed metadata, then presumably we want     */
     240             :     /*      to push it into PAM.                                            */
     241             :     /* -------------------------------------------------------------------- */
     242       26063 :     if (m_bMetadataChanged)
     243             :     {
     244           6 :         PushMetadataToPam();
     245           6 :         m_bMetadataChanged = false;
     246           6 :         GDALPamDataset::FlushCache(false);
     247             :     }
     248             : 
     249             :     /* -------------------------------------------------------------------- */
     250             :     /*      Cleanup overviews.                                              */
     251             :     /* -------------------------------------------------------------------- */
     252       26063 :     if (!m_poBaseDS)
     253             :     {
     254             :         // Nullify m_nOverviewCount before deleting overviews, otherwise
     255             :         // GTiffDataset::FlushDirectory() might try to access an overview
     256             :         // that is being deleted (#5580)
     257       24501 :         const int nOldOverviewCount = m_nOverviewCount;
     258       24501 :         m_nOverviewCount = 0;
     259       25774 :         for (int i = 0; i < nOldOverviewCount; ++i)
     260             :         {
     261        1273 :             delete m_papoOverviewDS[i];
     262        1273 :             bDroppedRef = true;
     263             :         }
     264             : 
     265       24561 :         for (int i = 0; i < m_nJPEGOverviewCountOri; ++i)
     266             :         {
     267          60 :             delete m_papoJPEGOverviewDS[i];
     268          60 :             bDroppedRef = true;
     269             :         }
     270       24501 :         m_nJPEGOverviewCount = 0;
     271       24501 :         m_nJPEGOverviewCountOri = 0;
     272       24501 :         CPLFree(m_papoJPEGOverviewDS);
     273       24500 :         m_papoJPEGOverviewDS = nullptr;
     274             :     }
     275             : 
     276             :     // If we are a mask dataset, we can have overviews, but we don't
     277             :     // own them. We can only free the array, not the overviews themselves.
     278       26062 :     CPLFree(m_papoOverviewDS);
     279       26062 :     m_papoOverviewDS = nullptr;
     280             : 
     281             :     // m_poMaskDS is owned by the main image and the overviews
     282             :     // so because of the latter case, we can delete it even if
     283             :     // we are not the base image.
     284       26062 :     if (m_poMaskDS)
     285             :     {
     286             :         // Nullify m_nOverviewCount before deleting overviews, otherwise
     287             :         // GTiffDataset::FlushDirectory() might try to access it while being
     288             :         // deleted. (#5580)
     289         286 :         auto poMaskDS = m_poMaskDS;
     290         286 :         m_poMaskDS = nullptr;
     291         286 :         delete poMaskDS;
     292         286 :         bDroppedRef = true;
     293             :     }
     294             : 
     295       26062 :     m_poColorTable.reset();
     296             : 
     297       26063 :     if (m_hTIFF)
     298             :     {
     299       26062 :         XTIFFClose(m_hTIFF);
     300       26063 :         m_hTIFF = nullptr;
     301             :     }
     302             : 
     303       26064 :     if (!m_poBaseDS)
     304             :     {
     305       24502 :         if (m_fpL != nullptr)
     306             :         {
     307       24502 :             if (m_bWriteKnownIncompatibleEdition)
     308             :             {
     309             :                 GByte abyHeader[4096];
     310           9 :                 VSIFSeekL(m_fpL, 0, SEEK_SET);
     311           9 :                 VSIFReadL(abyHeader, 1, sizeof(abyHeader), m_fpL);
     312           9 :                 const char *szKeyToLook =
     313             :                     "KNOWN_INCOMPATIBLE_EDITION=NO\n ";  // trailing space
     314             :                                                          // intended
     315        1449 :                 for (size_t i = 0; i < sizeof(abyHeader) - strlen(szKeyToLook);
     316             :                      i++)
     317             :                 {
     318        1449 :                     if (memcmp(abyHeader + i, szKeyToLook,
     319             :                                strlen(szKeyToLook)) == 0)
     320             :                     {
     321           9 :                         const char *szNewKey =
     322             :                             "KNOWN_INCOMPATIBLE_EDITION=YES\n";
     323           9 :                         CPLAssert(strlen(szKeyToLook) == strlen(szNewKey));
     324           9 :                         memcpy(abyHeader + i, szNewKey, strlen(szNewKey));
     325           9 :                         VSIFSeekL(m_fpL, 0, SEEK_SET);
     326           9 :                         VSIFWriteL(abyHeader, 1, sizeof(abyHeader), m_fpL);
     327           9 :                         break;
     328             :                     }
     329             :                 }
     330             :             }
     331       24502 :             if (VSIFCloseL(m_fpL) != 0)
     332             :             {
     333           0 :                 eErr = CE_Failure;
     334           0 :                 ReportError(CE_Failure, CPLE_FileIO, "I/O error");
     335             :             }
     336       24502 :             m_fpL = nullptr;
     337             :         }
     338             :     }
     339             : 
     340       26064 :     if (m_fpToWrite != nullptr)
     341             :     {
     342           7 :         if (VSIFCloseL(m_fpToWrite) != 0)
     343             :         {
     344           0 :             eErr = CE_Failure;
     345           0 :             ReportError(CE_Failure, CPLE_FileIO, "I/O error");
     346             :         }
     347           7 :         m_fpToWrite = nullptr;
     348             :     }
     349             : 
     350       26064 :     m_aoGCPs.clear();
     351             : 
     352       26064 :     CSLDestroy(m_papszCreationOptions);
     353       26064 :     m_papszCreationOptions = nullptr;
     354             : 
     355       26064 :     CPLFree(m_pabyTempWriteBuffer);
     356       26064 :     m_pabyTempWriteBuffer = nullptr;
     357             : 
     358       26064 :     m_bIMDRPCMetadataLoaded = false;
     359       26064 :     CSLDestroy(m_papszMetadataFiles);
     360       26064 :     m_papszMetadataFiles = nullptr;
     361             : 
     362       26064 :     VSIFree(m_pTempBufferForCommonDirectIO);
     363       26064 :     m_pTempBufferForCommonDirectIO = nullptr;
     364             : 
     365       26064 :     CPLFree(m_panMaskOffsetLsb);
     366       26064 :     m_panMaskOffsetLsb = nullptr;
     367             : 
     368       26064 :     CPLFree(m_pszVertUnit);
     369       26064 :     m_pszVertUnit = nullptr;
     370             : 
     371       26064 :     CPLFree(m_pszFilename);
     372       26063 :     m_pszFilename = nullptr;
     373             : 
     374       26063 :     CPLFree(m_pszGeorefFilename);
     375       26063 :     m_pszGeorefFilename = nullptr;
     376             : 
     377       26063 :     CPLFree(m_pszXMLFilename);
     378       26064 :     m_pszXMLFilename = nullptr;
     379             : 
     380       26064 :     m_bIsFinalized = true;
     381             : 
     382       26064 :     return std::tuple(eErr, bDroppedRef);
     383             : }
     384             : 
     385             : /************************************************************************/
     386             : /*                        CloseDependentDatasets()                      */
     387             : /************************************************************************/
     388             : 
     389          80 : int GTiffDataset::CloseDependentDatasets()
     390             : {
     391          80 :     if (m_poBaseDS)
     392           0 :         return FALSE;
     393             : 
     394          80 :     int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();
     395             : 
     396             :     // We ignore eErr as it is not relevant for CloseDependentDatasets(),
     397             :     // which is called in a "garbage collection" context.
     398          80 :     auto [eErr, bHasDroppedRefInFinalize] = Finalize();
     399          80 :     if (bHasDroppedRefInFinalize)
     400           1 :         bHasDroppedRef = true;
     401             : 
     402          80 :     return bHasDroppedRef;
     403             : }
     404             : 
     405             : /************************************************************************/
     406             : /*                        IsWholeBlock()                                */
     407             : /************************************************************************/
     408             : 
     409          27 : bool GTiffDataset::IsWholeBlock(int nXOff, int nYOff, int nXSize,
     410             :                                 int nYSize) const
     411             : {
     412          27 :     if ((nXOff % m_nBlockXSize) != 0 || (nYOff % m_nBlockYSize) != 0)
     413             :     {
     414           0 :         return false;
     415             :     }
     416          27 :     if (TIFFIsTiled(m_hTIFF))
     417             :     {
     418           3 :         return nXSize == m_nBlockXSize && nYSize == m_nBlockYSize;
     419             :     }
     420             :     else
     421             :     {
     422          46 :         return nXSize == m_nBlockXSize &&
     423          46 :                (nYSize == m_nBlockYSize || nYOff + nYSize == nRasterYSize);
     424             :     }
     425             : }
     426             : 
     427             : /************************************************************************/
     428             : /*                            IRasterIO()                               */
     429             : /************************************************************************/
     430             : 
     431      433881 : CPLErr GTiffDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
     432             :                                int nXSize, int nYSize, void *pData,
     433             :                                int nBufXSize, int nBufYSize,
     434             :                                GDALDataType eBufType, int nBandCount,
     435             :                                BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
     436             :                                GSpacing nLineSpace, GSpacing nBandSpace,
     437             :                                GDALRasterIOExtraArg *psExtraArg)
     438             : 
     439             : {
     440             :     // Try to pass the request to the most appropriate overview dataset.
     441      433881 :     if (nBufXSize < nXSize && nBufYSize < nYSize)
     442             :     {
     443      157845 :         int bTried = FALSE;
     444      157845 :         if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     445      157696 :             ++m_nJPEGOverviewVisibilityCounter;
     446      157845 :         const CPLErr eErr = TryOverviewRasterIO(
     447             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
     448             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
     449             :             nBandSpace, psExtraArg, &bTried);
     450      157845 :         if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     451      157696 :             --m_nJPEGOverviewVisibilityCounter;
     452      157845 :         if (bTried)
     453          22 :             return eErr;
     454             :     }
     455             : 
     456      433859 :     if (m_eVirtualMemIOUsage != VirtualMemIOEnum::NO)
     457             :     {
     458             :         const int nErr =
     459         649 :             VirtualMemIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
     460             :                          nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap,
     461             :                          nPixelSpace, nLineSpace, nBandSpace, psExtraArg);
     462         649 :         if (nErr >= 0)
     463         608 :             return static_cast<CPLErr>(nErr);
     464             :     }
     465      433251 :     if (m_bDirectIO)
     466             :     {
     467             :         const int nErr =
     468         471 :             DirectIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize,
     469             :                      nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace,
     470             :                      nLineSpace, nBandSpace, psExtraArg);
     471         471 :         if (nErr >= 0)
     472         414 :             return static_cast<CPLErr>(nErr);
     473             :     }
     474             : 
     475      432837 :     bool bCanUseMultiThreadedRead = false;
     476      432837 :     if (m_nDisableMultiThreadedRead == 0 && m_poThreadPool &&
     477      865819 :         eRWFlag == GF_Read && nBufXSize == nXSize && nBufYSize == nYSize &&
     478         145 :         IsMultiThreadedReadCompatible())
     479             :     {
     480         145 :         const int nBlockX1 = nXOff / m_nBlockXSize;
     481         145 :         const int nBlockY1 = nYOff / m_nBlockYSize;
     482         145 :         const int nBlockX2 = (nXOff + nXSize - 1) / m_nBlockXSize;
     483         145 :         const int nBlockY2 = (nYOff + nYSize - 1) / m_nBlockYSize;
     484         145 :         const int nXBlocks = nBlockX2 - nBlockX1 + 1;
     485         145 :         const int nYBlocks = nBlockY2 - nBlockY1 + 1;
     486         145 :         const int nBlocks =
     487         145 :             nXBlocks * nYBlocks *
     488         145 :             (m_nPlanarConfig == PLANARCONFIG_CONTIG ? 1 : nBandCount);
     489         145 :         if (nBlocks > 1)
     490             :         {
     491         142 :             bCanUseMultiThreadedRead = true;
     492             :         }
     493             :     }
     494             : 
     495      432837 :     void *pBufferedData = nullptr;
     496      432837 :     const auto poFirstBand = cpl::down_cast<GTiffRasterBand *>(papoBands[0]);
     497      432837 :     const auto eDataType = poFirstBand->GetRasterDataType();
     498             : 
     499       37922 :     if (eAccess == GA_ReadOnly && eRWFlag == GF_Read &&
     500       37922 :         (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG) &&
     501      470773 :         HasOptimizedReadMultiRange() &&
     502          15 :         !(bCanUseMultiThreadedRead &&
     503           3 :           VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF))->HasPRead()))
     504             :     {
     505          12 :         pBufferedData = poFirstBand->CacheMultiRange(
     506             :             nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, psExtraArg);
     507             :     }
     508      432824 :     else if (bCanUseMultiThreadedRead)
     509             :     {
     510         142 :         return MultiThreadedRead(nXOff, nYOff, nXSize, nYSize, pData, eBufType,
     511             :                                  nBandCount, panBandMap, nPixelSpace,
     512         142 :                                  nLineSpace, nBandSpace);
     513             :     }
     514             : 
     515             :     // Write optimization when writing whole blocks, by-passing the block cache.
     516             :     // We require the block cache to be non instantiated to simplify things
     517             :     // (otherwise we might need to evict corresponding existing blocks from the
     518             :     // block cache).
     519      201606 :     else if (eRWFlag == GF_Write && nBands > 1 &&
     520       28723 :              m_nPlanarConfig == PLANARCONFIG_CONTIG &&
     521             :              // Could be extended to "odd bit" case, but more work
     522       28234 :              m_nBitsPerSample == GDALGetDataTypeSize(eDataType) &&
     523       28223 :              nXSize == nBufXSize && nYSize == nBufYSize &&
     524       28221 :              nBandCount == nBands && !m_bLoadedBlockDirty &&
     525       28200 :              (nXOff % m_nBlockXSize) == 0 && (nYOff % m_nBlockYSize) == 0 &&
     526        2459 :              (nXOff + nXSize == nRasterXSize ||
     527      634328 :               (nXSize % m_nBlockXSize) == 0) &&
     528        2456 :              (nYOff + nYSize == nRasterYSize || (nYSize % m_nBlockYSize) == 0))
     529             :     {
     530        2334 :         bool bOptimOK = true;
     531        2334 :         bool bOrderedBands = true;
     532        9650 :         for (int i = 0; i < nBands; ++i)
     533             :         {
     534        7325 :             if (panBandMap[i] != i + 1)
     535             :             {
     536          14 :                 bOrderedBands = false;
     537             :             }
     538       14650 :             if (cpl::down_cast<GTiffRasterBand *>(papoBands[panBandMap[i] - 1])
     539        7325 :                     ->HasBlockCache())
     540             :             {
     541           9 :                 bOptimOK = false;
     542           9 :                 break;
     543             :             }
     544             :         }
     545        2334 :         if (bOptimOK)
     546             :         {
     547        2325 :             Crystalize();
     548             : 
     549        2325 :             if (m_bDebugDontWriteBlocks)
     550           0 :                 return CE_None;
     551             : 
     552        2325 :             const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
     553        2325 :             if (bOrderedBands && nXSize == m_nBlockXSize &&
     554        2104 :                 nYSize == m_nBlockYSize && eBufType == eDataType &&
     555        1156 :                 nBandSpace == nDTSize &&
     556          22 :                 nPixelSpace == static_cast<GSpacing>(nDTSize) * nBands &&
     557           5 :                 nLineSpace == nPixelSpace * m_nBlockXSize)
     558             :             {
     559             :                 // If writing one single block with the right data type and
     560             :                 // layout (interleaved per pixel), we don't need a temporary
     561             :                 // buffer
     562          10 :                 const int nBlockId = poFirstBand->ComputeBlockId(
     563           5 :                     nXOff / m_nBlockXSize, nYOff / m_nBlockYSize);
     564           5 :                 return WriteEncodedTileOrStrip(nBlockId, pData,
     565           5 :                                                /* bPreserveDataBuffer= */ true);
     566             :             }
     567             : 
     568             :             // Make sure m_poGDS->m_pabyBlockBuf is allocated.
     569             :             // We could actually use any temporary buffer
     570        2320 :             if (LoadBlockBuf(/* nBlockId = */ -1,
     571        2320 :                              /* bReadFromDisk = */ false) != CE_None)
     572             :             {
     573           0 :                 return CE_Failure;
     574             :             }
     575             : 
     576             :             // Iterate over all blocks defined by
     577             :             // [nXOff, nXOff+nXSize[ * [nYOff, nYOff+nYSize[
     578             :             // and write their content as a nBlockXSize x nBlockYSize strile
     579             :             // in a temporary buffer, before calling WriteEncodedTileOrStrip()
     580             :             // on it
     581        2320 :             const int nYBlockStart = nYOff / m_nBlockYSize;
     582        2320 :             const int nYBlockEnd = 1 + (nYOff + nYSize - 1) / m_nBlockYSize;
     583        2320 :             const int nXBlockStart = nXOff / m_nBlockXSize;
     584        2320 :             const int nXBlockEnd = 1 + (nXOff + nXSize - 1) / m_nBlockXSize;
     585       32395 :             for (int nYBlock = nYBlockStart; nYBlock < nYBlockEnd; ++nYBlock)
     586             :             {
     587             :                 const int nValidY = std::min(
     588       30079 :                     m_nBlockYSize, nRasterYSize - nYBlock * m_nBlockYSize);
     589       62911 :                 for (int nXBlock = nXBlockStart; nXBlock < nXBlockEnd;
     590             :                      ++nXBlock)
     591             :                 {
     592             :                     const int nValidX = std::min(
     593       32836 :                         m_nBlockXSize, nRasterXSize - nXBlock * m_nBlockXSize);
     594       32836 :                     if (nValidY < m_nBlockYSize || nValidX < m_nBlockXSize)
     595             :                     {
     596             :                         // Make sure padding bytes at the right/bottom of the
     597             :                         // tile are initialized to zero.
     598        1247 :                         memset(m_pabyBlockBuf, 0,
     599        1247 :                                static_cast<size_t>(m_nBlockXSize) *
     600        1247 :                                    m_nBlockYSize * nBands * nDTSize);
     601             :                     }
     602       32836 :                     const auto nBufDTSize = GDALGetDataTypeSizeBytes(eBufType);
     603       32836 :                     const GByte *pabySrcData =
     604             :                         static_cast<const GByte *>(pData) +
     605       32836 :                         static_cast<size_t>(nYBlock - nYBlockStart) *
     606       32836 :                             m_nBlockYSize * nLineSpace +
     607       32836 :                         static_cast<size_t>(nXBlock - nXBlockStart) *
     608       32836 :                             m_nBlockXSize * nPixelSpace;
     609       32836 :                     if (bOrderedBands && nBandSpace == nBufDTSize &&
     610          19 :                         nPixelSpace == nBands * nBandSpace)
     611             :                     {
     612             :                         // Input buffer is pixel interleaved
     613          17 :                         for (int iY = 0; iY < nValidY; ++iY)
     614             :                         {
     615          16 :                             GDALCopyWords64(
     616          16 :                                 pabySrcData +
     617          16 :                                     static_cast<size_t>(iY) * nLineSpace,
     618             :                                 eBufType, nBufDTSize,
     619          16 :                                 m_pabyBlockBuf + static_cast<size_t>(iY) *
     620          16 :                                                      m_nBlockXSize * nBands *
     621          16 :                                                      nDTSize,
     622             :                                 eDataType, nDTSize,
     623          16 :                                 static_cast<GPtrDiff_t>(nValidX) * nBands);
     624           1 :                         }
     625             :                     }
     626             :                     else
     627             :                     {
     628             :                         // "Random" spacing for input buffer
     629      133968 :                         for (int iBand = 0; iBand < nBands; ++iBand)
     630             :                         {
     631     4222190 :                             for (int iY = 0; iY < nValidY; ++iY)
     632             :                             {
     633     4121060 :                                 GDALCopyWords64(
     634     4121060 :                                     pabySrcData +
     635     4121060 :                                         static_cast<size_t>(iY) * nLineSpace,
     636             :                                     eBufType, static_cast<int>(nPixelSpace),
     637     4121060 :                                     m_pabyBlockBuf +
     638     4121060 :                                         (panBandMap[iBand] - 1 +
     639     4121060 :                                          static_cast<size_t>(iY) *
     640     4121060 :                                              m_nBlockXSize * nBands) *
     641     4121060 :                                             nDTSize,
     642     4121060 :                                     eDataType, nDTSize * nBands, nValidX);
     643             :                             }
     644      101133 :                             pabySrcData += nBandSpace;
     645             :                         }
     646             :                     }
     647             : 
     648             :                     const int nBlockId =
     649       32836 :                         poFirstBand->ComputeBlockId(nXBlock, nYBlock);
     650       65672 :                     if (WriteEncodedTileOrStrip(
     651       32836 :                             nBlockId, m_pabyBlockBuf,
     652       32836 :                             /* bPreserveDataBuffer= */ false) != CE_None)
     653             :                     {
     654           4 :                         return CE_Failure;
     655             :                     }
     656             :                 }
     657             :             }
     658        2316 :             return CE_None;
     659             :         }
     660             :     }
     661             : 
     662      430369 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     663      430213 :         ++m_nJPEGOverviewVisibilityCounter;
     664      430369 :     const CPLErr eErr = GDALPamDataset::IRasterIO(
     665             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
     666             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
     667             :         psExtraArg);
     668      430370 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     669      430213 :         m_nJPEGOverviewVisibilityCounter--;
     670             : 
     671      430370 :     if (pBufferedData)
     672             :     {
     673           6 :         VSIFree(pBufferedData);
     674           6 :         VSI_TIFFSetCachedRanges(TIFFClientdata(m_hTIFF), 0, nullptr, nullptr,
     675             :                                 nullptr);
     676             :     }
     677             : 
     678      430370 :     return eErr;
     679             : }
     680             : 
     681             : /************************************************************************/
     682             : /*                       GetGTIFFKeysFlavor()                           */
     683             : /************************************************************************/
     684             : 
     685       25837 : GTIFFKeysFlavorEnum GetGTIFFKeysFlavor(CSLConstList papszOptions)
     686             : {
     687             :     const char *pszGeoTIFFKeysFlavor =
     688       25837 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_KEYS_FLAVOR", "STANDARD");
     689       25785 :     if (EQUAL(pszGeoTIFFKeysFlavor, "ESRI_PE"))
     690           1 :         return GEOTIFF_KEYS_ESRI_PE;
     691       25784 :     return GEOTIFF_KEYS_STANDARD;
     692             : }
     693             : 
     694             : /************************************************************************/
     695             : /*                       GetGeoTIFFVersion()                            */
     696             : /************************************************************************/
     697             : 
     698       25726 : GeoTIFFVersionEnum GetGeoTIFFVersion(CSLConstList papszOptions)
     699             : {
     700             :     const char *pszVersion =
     701       25726 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_VERSION", "AUTO");
     702       25773 :     if (EQUAL(pszVersion, "1.0"))
     703           3 :         return GEOTIFF_VERSION_1_0;
     704       25770 :     if (EQUAL(pszVersion, "1.1"))
     705           5 :         return GEOTIFF_VERSION_1_1;
     706       25765 :     return GEOTIFF_VERSION_AUTO;
     707             : }
     708             : 
     709             : /************************************************************************/
     710             : /*                      InitCreationOrOpenOptions()                     */
     711             : /************************************************************************/
     712             : 
     713       24440 : void GTiffDataset::InitCreationOrOpenOptions(bool bUpdateMode,
     714             :                                              CSLConstList papszOptions)
     715             : {
     716       24440 :     InitCompressionThreads(bUpdateMode, papszOptions);
     717             : 
     718       24403 :     m_eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
     719       24349 :     m_eGeoTIFFVersion = GetGeoTIFFVersion(papszOptions);
     720       24344 : }
     721             : 
     722             : /************************************************************************/
     723             : /*                          IsBlockAvailable()                          */
     724             : /*                                                                      */
     725             : /*      Return true if the indicated strip/tile is available.  We       */
     726             : /*      establish this by testing if the stripbytecount is zero.  If    */
     727             : /*      zero then the block has never been committed to disk.           */
     728             : /************************************************************************/
     729             : 
     730     2268640 : bool GTiffDataset::IsBlockAvailable(int nBlockId, vsi_l_offset *pnOffset,
     731             :                                     vsi_l_offset *pnSize, bool *pbErrOccurred)
     732             : 
     733             : {
     734     2268640 :     if (pbErrOccurred)
     735     2231040 :         *pbErrOccurred = false;
     736             : 
     737     2268640 :     std::pair<vsi_l_offset, vsi_l_offset> oPair;
     738     2268640 :     if (m_oCacheStrileToOffsetByteCount.tryGet(nBlockId, oPair))
     739             :     {
     740         428 :         if (pnOffset)
     741          87 :             *pnOffset = oPair.first;
     742         428 :         if (pnSize)
     743           0 :             *pnSize = oPair.second;
     744         428 :         return oPair.first != 0;
     745             :     }
     746             : 
     747     2268120 :     WaitCompletionForBlock(nBlockId);
     748             : 
     749             :     // Optimization to avoid fetching the whole Strip/TileCounts and
     750             :     // Strip/TileOffsets arrays.
     751     2268140 :     if (eAccess == GA_ReadOnly && !m_bStreamingIn)
     752             :     {
     753     2167560 :         int nErrOccurred = 0;
     754             :         auto bytecount =
     755     2167560 :             TIFFGetStrileByteCountWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     756     2167550 :         if (nErrOccurred && pbErrOccurred)
     757           0 :             *pbErrOccurred = true;
     758     2167550 :         if (pnOffset)
     759             :         {
     760     2117430 :             *pnOffset =
     761     2117390 :                 TIFFGetStrileOffsetWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     762     2117430 :             if (nErrOccurred && pbErrOccurred)
     763           1 :                 *pbErrOccurred = true;
     764             :         }
     765     2167580 :         if (pnSize)
     766        4352 :             *pnSize = bytecount;
     767     2167580 :         return bytecount != 0;
     768             :     }
     769             : 
     770      100585 :     toff_t *panByteCounts = nullptr;
     771      100585 :     toff_t *panOffsets = nullptr;
     772      100585 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
     773             : 
     774      133673 :     if ((bIsTiled &&
     775       33119 :          TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
     776       25040 :          (pnOffset == nullptr ||
     777      201108 :           TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets))) ||
     778       67435 :         (!bIsTiled &&
     779       67435 :          TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
     780       36408 :          (pnOffset == nullptr ||
     781       36408 :           TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
     782             :     {
     783      100554 :         if (panByteCounts == nullptr ||
     784       61448 :             (pnOffset != nullptr && panOffsets == nullptr))
     785             :         {
     786           0 :             if (pbErrOccurred)
     787           0 :                 *pbErrOccurred = true;
     788           0 :             return false;
     789             :         }
     790             :         const int nBlockCount =
     791      100554 :             bIsTiled ? TIFFNumberOfTiles(m_hTIFF) : TIFFNumberOfStrips(m_hTIFF);
     792      100554 :         if (nBlockId >= nBlockCount)
     793             :         {
     794           0 :             if (pbErrOccurred)
     795           0 :                 *pbErrOccurred = true;
     796           0 :             return false;
     797             :         }
     798             : 
     799      100554 :         if (pnOffset)
     800       61448 :             *pnOffset = panOffsets[nBlockId];
     801      100554 :         if (pnSize)
     802        7065 :             *pnSize = panByteCounts[nBlockId];
     803      100554 :         return panByteCounts[nBlockId] != 0;
     804             :     }
     805             :     else
     806             :     {
     807           0 :         if (pbErrOccurred)
     808           0 :             *pbErrOccurred = true;
     809             :     }
     810             : 
     811           0 :     return false;
     812             : }
     813             : 
     814             : /************************************************************************/
     815             : /*                           ReloadDirectory()                          */
     816             : /************************************************************************/
     817             : 
     818        6595 : void GTiffDataset::ReloadDirectory(bool bReopenHandle)
     819             : {
     820        6595 :     bool bNeedSetInvalidDir = true;
     821        6595 :     if (bReopenHandle)
     822             :     {
     823             :         // When issuing a TIFFRewriteDirectory() or when a TIFFFlush() has
     824             :         // caused a move of the directory, we would need to invalidate the
     825             :         // tif_lastdiroff member, but it is not possible to do so without
     826             :         // re-opening the TIFF handle.
     827           9 :         auto hTIFFNew = VSI_TIFFReOpen(m_hTIFF);
     828           9 :         if (hTIFFNew != nullptr)
     829             :         {
     830           9 :             m_hTIFF = hTIFFNew;
     831           9 :             bNeedSetInvalidDir = false;  // we could do it, but not needed
     832             :         }
     833             :         else
     834             :         {
     835           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     836             :                      "Cannot re-open TIFF handle for file %s. "
     837             :                      "Directory chaining may be corrupted !",
     838             :                      m_pszFilename);
     839             :         }
     840             :     }
     841        6595 :     if (bNeedSetInvalidDir)
     842             :     {
     843        6586 :         TIFFSetSubDirectory(m_hTIFF, 0);
     844             :     }
     845        6595 :     CPL_IGNORE_RET_VAL(SetDirectory());
     846        6595 : }
     847             : 
     848             : /************************************************************************/
     849             : /*                            SetDirectory()                            */
     850             : /************************************************************************/
     851             : 
     852       46254 : bool GTiffDataset::SetDirectory()
     853             : 
     854             : {
     855       46254 :     Crystalize();
     856             : 
     857       46220 :     if (TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
     858             :     {
     859       38031 :         return true;
     860             :     }
     861             : 
     862        8158 :     const int nSetDirResult = TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
     863        8158 :     if (!nSetDirResult)
     864           0 :         return false;
     865             : 
     866        8158 :     RestoreVolatileParameters(m_hTIFF);
     867             : 
     868        8158 :     return true;
     869             : }
     870             : 
     871             : /************************************************************************/
     872             : /*                     GTiffSetDeflateSubCodec()                        */
     873             : /************************************************************************/
     874             : 
     875        6311 : void GTiffSetDeflateSubCodec(TIFF *hTIFF)
     876             : {
     877             :     (void)hTIFF;
     878             : 
     879             : #if defined(TIFFTAG_DEFLATE_SUBCODEC) && defined(LIBDEFLATE_SUPPORT)
     880             :     // Mostly for strict reproducibility purposes
     881        6311 :     if (EQUAL(CPLGetConfigOption("GDAL_TIFF_DEFLATE_SUBCODEC", ""), "ZLIB"))
     882             :     {
     883        4097 :         TIFFSetField(hTIFF, TIFFTAG_DEFLATE_SUBCODEC, DEFLATE_SUBCODEC_ZLIB);
     884             :     }
     885             : #endif
     886        6311 : }
     887             : 
     888             : /************************************************************************/
     889             : /*                     RestoreVolatileParameters()                      */
     890             : /************************************************************************/
     891             : 
     892       40191 : void GTiffDataset::RestoreVolatileParameters(TIFF *hTIFF)
     893             : {
     894             : 
     895             :     /* -------------------------------------------------------------------- */
     896             :     /*      YCbCr JPEG compressed images should be translated on the fly    */
     897             :     /*      to RGB by libtiff/libjpeg unless specifically requested         */
     898             :     /*      otherwise.                                                      */
     899             :     /* -------------------------------------------------------------------- */
     900       80801 :     if (m_nCompression == COMPRESSION_JPEG &&
     901       40470 :         m_nPhotometric == PHOTOMETRIC_YCBCR &&
     902         280 :         CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
     903             :     {
     904         280 :         int nColorMode = JPEGCOLORMODE_RAW;  // Initialize to 0;
     905             : 
     906         280 :         TIFFGetField(hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode);
     907         280 :         if (nColorMode != JPEGCOLORMODE_RGB)
     908             :         {
     909         246 :             TIFFSetField(hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
     910             :         }
     911             :     }
     912             : 
     913       40190 :     if (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     914       34471 :         m_nCompression == COMPRESSION_LERC)
     915             :     {
     916        5956 :         GTiffSetDeflateSubCodec(hTIFF);
     917             :     }
     918             : 
     919             :     /* -------------------------------------------------------------------- */
     920             :     /*      Propagate any quality settings.                                 */
     921             :     /* -------------------------------------------------------------------- */
     922       40189 :     if (eAccess == GA_Update)
     923             :     {
     924             :         // Now, reset zip and jpeg quality.
     925       34342 :         if (m_nJpegQuality > 0 && m_nCompression == COMPRESSION_JPEG)
     926             :         {
     927             : #ifdef DEBUG_VERBOSE
     928             :             CPLDebug("GTiff", "Propagate JPEG_QUALITY(%d) in SetDirectory()",
     929             :                      m_nJpegQuality);
     930             : #endif
     931         182 :             TIFFSetField(hTIFF, TIFFTAG_JPEGQUALITY, m_nJpegQuality);
     932             :         }
     933       34342 :         if (m_nJpegTablesMode >= 0 && m_nCompression == COMPRESSION_JPEG)
     934         319 :             TIFFSetField(hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
     935       34342 :         if (m_nZLevel > 0 && (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     936          12 :                               m_nCompression == COMPRESSION_LERC))
     937          26 :             TIFFSetField(hTIFF, TIFFTAG_ZIPQUALITY, m_nZLevel);
     938       34342 :         if (m_nLZMAPreset > 0 && m_nCompression == COMPRESSION_LZMA)
     939           8 :             TIFFSetField(hTIFF, TIFFTAG_LZMAPRESET, m_nLZMAPreset);
     940       34342 :         if (m_nZSTDLevel > 0 && (m_nCompression == COMPRESSION_ZSTD ||
     941          12 :                                  m_nCompression == COMPRESSION_LERC))
     942          18 :             TIFFSetField(hTIFF, TIFFTAG_ZSTD_LEVEL, m_nZSTDLevel);
     943       34342 :         if (m_nCompression == COMPRESSION_LERC)
     944             :         {
     945         185 :             TIFFSetField(hTIFF, TIFFTAG_LERC_MAXZERROR, m_dfMaxZError);
     946             :         }
     947       34342 :         if (m_nWebPLevel > 0 && m_nCompression == COMPRESSION_WEBP)
     948         124 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LEVEL, m_nWebPLevel);
     949       34342 :         if (m_bWebPLossless && m_nCompression == COMPRESSION_WEBP)
     950          50 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
     951             : #ifdef HAVE_JXL
     952       34342 :         if (m_nCompression == COMPRESSION_JXL)
     953             :         {
     954          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_LOSSYNESS,
     955          76 :                          m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
     956          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_EFFORT, m_nJXLEffort);
     957          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_DISTANCE, m_fJXLDistance);
     958          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
     959          76 :                          m_fJXLAlphaDistance);
     960             :         }
     961             : #endif
     962             :     }
     963       40189 : }
     964             : 
     965             : /************************************************************************/
     966             : /*                     ComputeBlocksPerColRowAndBand()                  */
     967             : /************************************************************************/
     968             : 
     969       26013 : bool GTiffDataset::ComputeBlocksPerColRowAndBand(int l_nBands)
     970             : {
     971       26013 :     m_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, m_nBlockYSize);
     972       26013 :     m_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, m_nBlockXSize);
     973       26013 :     if (m_nBlocksPerColumn > INT_MAX / m_nBlocksPerRow)
     974             :     {
     975           1 :         ReportError(CE_Failure, CPLE_AppDefined, "Too many blocks: %d x %d",
     976             :                     m_nBlocksPerRow, m_nBlocksPerColumn);
     977           1 :         return false;
     978             :     }
     979             : 
     980             :     // Note: we could potentially go up to UINT_MAX blocks, but currently
     981             :     // we use a int nBlockId
     982       26012 :     m_nBlocksPerBand = m_nBlocksPerColumn * m_nBlocksPerRow;
     983       26012 :     if (m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
     984        1552 :         m_nBlocksPerBand > INT_MAX / l_nBands)
     985             :     {
     986           1 :         ReportError(CE_Failure, CPLE_AppDefined,
     987             :                     "Too many blocks: %d x %d x %d bands", m_nBlocksPerRow,
     988             :                     m_nBlocksPerColumn, l_nBands);
     989           1 :         return false;
     990             :     }
     991       26011 :     return true;
     992             : }
     993             : 
     994             : /************************************************************************/
     995             : /*                   SetStructuralMDFromParent()                        */
     996             : /************************************************************************/
     997             : 
     998         989 : void GTiffDataset::SetStructuralMDFromParent(GTiffDataset *poParentDS)
     999             : {
    1000         989 :     m_bBlockOrderRowMajor = poParentDS->m_bBlockOrderRowMajor;
    1001         989 :     m_bLeaderSizeAsUInt4 = poParentDS->m_bLeaderSizeAsUInt4;
    1002         989 :     m_bTrailerRepeatedLast4BytesRepeated =
    1003         989 :         poParentDS->m_bTrailerRepeatedLast4BytesRepeated;
    1004         989 :     m_bMaskInterleavedWithImagery = poParentDS->m_bMaskInterleavedWithImagery;
    1005         989 :     m_bWriteEmptyTiles = poParentDS->m_bWriteEmptyTiles;
    1006         989 : }
    1007             : 
    1008             : /************************************************************************/
    1009             : /*                          ScanDirectories()                           */
    1010             : /*                                                                      */
    1011             : /*      Scan through all the directories finding overviews, masks       */
    1012             : /*      and subdatasets.                                                */
    1013             : /************************************************************************/
    1014             : 
    1015      802779 : void GTiffDataset::ScanDirectories()
    1016             : 
    1017             : {
    1018             :     /* -------------------------------------------------------------------- */
    1019             :     /*      We only scan once.  We do not scan for non-base datasets.       */
    1020             :     /* -------------------------------------------------------------------- */
    1021      802779 :     if (!m_bScanDeferred)
    1022      796467 :         return;
    1023             : 
    1024        6597 :     m_bScanDeferred = false;
    1025             : 
    1026        6597 :     if (m_poBaseDS)
    1027         285 :         return;
    1028             : 
    1029        6312 :     Crystalize();
    1030             : 
    1031        5996 :     CPLDebug("GTiff", "ScanDirectories()");
    1032             : 
    1033             :     /* ==================================================================== */
    1034             :     /*      Scan all directories.                                           */
    1035             :     /* ==================================================================== */
    1036       11992 :     CPLStringList aosSubdatasets;
    1037        5996 :     int iDirIndex = 0;
    1038             : 
    1039        5996 :     FlushDirectory();
    1040             : 
    1041         980 :     do
    1042             :     {
    1043        6976 :         toff_t nTopDir = TIFFCurrentDirOffset(m_hTIFF);
    1044        6976 :         uint32_t nSubType = 0;
    1045             : 
    1046        6976 :         ++iDirIndex;
    1047             : 
    1048        6976 :         toff_t *tmpSubIFDOffsets = nullptr;
    1049        6976 :         toff_t *subIFDOffsets = nullptr;
    1050        6976 :         uint16_t nSubIFDs = 0;
    1051        6976 :         if (TIFFGetField(m_hTIFF, TIFFTAG_SUBIFD, &nSubIFDs,
    1052        6976 :                          &tmpSubIFDOffsets) &&
    1053             :             iDirIndex == 1)
    1054             :         {
    1055             :             subIFDOffsets =
    1056          10 :                 static_cast<toff_t *>(CPLMalloc(nSubIFDs * sizeof(toff_t)));
    1057          30 :             for (uint16_t iSubIFD = 0; iSubIFD < nSubIFDs; iSubIFD++)
    1058             :             {
    1059          20 :                 subIFDOffsets[iSubIFD] = tmpSubIFDOffsets[iSubIFD];
    1060             :             }
    1061             :         }
    1062             : 
    1063             :         // early break for backwards compatibility: if the first directory read
    1064             :         // is also the last, and there are no subIFDs, no use continuing
    1065        6976 :         if (iDirIndex == 1 && nSubIFDs == 0 && TIFFLastDirectory(m_hTIFF))
    1066             :         {
    1067        5402 :             CPLFree(subIFDOffsets);
    1068        5402 :             break;
    1069             :         }
    1070             : 
    1071        3168 :         for (uint16_t iSubIFD = 0; iSubIFD <= nSubIFDs; iSubIFD++)
    1072             :         {
    1073        1600 :             toff_t nThisDir = nTopDir;
    1074        1600 :             if (iSubIFD > 0 && iDirIndex > 1)  // don't read subIFDs if we are
    1075             :                                                // not in the original directory
    1076           6 :                 break;
    1077        1594 :             if (iSubIFD > 0)
    1078             :             {
    1079             :                 // make static analyzer happy. subIFDOffsets cannot be null if
    1080             :                 // iSubIFD>0
    1081          20 :                 assert(subIFDOffsets != nullptr);
    1082          20 :                 nThisDir = subIFDOffsets[iSubIFD - 1];
    1083             :                 // CPLDebug("GTiff", "Opened subIFD %d/%d at offset %llu.",
    1084             :                 // iSubIFD, nSubIFDs, nThisDir);
    1085          20 :                 if (!TIFFSetSubDirectory(m_hTIFF, nThisDir))
    1086           0 :                     break;
    1087             :             }
    1088             : 
    1089        1594 :             if (!TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
    1090         357 :                 nSubType = 0;
    1091             : 
    1092             :             /* Embedded overview of the main image */
    1093        1594 :             if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1094        1147 :                 (nSubType & FILETYPE_MASK) == 0 &&
    1095        1066 :                 ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1096         818 :                 m_nOverviewCount < 30 /* to avoid DoS */)
    1097             :             {
    1098         818 :                 GTiffDataset *poODS = new GTiffDataset();
    1099         818 :                 poODS->ShareLockWithParentDataset(this);
    1100         818 :                 poODS->SetStructuralMDFromParent(this);
    1101         818 :                 if (m_bHasGotSiblingFiles)
    1102         125 :                     poODS->oOvManager.TransferSiblingFiles(
    1103             :                         CSLDuplicate(GetSiblingFiles()));
    1104         818 :                 poODS->m_pszFilename = CPLStrdup(m_pszFilename);
    1105         818 :                 poODS->m_nColorTableMultiplier = m_nColorTableMultiplier;
    1106         818 :                 if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1107        1636 :                                       eAccess) != CE_None ||
    1108         818 :                     poODS->GetRasterCount() != GetRasterCount())
    1109             :                 {
    1110           0 :                     delete poODS;
    1111             :                 }
    1112             :                 else
    1113             :                 {
    1114         818 :                     CPLDebug("GTiff", "Opened %dx%d overview.",
    1115             :                              poODS->GetRasterXSize(), poODS->GetRasterYSize());
    1116         818 :                     ++m_nOverviewCount;
    1117        1636 :                     m_papoOverviewDS = static_cast<GTiffDataset **>(CPLRealloc(
    1118         818 :                         m_papoOverviewDS, m_nOverviewCount * (sizeof(void *))));
    1119         818 :                     m_papoOverviewDS[m_nOverviewCount - 1] = poODS;
    1120         818 :                     poODS->m_poBaseDS = this;
    1121         818 :                     poODS->m_bIsOverview = true;
    1122             : 
    1123             :                     // Propagate a few compression related settings that are
    1124             :                     // no preserved at the TIFF tag level, but may be set in
    1125             :                     // the GDAL_METADATA tag in the IMAGE_STRUCTURE domain
    1126             :                     // Note: this might not be totally reflecting the reality
    1127             :                     // if users have created overviews with different settings
    1128             :                     // but this is probably better than the default ones
    1129         818 :                     poODS->m_nWebPLevel = m_nWebPLevel;
    1130             :                     // below is not a copy & paste error: we transfer the
    1131             :                     // m_dfMaxZErrorOverview overview of the parent to
    1132             :                     // m_dfMaxZError of the overview
    1133         818 :                     poODS->m_dfMaxZError = m_dfMaxZErrorOverview;
    1134         818 :                     poODS->m_dfMaxZErrorOverview = m_dfMaxZErrorOverview;
    1135             : #if HAVE_JXL
    1136         818 :                     poODS->m_bJXLLossless = m_bJXLLossless;
    1137         818 :                     poODS->m_fJXLDistance = m_fJXLDistance;
    1138         818 :                     poODS->m_fJXLAlphaDistance = m_fJXLAlphaDistance;
    1139         818 :                     poODS->m_nJXLEffort = m_nJXLEffort;
    1140             : #endif
    1141             :                     // Those ones are not serialized currently..
    1142             :                     // poODS->m_nZLevel = m_nZLevel;
    1143             :                     // poODS->m_nLZMAPreset = m_nLZMAPreset;
    1144             :                     // poODS->m_nZSTDLevel = m_nZSTDLevel;
    1145         818 :                 }
    1146             :             }
    1147             :             // Embedded mask of the main image.
    1148         776 :             else if ((nSubType & FILETYPE_MASK) != 0 &&
    1149         171 :                      (nSubType & FILETYPE_REDUCEDIMAGE) == 0 &&
    1150          90 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1151          90 :                      m_poMaskDS == nullptr)
    1152             :             {
    1153          90 :                 m_poMaskDS = new GTiffDataset();
    1154          90 :                 m_poMaskDS->ShareLockWithParentDataset(this);
    1155          90 :                 m_poMaskDS->SetStructuralMDFromParent(this);
    1156          90 :                 m_poMaskDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1157             : 
    1158             :                 // The TIFF6 specification - page 37 - only allows 1
    1159             :                 // SamplesPerPixel and 1 BitsPerSample Here we support either 1
    1160             :                 // or 8 bit per sample and we support either 1 sample per pixel
    1161             :                 // or as many samples as in the main image We don't check the
    1162             :                 // value of the PhotometricInterpretation tag, which should be
    1163             :                 // set to "Transparency mask" (4) according to the specification
    1164             :                 // (page 36).  However, the TIFF6 specification allows image
    1165             :                 // masks to have a higher resolution than the main image, what
    1166             :                 // we don't support here.
    1167             : 
    1168          90 :                 if (m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1169          90 :                                            eAccess) != CE_None ||
    1170          90 :                     m_poMaskDS->GetRasterCount() == 0 ||
    1171          90 :                     !(m_poMaskDS->GetRasterCount() == 1 ||
    1172           3 :                       m_poMaskDS->GetRasterCount() == GetRasterCount()) ||
    1173          90 :                     m_poMaskDS->GetRasterXSize() != GetRasterXSize() ||
    1174         270 :                     m_poMaskDS->GetRasterYSize() != GetRasterYSize() ||
    1175          90 :                     m_poMaskDS->GetRasterBand(1)->GetRasterDataType() !=
    1176             :                         GDT_Byte)
    1177             :                 {
    1178           0 :                     delete m_poMaskDS;
    1179           0 :                     m_poMaskDS = nullptr;
    1180             :                 }
    1181             :                 else
    1182             :                 {
    1183          90 :                     CPLDebug("GTiff", "Opened band mask.");
    1184          90 :                     m_poMaskDS->m_poBaseDS = this;
    1185          90 :                     m_poMaskDS->m_poImageryDS = this;
    1186             : 
    1187         180 :                     m_poMaskDS->m_bPromoteTo8Bits =
    1188          90 :                         CPLTestBool(CPLGetConfigOption(
    1189             :                             "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1190             :                 }
    1191             :             }
    1192             : 
    1193             :             // Embedded mask of an overview.  The TIFF6 specification allows the
    1194             :             // combination of the FILETYPE_xxxx masks.
    1195         686 :             else if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1196         329 :                      (nSubType & FILETYPE_MASK) != 0 &&
    1197          81 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0))
    1198             :             {
    1199          81 :                 GTiffDataset *poDS = new GTiffDataset();
    1200          81 :                 poDS->ShareLockWithParentDataset(this);
    1201          81 :                 poDS->SetStructuralMDFromParent(this);
    1202          81 :                 poDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1203          81 :                 if (poDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1204          81 :                                      eAccess) != CE_None ||
    1205         162 :                     poDS->GetRasterCount() == 0 ||
    1206          81 :                     poDS->GetRasterBand(1)->GetRasterDataType() != GDT_Byte)
    1207             :                 {
    1208           0 :                     delete poDS;
    1209             :                 }
    1210             :                 else
    1211             :                 {
    1212          81 :                     int i = 0;  // Used after for.
    1213         121 :                     for (; i < m_nOverviewCount; ++i)
    1214             :                     {
    1215         121 :                         auto poOvrDS = cpl::down_cast<GTiffDataset *>(
    1216         121 :                             GDALDataset::FromHandle(m_papoOverviewDS[i]));
    1217         323 :                         if (poOvrDS->m_poMaskDS == nullptr &&
    1218          81 :                             poDS->GetRasterXSize() ==
    1219          81 :                                 m_papoOverviewDS[i]->GetRasterXSize() &&
    1220          81 :                             poDS->GetRasterYSize() ==
    1221         283 :                                 m_papoOverviewDS[i]->GetRasterYSize() &&
    1222          81 :                             (poDS->GetRasterCount() == 1 ||
    1223           0 :                              poDS->GetRasterCount() == GetRasterCount()))
    1224             :                         {
    1225          81 :                             CPLDebug(
    1226             :                                 "GTiff", "Opened band mask for %dx%d overview.",
    1227             :                                 poDS->GetRasterXSize(), poDS->GetRasterYSize());
    1228          81 :                             poDS->m_poImageryDS = poOvrDS;
    1229          81 :                             poOvrDS->m_poMaskDS = poDS;
    1230          81 :                             poDS->m_bPromoteTo8Bits =
    1231          81 :                                 CPLTestBool(CPLGetConfigOption(
    1232             :                                     "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1233          81 :                             poDS->m_poBaseDS = this;
    1234          81 :                             break;
    1235             :                         }
    1236             :                     }
    1237          81 :                     if (i == m_nOverviewCount)
    1238             :                     {
    1239           0 :                         delete poDS;
    1240             :                     }
    1241          81 :                 }
    1242             :             }
    1243         605 :             else if (!m_bSingleIFDOpened &&
    1244         601 :                      (nSubType == 0 || nSubType == FILETYPE_PAGE))
    1245             :             {
    1246         353 :                 uint32_t nXSize = 0;
    1247         353 :                 uint32_t nYSize = 0;
    1248             : 
    1249         353 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
    1250         353 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
    1251             : 
    1252             :                 // For Geodetic TIFF grids (GTG)
    1253             :                 // (https://proj.org/specifications/geodetictiffgrids.html)
    1254             :                 // extract the grid_name to put it in the description
    1255         706 :                 std::string osFriendlyName;
    1256         353 :                 char *pszText = nullptr;
    1257         408 :                 if (TIFFGetField(m_hTIFF, TIFFTAG_GDAL_METADATA, &pszText) &&
    1258          55 :                     strstr(pszText, "grid_name") != nullptr)
    1259             :                 {
    1260           4 :                     CPLXMLNode *psRoot = CPLParseXMLString(pszText);
    1261             :                     const CPLXMLNode *psItem =
    1262           4 :                         psRoot ? CPLGetXMLNode(psRoot, "=GDALMetadata")
    1263           4 :                                : nullptr;
    1264           4 :                     if (psItem)
    1265           4 :                         psItem = psItem->psChild;
    1266           4 :                     for (; psItem != nullptr; psItem = psItem->psNext)
    1267             :                     {
    1268             : 
    1269           4 :                         if (psItem->eType != CXT_Element ||
    1270           4 :                             !EQUAL(psItem->pszValue, "Item"))
    1271           0 :                             continue;
    1272             : 
    1273             :                         const char *pszKey =
    1274           4 :                             CPLGetXMLValue(psItem, "name", nullptr);
    1275             :                         const char *pszValue =
    1276           4 :                             CPLGetXMLValue(psItem, nullptr, nullptr);
    1277             :                         int nBand =
    1278           4 :                             atoi(CPLGetXMLValue(psItem, "sample", "-1"));
    1279           4 :                         if (pszKey && pszValue && nBand <= 0 &&
    1280           4 :                             EQUAL(pszKey, "grid_name"))
    1281             :                         {
    1282           4 :                             osFriendlyName = ": ";
    1283           4 :                             osFriendlyName += pszValue;
    1284           4 :                             break;
    1285             :                         }
    1286             :                     }
    1287             : 
    1288           4 :                     CPLDestroyXMLNode(psRoot);
    1289             :                 }
    1290             : 
    1291         353 :                 if (nXSize > INT_MAX || nYSize > INT_MAX)
    1292             :                 {
    1293           1 :                     CPLDebug("GTiff",
    1294             :                              "Skipping directory with too large image: %u x %u",
    1295             :                              nXSize, nYSize);
    1296             :                 }
    1297             :                 else
    1298             :                 {
    1299         352 :                     uint16_t nSPP = 0;
    1300         352 :                     if (!TIFFGetField(m_hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSPP))
    1301           0 :                         nSPP = 1;
    1302             : 
    1303         704 :                     CPLString osName, osDesc;
    1304             :                     osName.Printf("SUBDATASET_%d_NAME=GTIFF_DIR:%d:%s",
    1305         352 :                                   iDirIndex, iDirIndex, m_pszFilename);
    1306             :                     osDesc.Printf(
    1307             :                         "SUBDATASET_%d_DESC=Page %d (%dP x %dL x %dB)",
    1308             :                         iDirIndex, iDirIndex, static_cast<int>(nXSize),
    1309         352 :                         static_cast<int>(nYSize), nSPP);
    1310         352 :                     osDesc += osFriendlyName;
    1311             : 
    1312         352 :                     aosSubdatasets.AddString(osName);
    1313         352 :                     aosSubdatasets.AddString(osDesc);
    1314             :                 }
    1315             :             }
    1316             :         }
    1317        1574 :         CPLFree(subIFDOffsets);
    1318             : 
    1319             :         // Make sure we are stepping from the expected directory regardless
    1320             :         // of churn done processing the above.
    1321        1574 :         if (TIFFCurrentDirOffset(m_hTIFF) != nTopDir)
    1322          10 :             TIFFSetSubDirectory(m_hTIFF, nTopDir);
    1323        2554 :     } while (!m_bSingleIFDOpened && !TIFFLastDirectory(m_hTIFF) &&
    1324         980 :              TIFFReadDirectory(m_hTIFF) != 0);
    1325             : 
    1326        5996 :     ReloadDirectory();
    1327             : 
    1328             :     // If we have a mask for the main image, loop over the overviews, and if
    1329             :     // they have a mask, let's set this mask as an overview of the main mask.
    1330        5996 :     if (m_poMaskDS != nullptr)
    1331             :     {
    1332         171 :         for (int i = 0; i < m_nOverviewCount; ++i)
    1333             :         {
    1334          81 :             if (cpl::down_cast<GTiffDataset *>(
    1335          81 :                     GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1336          81 :                     ->m_poMaskDS != nullptr)
    1337             :             {
    1338          81 :                 ++m_poMaskDS->m_nOverviewCount;
    1339         162 :                 m_poMaskDS->m_papoOverviewDS =
    1340         162 :                     static_cast<GTiffDataset **>(CPLRealloc(
    1341          81 :                         m_poMaskDS->m_papoOverviewDS,
    1342          81 :                         m_poMaskDS->m_nOverviewCount * (sizeof(void *))));
    1343          81 :                 m_poMaskDS->m_papoOverviewDS[m_poMaskDS->m_nOverviewCount - 1] =
    1344          81 :                     cpl::down_cast<GTiffDataset *>(
    1345          81 :                         GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1346          81 :                         ->m_poMaskDS;
    1347             :             }
    1348             :         }
    1349             :     }
    1350             : 
    1351             :     // Assign color interpretation from main dataset
    1352        5996 :     const int l_nBands = GetRasterCount();
    1353        6814 :     for (int iOvr = 0; iOvr < m_nOverviewCount; ++iOvr)
    1354             :     {
    1355        2278 :         for (int i = 1; i <= l_nBands; i++)
    1356             :         {
    1357           0 :             auto poBand = dynamic_cast<GTiffRasterBand *>(
    1358        1460 :                 m_papoOverviewDS[iOvr]->GetRasterBand(i));
    1359        1460 :             if (poBand)
    1360        1460 :                 poBand->m_eBandInterp =
    1361        1460 :                     GetRasterBand(i)->GetColorInterpretation();
    1362             :         }
    1363             :     }
    1364             : 
    1365             :     /* -------------------------------------------------------------------- */
    1366             :     /*      Only keep track of subdatasets if we have more than one         */
    1367             :     /*      subdataset (pair).                                              */
    1368             :     /* -------------------------------------------------------------------- */
    1369        5996 :     if (aosSubdatasets.size() > 2)
    1370             :     {
    1371           8 :         m_oGTiffMDMD.SetMetadata(aosSubdatasets.List(), "SUBDATASETS");
    1372             :     }
    1373             : }
    1374             : 
    1375             : /************************************************************************/
    1376             : /*                         GetInternalHandle()                          */
    1377             : /************************************************************************/
    1378             : 
    1379        2072 : void *GTiffDataset::GetInternalHandle(const char * /* pszHandleName */)
    1380             : 
    1381             : {
    1382        2072 :     return m_hTIFF;
    1383             : }
    1384             : 
    1385             : /************************************************************************/
    1386             : /*                            GetFileList()                             */
    1387             : /************************************************************************/
    1388             : 
    1389        2415 : char **GTiffDataset::GetFileList()
    1390             : 
    1391             : {
    1392        2415 :     LoadGeoreferencingAndPamIfNeeded();
    1393             : 
    1394        2415 :     char **papszFileList = GDALPamDataset::GetFileList();
    1395             : 
    1396        2415 :     LoadMetadata();
    1397        2415 :     if (nullptr != m_papszMetadataFiles)
    1398             :     {
    1399          77 :         for (int i = 0; m_papszMetadataFiles[i] != nullptr; ++i)
    1400             :         {
    1401          44 :             if (CSLFindString(papszFileList, m_papszMetadataFiles[i]) < 0)
    1402             :             {
    1403             :                 papszFileList =
    1404          44 :                     CSLAddString(papszFileList, m_papszMetadataFiles[i]);
    1405             :             }
    1406             :         }
    1407             :     }
    1408             : 
    1409        2421 :     if (m_pszGeorefFilename &&
    1410           6 :         CSLFindString(papszFileList, m_pszGeorefFilename) == -1)
    1411             :     {
    1412           6 :         papszFileList = CSLAddString(papszFileList, m_pszGeorefFilename);
    1413             :     }
    1414             : 
    1415        2415 :     if (m_nXMLGeorefSrcIndex >= 0)
    1416        2415 :         LookForProjection();
    1417             : 
    1418        2416 :     if (m_pszXMLFilename &&
    1419           1 :         CSLFindString(papszFileList, m_pszXMLFilename) == -1)
    1420             :     {
    1421           1 :         papszFileList = CSLAddString(papszFileList, m_pszXMLFilename);
    1422             :     }
    1423             : 
    1424        2415 :     return papszFileList;
    1425             : }
    1426             : 
    1427             : /************************************************************************/
    1428             : /*                        GetRawBinaryLayout()                          */
    1429             : /************************************************************************/
    1430             : 
    1431           9 : bool GTiffDataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
    1432             : {
    1433           9 :     if (eAccess == GA_Update)
    1434             :     {
    1435           3 :         FlushCache(false);
    1436           3 :         Crystalize();
    1437             :     }
    1438             : 
    1439           9 :     if (m_nCompression != COMPRESSION_NONE)
    1440           1 :         return false;
    1441           8 :     if (!CPLIsPowerOfTwo(m_nBitsPerSample) || m_nBitsPerSample < 8)
    1442           0 :         return false;
    1443           8 :     const auto eDT = GetRasterBand(1)->GetRasterDataType();
    1444           8 :     if (GDALDataTypeIsComplex(eDT))
    1445           0 :         return false;
    1446             : 
    1447           8 :     toff_t *panByteCounts = nullptr;
    1448           8 :     toff_t *panOffsets = nullptr;
    1449           8 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
    1450             : 
    1451          16 :     if (!((bIsTiled &&
    1452           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
    1453           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets)) ||
    1454           5 :           (!bIsTiled &&
    1455           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
    1456           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
    1457             :     {
    1458           0 :         return false;
    1459             :     }
    1460             : 
    1461           8 :     const int nDTSize = GDALGetDataTypeSizeBytes(eDT);
    1462           8 :     vsi_l_offset nImgOffset = panOffsets[0];
    1463          16 :     GIntBig nPixelOffset = (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1464           8 :                                ? static_cast<GIntBig>(nDTSize) * nBands
    1465             :                                : nDTSize;
    1466           8 :     GIntBig nLineOffset = nPixelOffset * nRasterXSize;
    1467           8 :     GIntBig nBandOffset =
    1468           8 :         (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1) ? nDTSize : 0;
    1469           8 :     RawBinaryLayout::Interleaving eInterleaving =
    1470          12 :         (nBands == 1) ? RawBinaryLayout::Interleaving::UNKNOWN
    1471           4 :         : (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1472           4 :             ? RawBinaryLayout::Interleaving::BIP
    1473             :             : RawBinaryLayout::Interleaving::BSQ;
    1474           8 :     if (bIsTiled)
    1475             :     {
    1476             :         // Only a single block tiled file with same dimension as the raster
    1477             :         // might be acceptable
    1478           3 :         if (m_nBlockXSize != nRasterXSize || m_nBlockYSize != nRasterYSize)
    1479           1 :             return false;
    1480           2 :         if (nBands > 1 && m_nPlanarConfig != PLANARCONFIG_CONTIG)
    1481             :         {
    1482           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[1]) -
    1483           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1484           2 :             for (int i = 2; i < nBands; i++)
    1485             :             {
    1486           1 :                 if (static_cast<GIntBig>(panOffsets[i]) -
    1487           1 :                         static_cast<GIntBig>(panOffsets[i - 1]) !=
    1488             :                     nBandOffset)
    1489           0 :                     return false;
    1490             :             }
    1491             :         }
    1492             :     }
    1493             :     else
    1494             :     {
    1495           5 :         const int nStrips = DIV_ROUND_UP(nRasterYSize, m_nRowsPerStrip);
    1496           5 :         if (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1497             :         {
    1498           4 :             vsi_l_offset nLastStripEnd = panOffsets[0] + panByteCounts[0];
    1499          16 :             for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1500             :             {
    1501          12 :                 if (nLastStripEnd != panOffsets[iStrip])
    1502           0 :                     return false;
    1503          12 :                 nLastStripEnd = panOffsets[iStrip] + panByteCounts[iStrip];
    1504           4 :             }
    1505             :         }
    1506             :         else
    1507             :         {
    1508             :             // Note: we could potentially have BIL order with m_nRowsPerStrip ==
    1509             :             // 1 and if strips are ordered strip_line_1_band_1, ...,
    1510             :             // strip_line_1_band_N, strip_line2_band1, ... strip_line2_band_N,
    1511             :             // etc.... but that'd be faily exotic ! So only detect BSQ layout
    1512             :             // here
    1513           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[nStrips]) -
    1514           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1515           4 :             for (int i = 0; i < nBands; i++)
    1516             :             {
    1517           3 :                 uint32_t iStripOffset = nStrips * i;
    1518           3 :                 vsi_l_offset nLastStripEnd =
    1519           3 :                     panOffsets[iStripOffset] + panByteCounts[iStripOffset];
    1520           3 :                 for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1521             :                 {
    1522           0 :                     if (nLastStripEnd != panOffsets[iStripOffset + iStrip])
    1523           0 :                         return false;
    1524           0 :                     nLastStripEnd = panOffsets[iStripOffset + iStrip] +
    1525           0 :                                     panByteCounts[iStripOffset + iStrip];
    1526             :                 }
    1527           3 :                 if (i >= 2 && static_cast<GIntBig>(panOffsets[iStripOffset]) -
    1528           1 :                                       static_cast<GIntBig>(
    1529           1 :                                           panOffsets[iStripOffset - nStrips]) !=
    1530             :                                   nBandOffset)
    1531             :                 {
    1532           0 :                     return false;
    1533             :                 }
    1534             :             }
    1535             :         }
    1536             :     }
    1537             : 
    1538           7 :     sLayout.osRawFilename = m_pszFilename;
    1539           7 :     sLayout.eInterleaving = eInterleaving;
    1540           7 :     sLayout.eDataType = eDT;
    1541             : #ifdef CPL_LSB
    1542           7 :     sLayout.bLittleEndianOrder = !TIFFIsByteSwapped(m_hTIFF);
    1543             : #else
    1544             :     sLayout.bLittleEndianOrder = TIFFIsByteSwapped(m_hTIFF);
    1545             : #endif
    1546           7 :     sLayout.nImageOffset = nImgOffset;
    1547           7 :     sLayout.nPixelOffset = nPixelOffset;
    1548           7 :     sLayout.nLineOffset = nLineOffset;
    1549           7 :     sLayout.nBandOffset = nBandOffset;
    1550             : 
    1551           7 :     return true;
    1552             : }
    1553             : 
    1554             : /************************************************************************/
    1555             : /*               GTiffDatasetLibGeotiffErrorCallback()                  */
    1556             : /************************************************************************/
    1557             : 
    1558           0 : static void GTiffDatasetLibGeotiffErrorCallback(GTIF *, int level,
    1559             :                                                 const char *pszMsg, ...)
    1560             : {
    1561             :     va_list ap;
    1562           0 :     va_start(ap, pszMsg);
    1563           0 :     CPLErrorV((level == LIBGEOTIFF_WARNING) ? CE_Warning : CE_Failure,
    1564             :               CPLE_AppDefined, pszMsg, ap);
    1565           0 :     va_end(ap);
    1566           0 : }
    1567             : 
    1568             : /************************************************************************/
    1569             : /*                           GTIFNew()                                  */
    1570             : /************************************************************************/
    1571             : 
    1572       25686 : /* static */ GTIF *GTiffDataset::GTIFNew(TIFF *hTIFF)
    1573             : {
    1574       25686 :     GTIF *gtif = GTIFNewEx(hTIFF, GTiffDatasetLibGeotiffErrorCallback, nullptr);
    1575       25686 :     if (gtif)
    1576             :     {
    1577       25686 :         GTIFAttachPROJContext(gtif, OSRGetProjTLSContext());
    1578             :     }
    1579       25686 :     return gtif;
    1580             : }

Generated by: LCOV version 1.14