LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 684 733 93.3 %
Date: 2025-01-18 12:42:00 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       25458 : const GTIFFTag *GTiffDataset::GetTIFFTags()
      63             : {
      64       25458 :     return asTIFFTags;
      65             : }
      66             : 
      67             : /************************************************************************/
      68             : /*                            GTiffDataset()                            */
      69             : /************************************************************************/
      70             : 
      71       26579 : 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       26585 :           CPLTestBool(CPLGetConfigOption("GTIFF_DONT_WRITE_BLOCKS", "NO"))),
      91             :       m_bIsFinalized(false),
      92             :       m_bIgnoreReadErrors(
      93       26582 :           CPLTestBool(CPLGetConfigOption("GTIFF_IGNORE_READ_ERRORS", "NO"))),
      94       26585 :       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       79742 :       m_bWriteCOGLayout(false)
     103             : {
     104             :     // CPLDebug("GDAL", "sizeof(GTiffDataset) = %d bytes", static_cast<int>(
     105             :     //     sizeof(GTiffDataset)));
     106             : 
     107             :     const char *pszVirtualMemIO =
     108       26584 :         CPLGetConfigOption("GTIFF_VIRTUAL_MEM_IO", "NO");
     109       26585 :     if (EQUAL(pszVirtualMemIO, "IF_ENOUGH_RAM"))
     110           0 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::IF_ENOUGH_RAM;
     111       26585 :     else if (CPLTestBool(pszVirtualMemIO))
     112          41 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::YES;
     113             : 
     114       26582 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     115       26493 : }
     116             : 
     117             : /************************************************************************/
     118             : /*                           ~GTiffDataset()                            */
     119             : /************************************************************************/
     120             : 
     121       53156 : GTiffDataset::~GTiffDataset()
     122             : 
     123             : {
     124       26578 :     GTiffDataset::Close();
     125       53156 : }
     126             : 
     127             : /************************************************************************/
     128             : /*                              Close()                                 */
     129             : /************************************************************************/
     130             : 
     131       47278 : CPLErr GTiffDataset::Close()
     132             : {
     133       47278 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     134             :     {
     135       26583 :         auto [eErr, bDroppedRef] = Finalize();
     136             : 
     137       26577 :         if (m_pszTmpFilename)
     138             :         {
     139           4 :             VSIUnlink(m_pszTmpFilename);
     140           4 :             CPLFree(m_pszTmpFilename);
     141             :         }
     142             : 
     143       26577 :         if (GDALPamDataset::Close() != CE_None)
     144           0 :             eErr = CE_Failure;
     145       26577 :         return eErr;
     146             :     }
     147       20695 :     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       26642 : std::tuple<CPLErr, bool> GTiffDataset::Finalize()
     157             : {
     158       26642 :     bool bDroppedRef = false;
     159       26642 :     if (m_bIsFinalized)
     160         118 :         return std::tuple(CE_None, bDroppedRef);
     161             : 
     162       26583 :     CPLErr eErr = CE_None;
     163       26583 :     Crystalize();
     164             : 
     165       26582 :     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       26582 :     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       26583 :     if (m_psVirtualMemIOMapping)
     184          11 :         CPLVirtualMemFree(m_psVirtualMemIOMapping);
     185       26583 :     m_psVirtualMemIOMapping = nullptr;
     186             : 
     187             :     /* -------------------------------------------------------------------- */
     188             :     /*      Fill in missing blocks with empty data.                         */
     189             :     /* -------------------------------------------------------------------- */
     190       26583 :     if (m_bFillEmptyTilesAtClosing)
     191             :     {
     192             :         /* --------------------------------------------------------------------
     193             :          */
     194             :         /*  Ensure any blocks write cached by GDAL gets pushed through libtiff.
     195             :          */
     196             :         /* --------------------------------------------------------------------
     197             :          */
     198        5257 :         if (FlushCacheInternal(true, /* at closing */
     199        5257 :                                false /* do not call FlushDirectory */) !=
     200             :             CE_None)
     201             :         {
     202           0 :             eErr = CE_Failure;
     203             :         }
     204             : 
     205        5257 :         if (FillEmptyTiles() != CE_None)
     206             :         {
     207           9 :             eErr = CE_Failure;
     208             :         }
     209        5257 :         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       26583 :     if (FlushCacheInternal(true /* at closing */, true) != CE_None)
     217             :     {
     218           7 :         eErr = CE_Failure;
     219             :     }
     220             : 
     221             :     // Destroy compression queue
     222       26583 :     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       26582 :     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       26582 :     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       24942 :         const int nOldOverviewCount = m_nOverviewCount;
     258       24942 :         m_nOverviewCount = 0;
     259       26273 :         for (int i = 0; i < nOldOverviewCount; ++i)
     260             :         {
     261        1331 :             delete m_papoOverviewDS[i];
     262        1331 :             bDroppedRef = true;
     263             :         }
     264             : 
     265       25002 :         for (int i = 0; i < m_nJPEGOverviewCountOri; ++i)
     266             :         {
     267          60 :             delete m_papoJPEGOverviewDS[i];
     268          60 :             bDroppedRef = true;
     269             :         }
     270       24942 :         m_nJPEGOverviewCount = 0;
     271       24942 :         m_nJPEGOverviewCountOri = 0;
     272       24942 :         CPLFree(m_papoJPEGOverviewDS);
     273       24941 :         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       26581 :     CPLFree(m_papoOverviewDS);
     279       26582 :     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       26582 :     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         306 :         auto poMaskDS = m_poMaskDS;
     290         306 :         m_poMaskDS = nullptr;
     291         306 :         delete poMaskDS;
     292         306 :         bDroppedRef = true;
     293             :     }
     294             : 
     295       26582 :     m_poColorTable.reset();
     296             : 
     297       26581 :     if (m_hTIFF)
     298             :     {
     299       26580 :         XTIFFClose(m_hTIFF);
     300       26582 :         m_hTIFF = nullptr;
     301             :     }
     302             : 
     303       26583 :     if (!m_poBaseDS)
     304             :     {
     305       24943 :         if (m_fpL != nullptr)
     306             :         {
     307       24943 :             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       24943 :             if (VSIFCloseL(m_fpL) != 0)
     332             :             {
     333           0 :                 eErr = CE_Failure;
     334           0 :                 ReportError(CE_Failure, CPLE_FileIO, "I/O error");
     335             :             }
     336       24943 :             m_fpL = nullptr;
     337             :         }
     338             :     }
     339             : 
     340       26583 :     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       26583 :     m_aoGCPs.clear();
     351             : 
     352       26578 :     CSLDestroy(m_papszCreationOptions);
     353       26580 :     m_papszCreationOptions = nullptr;
     354             : 
     355       26580 :     CPLFree(m_pabyTempWriteBuffer);
     356       26580 :     m_pabyTempWriteBuffer = nullptr;
     357             : 
     358       26580 :     m_bIMDRPCMetadataLoaded = false;
     359       26580 :     CSLDestroy(m_papszMetadataFiles);
     360       26579 :     m_papszMetadataFiles = nullptr;
     361             : 
     362       26579 :     VSIFree(m_pTempBufferForCommonDirectIO);
     363       26580 :     m_pTempBufferForCommonDirectIO = nullptr;
     364             : 
     365       26580 :     CPLFree(m_panMaskOffsetLsb);
     366       26579 :     m_panMaskOffsetLsb = nullptr;
     367             : 
     368       26579 :     CPLFree(m_pszVertUnit);
     369       26580 :     m_pszVertUnit = nullptr;
     370             : 
     371       26580 :     CPLFree(m_pszFilename);
     372       26582 :     m_pszFilename = nullptr;
     373             : 
     374       26582 :     CPLFree(m_pszGeorefFilename);
     375       26582 :     m_pszGeorefFilename = nullptr;
     376             : 
     377       26582 :     CPLFree(m_pszXMLFilename);
     378       26583 :     m_pszXMLFilename = nullptr;
     379             : 
     380       26583 :     m_bIsFinalized = true;
     381             : 
     382       26583 :     return std::tuple(eErr, bDroppedRef);
     383             : }
     384             : 
     385             : /************************************************************************/
     386             : /*                        CloseDependentDatasets()                      */
     387             : /************************************************************************/
     388             : 
     389          59 : int GTiffDataset::CloseDependentDatasets()
     390             : {
     391          59 :     if (m_poBaseDS)
     392           0 :         return FALSE;
     393             : 
     394          59 :     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          59 :     auto [eErr, bHasDroppedRefInFinalize] = Finalize();
     399          59 :     if (bHasDroppedRefInFinalize)
     400           1 :         bHasDroppedRef = true;
     401             : 
     402          59 :     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      434865 : 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      434865 :     if (nBufXSize < nXSize && nBufYSize < nYSize)
     442             :     {
     443      157851 :         int bTried = FALSE;
     444      157851 :         if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     445      157699 :             ++m_nJPEGOverviewVisibilityCounter;
     446      157851 :         const CPLErr eErr = TryOverviewRasterIO(
     447             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
     448             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
     449             :             nBandSpace, psExtraArg, &bTried);
     450      157851 :         if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     451      157699 :             --m_nJPEGOverviewVisibilityCounter;
     452      157851 :         if (bTried)
     453          22 :             return eErr;
     454             :     }
     455             : 
     456      434843 :     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      434235 :     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      433821 :     bool bCanUseMultiThreadedRead = false;
     476      433821 :     if (m_nDisableMultiThreadedRead == 0 && m_poThreadPool &&
     477      867787 :         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      433821 :     void *pBufferedData = nullptr;
     496      433821 :     const auto poFirstBand = cpl::down_cast<GTiffRasterBand *>(papoBands[0]);
     497      433821 :     const auto eDataType = poFirstBand->GetRasterDataType();
     498             : 
     499       37870 :     if (eAccess == GA_ReadOnly && eRWFlag == GF_Read &&
     500       37870 :         (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG) &&
     501      471706 :         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      433809 :     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      202642 :     else if (eRWFlag == GF_Write && nBands > 1 &&
     520       28745 :              m_nPlanarConfig == PLANARCONFIG_CONTIG &&
     521             :              // Could be extended to "odd bit" case, but more work
     522       28256 :              m_nBitsPerSample == GDALGetDataTypeSize(eDataType) &&
     523       28245 :              nXSize == nBufXSize && nYSize == nBufYSize &&
     524       28243 :              nBandCount == nBands && !m_bLoadedBlockDirty &&
     525       28221 :              (nXOff % m_nBlockXSize) == 0 && (nYOff % m_nBlockYSize) == 0 &&
     526        2480 :              (nXOff + nXSize == nRasterXSize ||
     527      636349 :               (nXSize % m_nBlockXSize) == 0) &&
     528        2477 :              (nYOff + nYSize == nRasterYSize || (nYSize % m_nBlockYSize) == 0))
     529             :     {
     530        2355 :         bool bOptimOK = true;
     531        2355 :         bool bOrderedBands = true;
     532        9759 :         for (int i = 0; i < nBands; ++i)
     533             :         {
     534        7413 :             if (panBandMap[i] != i + 1)
     535             :             {
     536          14 :                 bOrderedBands = false;
     537             :             }
     538       14826 :             if (cpl::down_cast<GTiffRasterBand *>(papoBands[panBandMap[i] - 1])
     539        7413 :                     ->HasBlockCache())
     540             :             {
     541           9 :                 bOptimOK = false;
     542           9 :                 break;
     543             :             }
     544             :         }
     545        2355 :         if (bOptimOK)
     546             :         {
     547        2346 :             Crystalize();
     548             : 
     549        2346 :             if (m_bDebugDontWriteBlocks)
     550           0 :                 return CE_None;
     551             : 
     552        2346 :             const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
     553        2346 :             if (bOrderedBands && nXSize == m_nBlockXSize &&
     554        2125 :                 nYSize == m_nBlockYSize && eBufType == eDataType &&
     555        1169 :                 nBandSpace == nDTSize &&
     556          23 :                 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        2341 :             if (LoadBlockBuf(/* nBlockId = */ -1,
     571        2341 :                              /* 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        2341 :             const int nYBlockStart = nYOff / m_nBlockYSize;
     582        2341 :             const int nYBlockEnd = 1 + (nYOff + nYSize - 1) / m_nBlockYSize;
     583        2341 :             const int nXBlockStart = nXOff / m_nBlockXSize;
     584        2341 :             const int nXBlockEnd = 1 + (nXOff + nXSize - 1) / m_nBlockXSize;
     585       32440 :             for (int nYBlock = nYBlockStart; nYBlock < nYBlockEnd; ++nYBlock)
     586             :             {
     587             :                 const int nValidY = std::min(
     588       30103 :                     m_nBlockYSize, nRasterYSize - nYBlock * m_nBlockYSize);
     589       62959 :                 for (int nXBlock = nXBlockStart; nXBlock < nXBlockEnd;
     590             :                      ++nXBlock)
     591             :                 {
     592             :                     const int nValidX = std::min(
     593       32860 :                         m_nBlockXSize, nRasterXSize - nXBlock * m_nBlockXSize);
     594       32860 :                     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        1248 :                         memset(m_pabyBlockBuf, 0,
     599        1248 :                                static_cast<size_t>(m_nBlockXSize) *
     600        1248 :                                    m_nBlockYSize * nBands * nDTSize);
     601             :                     }
     602       32860 :                     const auto nBufDTSize = GDALGetDataTypeSizeBytes(eBufType);
     603       32860 :                     const GByte *pabySrcData =
     604             :                         static_cast<const GByte *>(pData) +
     605       32860 :                         static_cast<size_t>(nYBlock - nYBlockStart) *
     606       32860 :                             m_nBlockYSize * nLineSpace +
     607       32860 :                         static_cast<size_t>(nXBlock - nXBlockStart) *
     608       32860 :                             m_nBlockXSize * nPixelSpace;
     609       32860 :                     if (bOrderedBands && nBandSpace == nBufDTSize &&
     610          24 :                         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      134089 :                         for (int iBand = 0; iBand < nBands; ++iBand)
     630             :                         {
     631     4222720 :                             for (int iY = 0; iY < nValidY; ++iY)
     632             :                             {
     633     4121490 :                                 GDALCopyWords64(
     634     4121490 :                                     pabySrcData +
     635     4121490 :                                         static_cast<size_t>(iY) * nLineSpace,
     636             :                                     eBufType, static_cast<int>(nPixelSpace),
     637     4121490 :                                     m_pabyBlockBuf +
     638     4121490 :                                         (panBandMap[iBand] - 1 +
     639     4121490 :                                          static_cast<size_t>(iY) *
     640     4121490 :                                              m_nBlockXSize * nBands) *
     641     4121490 :                                             nDTSize,
     642     4121490 :                                     eDataType, nDTSize * nBands, nValidX);
     643             :                             }
     644      101230 :                             pabySrcData += nBandSpace;
     645             :                         }
     646             :                     }
     647             : 
     648             :                     const int nBlockId =
     649       32860 :                         poFirstBand->ComputeBlockId(nXBlock, nYBlock);
     650       65720 :                     if (WriteEncodedTileOrStrip(
     651       32860 :                             nBlockId, m_pabyBlockBuf,
     652       32860 :                             /* bPreserveDataBuffer= */ false) != CE_None)
     653             :                     {
     654           4 :                         return CE_Failure;
     655             :                     }
     656             :                 }
     657             :             }
     658        2337 :             return CE_None;
     659             :         }
     660             :     }
     661             : 
     662      431333 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     663      431173 :         ++m_nJPEGOverviewVisibilityCounter;
     664      431333 :     const CPLErr eErr = GDALPamDataset::IRasterIO(
     665             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
     666             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
     667             :         psExtraArg);
     668      431333 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     669      431173 :         m_nJPEGOverviewVisibilityCounter--;
     670             : 
     671      431333 :     if (pBufferedData)
     672             :     {
     673           6 :         VSIFree(pBufferedData);
     674           6 :         VSI_TIFFSetCachedRanges(TIFFClientdata(m_hTIFF), 0, nullptr, nullptr,
     675             :                                 nullptr);
     676             :     }
     677             : 
     678      431333 :     return eErr;
     679             : }
     680             : 
     681             : /************************************************************************/
     682             : /*                       GetGTIFFKeysFlavor()                           */
     683             : /************************************************************************/
     684             : 
     685       26244 : GTIFFKeysFlavorEnum GetGTIFFKeysFlavor(CSLConstList papszOptions)
     686             : {
     687             :     const char *pszGeoTIFFKeysFlavor =
     688       26244 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_KEYS_FLAVOR", "STANDARD");
     689       26287 :     if (EQUAL(pszGeoTIFFKeysFlavor, "ESRI_PE"))
     690           1 :         return GEOTIFF_KEYS_ESRI_PE;
     691       26286 :     return GEOTIFF_KEYS_STANDARD;
     692             : }
     693             : 
     694             : /************************************************************************/
     695             : /*                       GetGeoTIFFVersion()                            */
     696             : /************************************************************************/
     697             : 
     698       26252 : GeoTIFFVersionEnum GetGeoTIFFVersion(CSLConstList papszOptions)
     699             : {
     700             :     const char *pszVersion =
     701       26252 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_VERSION", "AUTO");
     702       26271 :     if (EQUAL(pszVersion, "1.0"))
     703           3 :         return GEOTIFF_VERSION_1_0;
     704       26268 :     if (EQUAL(pszVersion, "1.1"))
     705           5 :         return GEOTIFF_VERSION_1_1;
     706       26263 :     return GEOTIFF_VERSION_AUTO;
     707             : }
     708             : 
     709             : /************************************************************************/
     710             : /*                      InitCreationOrOpenOptions()                     */
     711             : /************************************************************************/
     712             : 
     713       24888 : void GTiffDataset::InitCreationOrOpenOptions(bool bUpdateMode,
     714             :                                              CSLConstList papszOptions)
     715             : {
     716       24888 :     InitCompressionThreads(bUpdateMode, papszOptions);
     717             : 
     718       24846 :     m_eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
     719       24809 :     m_eGeoTIFFVersion = GetGeoTIFFVersion(papszOptions);
     720       24773 : }
     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     2287830 : bool GTiffDataset::IsBlockAvailable(int nBlockId, vsi_l_offset *pnOffset,
     731             :                                     vsi_l_offset *pnSize, bool *pbErrOccurred)
     732             : 
     733             : {
     734     2287830 :     if (pbErrOccurred)
     735     2246450 :         *pbErrOccurred = false;
     736             : 
     737     2287830 :     std::pair<vsi_l_offset, vsi_l_offset> oPair;
     738     2287830 :     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     2287250 :     WaitCompletionForBlock(nBlockId);
     748             : 
     749             :     // Optimization to avoid fetching the whole Strip/TileCounts and
     750             :     // Strip/TileOffsets arrays.
     751     2287240 :     if (eAccess == GA_ReadOnly && !m_bStreamingIn)
     752             :     {
     753     2176390 :         int nErrOccurred = 0;
     754             :         auto bytecount =
     755     2176390 :             TIFFGetStrileByteCountWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     756     2176450 :         if (nErrOccurred && pbErrOccurred)
     757           0 :             *pbErrOccurred = true;
     758     2176450 :         if (pnOffset)
     759             :         {
     760     2126130 :             *pnOffset =
     761     2126050 :                 TIFFGetStrileOffsetWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     762     2126130 :             if (nErrOccurred && pbErrOccurred)
     763           2 :                 *pbErrOccurred = true;
     764             :         }
     765     2176530 :         if (pnSize)
     766       11635 :             *pnSize = bytecount;
     767     2176530 :         return bytecount != 0;
     768             :     }
     769             : 
     770      110850 :     toff_t *panByteCounts = nullptr;
     771      110850 :     toff_t *panOffsets = nullptr;
     772      110850 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
     773             : 
     774      143929 :     if ((bIsTiled &&
     775       33135 :          TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
     776       25052 :          (pnOffset == nullptr ||
     777      221588 :           TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets))) ||
     778       77659 :         (!bIsTiled &&
     779       77659 :          TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
     780       36539 :          (pnOffset == nullptr ||
     781       36539 :           TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
     782             :     {
     783      110794 :         if (panByteCounts == nullptr ||
     784       61591 :             (pnOffset != nullptr && panOffsets == nullptr))
     785             :         {
     786           0 :             if (pbErrOccurred)
     787           0 :                 *pbErrOccurred = true;
     788           0 :             return false;
     789             :         }
     790             :         const int nBlockCount =
     791      110794 :             bIsTiled ? TIFFNumberOfTiles(m_hTIFF) : TIFFNumberOfStrips(m_hTIFF);
     792      110794 :         if (nBlockId >= nBlockCount)
     793             :         {
     794           0 :             if (pbErrOccurred)
     795           0 :                 *pbErrOccurred = true;
     796           0 :             return false;
     797             :         }
     798             : 
     799      110794 :         if (pnOffset)
     800       61591 :             *pnOffset = panOffsets[nBlockId];
     801      110794 :         if (pnSize)
     802        7065 :             *pnSize = panByteCounts[nBlockId];
     803      110794 :         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        6802 : void GTiffDataset::ReloadDirectory(bool bReopenHandle)
     819             : {
     820        6802 :     bool bNeedSetInvalidDir = true;
     821        6802 :     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        6802 :     if (bNeedSetInvalidDir)
     842             :     {
     843        6793 :         TIFFSetSubDirectory(m_hTIFF, 0);
     844             :     }
     845        6802 :     CPL_IGNORE_RET_VAL(SetDirectory());
     846        6801 : }
     847             : 
     848             : /************************************************************************/
     849             : /*                            SetDirectory()                            */
     850             : /************************************************************************/
     851             : 
     852       47252 : bool GTiffDataset::SetDirectory()
     853             : 
     854             : {
     855       47252 :     Crystalize();
     856             : 
     857       47123 :     if (TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
     858             :     {
     859       38708 :         return true;
     860             :     }
     861             : 
     862        8443 :     const int nSetDirResult = TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
     863        8443 :     if (!nSetDirResult)
     864           0 :         return false;
     865             : 
     866        8443 :     RestoreVolatileParameters(m_hTIFF);
     867             : 
     868        8443 :     return true;
     869             : }
     870             : 
     871             : /************************************************************************/
     872             : /*                     GTiffSetDeflateSubCodec()                        */
     873             : /************************************************************************/
     874             : 
     875        6316 : 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        6316 :     if (EQUAL(CPLGetConfigOption("GDAL_TIFF_DEFLATE_SUBCODEC", ""), "ZLIB"))
     882             :     {
     883        4097 :         TIFFSetField(hTIFF, TIFFTAG_DEFLATE_SUBCODEC, DEFLATE_SUBCODEC_ZLIB);
     884             :     }
     885             : #endif
     886        6316 : }
     887             : 
     888             : /************************************************************************/
     889             : /*                     RestoreVolatileParameters()                      */
     890             : /************************************************************************/
     891             : 
     892       40572 : 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       81567 :     if (m_nCompression == COMPRESSION_JPEG &&
     901       40855 :         m_nPhotometric == PHOTOMETRIC_YCBCR &&
     902         285 :         CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
     903             :     {
     904         285 :         int nColorMode = JPEGCOLORMODE_RAW;  // Initialize to 0;
     905             : 
     906         285 :         TIFFGetField(hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode);
     907         285 :         if (nColorMode != JPEGCOLORMODE_RGB)
     908             :         {
     909         251 :             TIFFSetField(hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
     910             :         }
     911             :     }
     912             : 
     913       40570 :     if (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     914       34847 :         m_nCompression == COMPRESSION_LERC)
     915             :     {
     916        5960 :         GTiffSetDeflateSubCodec(hTIFF);
     917             :     }
     918             : 
     919             :     /* -------------------------------------------------------------------- */
     920             :     /*      Propagate any quality settings.                                 */
     921             :     /* -------------------------------------------------------------------- */
     922       40570 :     if (eAccess == GA_Update)
     923             :     {
     924             :         // Now, reset zip and jpeg quality.
     925       34492 :         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         185 :             TIFFSetField(hTIFF, TIFFTAG_JPEGQUALITY, m_nJpegQuality);
     932             :         }
     933       34492 :         if (m_nJpegTablesMode >= 0 && m_nCompression == COMPRESSION_JPEG)
     934         323 :             TIFFSetField(hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
     935       34492 :         if (m_nZLevel > 0 && (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     936          12 :                               m_nCompression == COMPRESSION_LERC))
     937          26 :             TIFFSetField(hTIFF, TIFFTAG_ZIPQUALITY, m_nZLevel);
     938       34492 :         if (m_nLZMAPreset > 0 && m_nCompression == COMPRESSION_LZMA)
     939           8 :             TIFFSetField(hTIFF, TIFFTAG_LZMAPRESET, m_nLZMAPreset);
     940       34492 :         if (m_nZSTDLevel > 0 && (m_nCompression == COMPRESSION_ZSTD ||
     941          12 :                                  m_nCompression == COMPRESSION_LERC))
     942          18 :             TIFFSetField(hTIFF, TIFFTAG_ZSTD_LEVEL, m_nZSTDLevel);
     943       34492 :         if (m_nCompression == COMPRESSION_LERC)
     944             :         {
     945         185 :             TIFFSetField(hTIFF, TIFFTAG_LERC_MAXZERROR, m_dfMaxZError);
     946             :         }
     947       34492 :         if (m_nWebPLevel > 0 && m_nCompression == COMPRESSION_WEBP)
     948         124 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LEVEL, m_nWebPLevel);
     949       34492 :         if (m_bWebPLossless && m_nCompression == COMPRESSION_WEBP)
     950          50 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
     951             : #ifdef HAVE_JXL
     952       34492 :         if (m_nCompression == COMPRESSION_JXL ||
     953       34490 :             m_nCompression == COMPRESSION_JXL_DNG_1_7)
     954             :         {
     955          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_LOSSYNESS,
     956          76 :                          m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
     957          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_EFFORT, m_nJXLEffort);
     958          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_DISTANCE, m_fJXLDistance);
     959          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
     960          76 :                          m_fJXLAlphaDistance);
     961             :         }
     962             : #endif
     963             :     }
     964       40570 : }
     965             : 
     966             : /************************************************************************/
     967             : /*                     ComputeBlocksPerColRowAndBand()                  */
     968             : /************************************************************************/
     969             : 
     970       26566 : bool GTiffDataset::ComputeBlocksPerColRowAndBand(int l_nBands)
     971             : {
     972       26566 :     m_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, m_nBlockYSize);
     973       26566 :     m_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, m_nBlockXSize);
     974       26566 :     if (m_nBlocksPerColumn > INT_MAX / m_nBlocksPerRow)
     975             :     {
     976           1 :         ReportError(CE_Failure, CPLE_AppDefined, "Too many blocks: %d x %d",
     977             :                     m_nBlocksPerRow, m_nBlocksPerColumn);
     978           1 :         return false;
     979             :     }
     980             : 
     981             :     // Note: we could potentially go up to UINT_MAX blocks, but currently
     982             :     // we use a int nBlockId
     983       26565 :     m_nBlocksPerBand = m_nBlocksPerColumn * m_nBlocksPerRow;
     984       26565 :     if (m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
     985        1565 :         m_nBlocksPerBand > INT_MAX / l_nBands)
     986             :     {
     987           1 :         ReportError(CE_Failure, CPLE_AppDefined,
     988             :                     "Too many blocks: %d x %d x %d bands", m_nBlocksPerRow,
     989             :                     m_nBlocksPerColumn, l_nBands);
     990           1 :         return false;
     991             :     }
     992       26564 :     return true;
     993             : }
     994             : 
     995             : /************************************************************************/
     996             : /*                   SetStructuralMDFromParent()                        */
     997             : /************************************************************************/
     998             : 
     999        1051 : void GTiffDataset::SetStructuralMDFromParent(GTiffDataset *poParentDS)
    1000             : {
    1001        1051 :     m_bBlockOrderRowMajor = poParentDS->m_bBlockOrderRowMajor;
    1002        1051 :     m_bLeaderSizeAsUInt4 = poParentDS->m_bLeaderSizeAsUInt4;
    1003        1051 :     m_bTrailerRepeatedLast4BytesRepeated =
    1004        1051 :         poParentDS->m_bTrailerRepeatedLast4BytesRepeated;
    1005        1051 :     m_bMaskInterleavedWithImagery = poParentDS->m_bMaskInterleavedWithImagery;
    1006        1051 :     m_bWriteEmptyTiles = poParentDS->m_bWriteEmptyTiles;
    1007        1051 : }
    1008             : 
    1009             : /************************************************************************/
    1010             : /*                          ScanDirectories()                           */
    1011             : /*                                                                      */
    1012             : /*      Scan through all the directories finding overviews, masks       */
    1013             : /*      and subdatasets.                                                */
    1014             : /************************************************************************/
    1015             : 
    1016      806577 : void GTiffDataset::ScanDirectories()
    1017             : 
    1018             : {
    1019             :     /* -------------------------------------------------------------------- */
    1020             :     /*      We only scan once.  We do not scan for non-base datasets.       */
    1021             :     /* -------------------------------------------------------------------- */
    1022      806577 :     if (!m_bScanDeferred)
    1023      800404 :         return;
    1024             : 
    1025        6465 :     m_bScanDeferred = false;
    1026             : 
    1027        6465 :     if (m_poBaseDS)
    1028         292 :         return;
    1029             : 
    1030        6173 :     Crystalize();
    1031             : 
    1032        6179 :     CPLDebug("GTiff", "ScanDirectories()");
    1033             : 
    1034             :     /* ==================================================================== */
    1035             :     /*      Scan all directories.                                           */
    1036             :     /* ==================================================================== */
    1037       12358 :     CPLStringList aosSubdatasets;
    1038        6179 :     int iDirIndex = 0;
    1039             : 
    1040        6179 :     FlushDirectory();
    1041             : 
    1042        1038 :     do
    1043             :     {
    1044        7217 :         toff_t nTopDir = TIFFCurrentDirOffset(m_hTIFF);
    1045        7217 :         uint32_t nSubType = 0;
    1046             : 
    1047        7217 :         ++iDirIndex;
    1048             : 
    1049        7217 :         toff_t *tmpSubIFDOffsets = nullptr;
    1050        7217 :         toff_t *subIFDOffsets = nullptr;
    1051        7217 :         uint16_t nSubIFDs = 0;
    1052        7217 :         if (TIFFGetField(m_hTIFF, TIFFTAG_SUBIFD, &nSubIFDs,
    1053        7217 :                          &tmpSubIFDOffsets) &&
    1054             :             iDirIndex == 1)
    1055             :         {
    1056             :             subIFDOffsets =
    1057          13 :                 static_cast<toff_t *>(CPLMalloc(nSubIFDs * sizeof(toff_t)));
    1058          39 :             for (uint16_t iSubIFD = 0; iSubIFD < nSubIFDs; iSubIFD++)
    1059             :             {
    1060          26 :                 subIFDOffsets[iSubIFD] = tmpSubIFDOffsets[iSubIFD];
    1061             :             }
    1062             :         }
    1063             : 
    1064             :         // early break for backwards compatibility: if the first directory read
    1065             :         // is also the last, and there are no subIFDs, no use continuing
    1066        7217 :         if (iDirIndex == 1 && nSubIFDs == 0 && TIFFLastDirectory(m_hTIFF))
    1067             :         {
    1068        5556 :             CPLFree(subIFDOffsets);
    1069        5556 :             break;
    1070             :         }
    1071             : 
    1072        3348 :         for (uint16_t iSubIFD = 0; iSubIFD <= nSubIFDs; iSubIFD++)
    1073             :         {
    1074        1695 :             toff_t nThisDir = nTopDir;
    1075        1695 :             if (iSubIFD > 0 && iDirIndex > 1)  // don't read subIFDs if we are
    1076             :                                                // not in the original directory
    1077           8 :                 break;
    1078        1687 :             if (iSubIFD > 0)
    1079             :             {
    1080             :                 // make static analyzer happy. subIFDOffsets cannot be null if
    1081             :                 // iSubIFD>0
    1082          26 :                 assert(subIFDOffsets != nullptr);
    1083          26 :                 nThisDir = subIFDOffsets[iSubIFD - 1];
    1084             :                 // CPLDebug("GTiff", "Opened subIFD %d/%d at offset %llu.",
    1085             :                 // iSubIFD, nSubIFDs, nThisDir);
    1086          26 :                 if (!TIFFSetSubDirectory(m_hTIFF, nThisDir))
    1087           0 :                     break;
    1088             :             }
    1089             : 
    1090        1687 :             if (!TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
    1091         388 :                 nSubType = 0;
    1092             : 
    1093             :             /* Embedded overview of the main image */
    1094        1687 :             if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1095        1201 :                 (nSubType & FILETYPE_MASK) == 0 &&
    1096        1112 :                 ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1097         864 :                 m_nOverviewCount < 30 /* to avoid DoS */)
    1098             :             {
    1099         864 :                 GTiffDataset *poODS = new GTiffDataset();
    1100         864 :                 poODS->ShareLockWithParentDataset(this);
    1101         864 :                 poODS->SetStructuralMDFromParent(this);
    1102         864 :                 if (m_bHasGotSiblingFiles)
    1103         169 :                     poODS->oOvManager.TransferSiblingFiles(
    1104             :                         CSLDuplicate(GetSiblingFiles()));
    1105         864 :                 poODS->m_pszFilename = CPLStrdup(m_pszFilename);
    1106         864 :                 poODS->m_nColorTableMultiplier = m_nColorTableMultiplier;
    1107         864 :                 if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1108        1728 :                                       eAccess) != CE_None ||
    1109         864 :                     poODS->GetRasterCount() != GetRasterCount())
    1110             :                 {
    1111           0 :                     delete poODS;
    1112             :                 }
    1113             :                 else
    1114             :                 {
    1115         864 :                     CPLDebug("GTiff", "Opened %dx%d overview.",
    1116             :                              poODS->GetRasterXSize(), poODS->GetRasterYSize());
    1117         864 :                     ++m_nOverviewCount;
    1118        1728 :                     m_papoOverviewDS = static_cast<GTiffDataset **>(CPLRealloc(
    1119         864 :                         m_papoOverviewDS, m_nOverviewCount * (sizeof(void *))));
    1120         864 :                     m_papoOverviewDS[m_nOverviewCount - 1] = poODS;
    1121         864 :                     poODS->m_poBaseDS = this;
    1122         864 :                     poODS->m_bIsOverview = true;
    1123             : 
    1124             :                     // Propagate a few compression related settings that are
    1125             :                     // no preserved at the TIFF tag level, but may be set in
    1126             :                     // the GDAL_METADATA tag in the IMAGE_STRUCTURE domain
    1127             :                     // Note: this might not be totally reflecting the reality
    1128             :                     // if users have created overviews with different settings
    1129             :                     // but this is probably better than the default ones
    1130         864 :                     poODS->m_nWebPLevel = m_nWebPLevel;
    1131             :                     // below is not a copy & paste error: we transfer the
    1132             :                     // m_dfMaxZErrorOverview overview of the parent to
    1133             :                     // m_dfMaxZError of the overview
    1134         864 :                     poODS->m_dfMaxZError = m_dfMaxZErrorOverview;
    1135         864 :                     poODS->m_dfMaxZErrorOverview = m_dfMaxZErrorOverview;
    1136             : #if HAVE_JXL
    1137         864 :                     poODS->m_bJXLLossless = m_bJXLLossless;
    1138         864 :                     poODS->m_fJXLDistance = m_fJXLDistance;
    1139         864 :                     poODS->m_fJXLAlphaDistance = m_fJXLAlphaDistance;
    1140         864 :                     poODS->m_nJXLEffort = m_nJXLEffort;
    1141             : #endif
    1142             :                     // Those ones are not serialized currently..
    1143             :                     // poODS->m_nZLevel = m_nZLevel;
    1144             :                     // poODS->m_nLZMAPreset = m_nLZMAPreset;
    1145             :                     // poODS->m_nZSTDLevel = m_nZSTDLevel;
    1146         864 :                 }
    1147             :             }
    1148             :             // Embedded mask of the main image.
    1149         823 :             else if ((nSubType & FILETYPE_MASK) != 0 &&
    1150         187 :                      (nSubType & FILETYPE_REDUCEDIMAGE) == 0 &&
    1151          98 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1152          98 :                      m_poMaskDS == nullptr)
    1153             :             {
    1154          98 :                 m_poMaskDS = new GTiffDataset();
    1155          98 :                 m_poMaskDS->ShareLockWithParentDataset(this);
    1156          98 :                 m_poMaskDS->SetStructuralMDFromParent(this);
    1157          98 :                 m_poMaskDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1158             : 
    1159             :                 // The TIFF6 specification - page 37 - only allows 1
    1160             :                 // SamplesPerPixel and 1 BitsPerSample Here we support either 1
    1161             :                 // or 8 bit per sample and we support either 1 sample per pixel
    1162             :                 // or as many samples as in the main image We don't check the
    1163             :                 // value of the PhotometricInterpretation tag, which should be
    1164             :                 // set to "Transparency mask" (4) according to the specification
    1165             :                 // (page 36).  However, the TIFF6 specification allows image
    1166             :                 // masks to have a higher resolution than the main image, what
    1167             :                 // we don't support here.
    1168             : 
    1169          98 :                 if (m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1170          98 :                                            eAccess) != CE_None ||
    1171          98 :                     m_poMaskDS->GetRasterCount() == 0 ||
    1172          98 :                     !(m_poMaskDS->GetRasterCount() == 1 ||
    1173           3 :                       m_poMaskDS->GetRasterCount() == GetRasterCount()) ||
    1174          98 :                     m_poMaskDS->GetRasterXSize() != GetRasterXSize() ||
    1175         294 :                     m_poMaskDS->GetRasterYSize() != GetRasterYSize() ||
    1176          98 :                     m_poMaskDS->GetRasterBand(1)->GetRasterDataType() !=
    1177             :                         GDT_Byte)
    1178             :                 {
    1179           0 :                     delete m_poMaskDS;
    1180           0 :                     m_poMaskDS = nullptr;
    1181             :                 }
    1182             :                 else
    1183             :                 {
    1184          98 :                     CPLDebug("GTiff", "Opened band mask.");
    1185          98 :                     m_poMaskDS->m_poBaseDS = this;
    1186          98 :                     m_poMaskDS->m_poImageryDS = this;
    1187             : 
    1188         196 :                     m_poMaskDS->m_bPromoteTo8Bits =
    1189          98 :                         CPLTestBool(CPLGetConfigOption(
    1190             :                             "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1191             :                 }
    1192             :             }
    1193             : 
    1194             :             // Embedded mask of an overview.  The TIFF6 specification allows the
    1195             :             // combination of the FILETYPE_xxxx masks.
    1196         725 :             else if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1197         337 :                      (nSubType & FILETYPE_MASK) != 0 &&
    1198          89 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0))
    1199             :             {
    1200          89 :                 GTiffDataset *poDS = new GTiffDataset();
    1201          89 :                 poDS->ShareLockWithParentDataset(this);
    1202          89 :                 poDS->SetStructuralMDFromParent(this);
    1203          89 :                 poDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1204          89 :                 if (poDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1205          89 :                                      eAccess) != CE_None ||
    1206         178 :                     poDS->GetRasterCount() == 0 ||
    1207          89 :                     poDS->GetRasterBand(1)->GetRasterDataType() != GDT_Byte)
    1208             :                 {
    1209           0 :                     delete poDS;
    1210             :                 }
    1211             :                 else
    1212             :                 {
    1213          89 :                     int i = 0;  // Used after for.
    1214         129 :                     for (; i < m_nOverviewCount; ++i)
    1215             :                     {
    1216         129 :                         auto poOvrDS = cpl::down_cast<GTiffDataset *>(
    1217         129 :                             GDALDataset::FromHandle(m_papoOverviewDS[i]));
    1218         347 :                         if (poOvrDS->m_poMaskDS == nullptr &&
    1219          89 :                             poDS->GetRasterXSize() ==
    1220          89 :                                 m_papoOverviewDS[i]->GetRasterXSize() &&
    1221          89 :                             poDS->GetRasterYSize() ==
    1222         307 :                                 m_papoOverviewDS[i]->GetRasterYSize() &&
    1223          89 :                             (poDS->GetRasterCount() == 1 ||
    1224           0 :                              poDS->GetRasterCount() == GetRasterCount()))
    1225             :                         {
    1226          89 :                             CPLDebug(
    1227             :                                 "GTiff", "Opened band mask for %dx%d overview.",
    1228             :                                 poDS->GetRasterXSize(), poDS->GetRasterYSize());
    1229          89 :                             poDS->m_poImageryDS = poOvrDS;
    1230          89 :                             poOvrDS->m_poMaskDS = poDS;
    1231          89 :                             poDS->m_bPromoteTo8Bits =
    1232          89 :                                 CPLTestBool(CPLGetConfigOption(
    1233             :                                     "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1234          89 :                             poDS->m_poBaseDS = this;
    1235          89 :                             break;
    1236             :                         }
    1237             :                     }
    1238          89 :                     if (i == m_nOverviewCount)
    1239             :                     {
    1240           0 :                         delete poDS;
    1241             :                     }
    1242          89 :                 }
    1243             :             }
    1244         636 :             else if (!m_bSingleIFDOpened &&
    1245         631 :                      (nSubType == 0 || nSubType == FILETYPE_PAGE))
    1246             :             {
    1247         383 :                 uint32_t nXSize = 0;
    1248         383 :                 uint32_t nYSize = 0;
    1249             : 
    1250         383 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
    1251         383 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
    1252             : 
    1253             :                 // For Geodetic TIFF grids (GTG)
    1254             :                 // (https://proj.org/specifications/geodetictiffgrids.html)
    1255             :                 // extract the grid_name to put it in the description
    1256         766 :                 std::string osFriendlyName;
    1257         383 :                 char *pszText = nullptr;
    1258         442 :                 if (TIFFGetField(m_hTIFF, TIFFTAG_GDAL_METADATA, &pszText) &&
    1259          59 :                     strstr(pszText, "grid_name") != nullptr)
    1260             :                 {
    1261           4 :                     CPLXMLNode *psRoot = CPLParseXMLString(pszText);
    1262             :                     const CPLXMLNode *psItem =
    1263           4 :                         psRoot ? CPLGetXMLNode(psRoot, "=GDALMetadata")
    1264           4 :                                : nullptr;
    1265           4 :                     if (psItem)
    1266           4 :                         psItem = psItem->psChild;
    1267           4 :                     for (; psItem != nullptr; psItem = psItem->psNext)
    1268             :                     {
    1269             : 
    1270           4 :                         if (psItem->eType != CXT_Element ||
    1271           4 :                             !EQUAL(psItem->pszValue, "Item"))
    1272           0 :                             continue;
    1273             : 
    1274             :                         const char *pszKey =
    1275           4 :                             CPLGetXMLValue(psItem, "name", nullptr);
    1276             :                         const char *pszValue =
    1277           4 :                             CPLGetXMLValue(psItem, nullptr, nullptr);
    1278             :                         int nBand =
    1279           4 :                             atoi(CPLGetXMLValue(psItem, "sample", "-1"));
    1280           4 :                         if (pszKey && pszValue && nBand <= 0 &&
    1281           4 :                             EQUAL(pszKey, "grid_name"))
    1282             :                         {
    1283           4 :                             osFriendlyName = ": ";
    1284           4 :                             osFriendlyName += pszValue;
    1285           4 :                             break;
    1286             :                         }
    1287             :                     }
    1288             : 
    1289           4 :                     CPLDestroyXMLNode(psRoot);
    1290             :                 }
    1291             : 
    1292         383 :                 if (nXSize > INT_MAX || nYSize > INT_MAX)
    1293             :                 {
    1294           1 :                     CPLDebug("GTiff",
    1295             :                              "Skipping directory with too large image: %u x %u",
    1296             :                              nXSize, nYSize);
    1297             :                 }
    1298             :                 else
    1299             :                 {
    1300         382 :                     uint16_t nSPP = 0;
    1301         382 :                     if (!TIFFGetField(m_hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSPP))
    1302           0 :                         nSPP = 1;
    1303             : 
    1304         764 :                     CPLString osName, osDesc;
    1305             :                     osName.Printf("SUBDATASET_%d_NAME=GTIFF_DIR:%d:%s",
    1306         382 :                                   iDirIndex, iDirIndex, m_pszFilename);
    1307             :                     osDesc.Printf(
    1308             :                         "SUBDATASET_%d_DESC=Page %d (%dP x %dL x %dB)",
    1309             :                         iDirIndex, iDirIndex, static_cast<int>(nXSize),
    1310         382 :                         static_cast<int>(nYSize), nSPP);
    1311         382 :                     osDesc += osFriendlyName;
    1312             : 
    1313         382 :                     aosSubdatasets.AddString(osName);
    1314         382 :                     aosSubdatasets.AddString(osDesc);
    1315             :                 }
    1316             :             }
    1317             :         }
    1318        1661 :         CPLFree(subIFDOffsets);
    1319             : 
    1320             :         // Make sure we are stepping from the expected directory regardless
    1321             :         // of churn done processing the above.
    1322        1661 :         if (TIFFCurrentDirOffset(m_hTIFF) != nTopDir)
    1323          13 :             TIFFSetSubDirectory(m_hTIFF, nTopDir);
    1324        2699 :     } while (!m_bSingleIFDOpened && !TIFFLastDirectory(m_hTIFF) &&
    1325        1038 :              TIFFReadDirectory(m_hTIFF) != 0);
    1326             : 
    1327        6179 :     ReloadDirectory();
    1328             : 
    1329             :     // If we have a mask for the main image, loop over the overviews, and if
    1330             :     // they have a mask, let's set this mask as an overview of the main mask.
    1331        6179 :     if (m_poMaskDS != nullptr)
    1332             :     {
    1333         187 :         for (int i = 0; i < m_nOverviewCount; ++i)
    1334             :         {
    1335          89 :             if (cpl::down_cast<GTiffDataset *>(
    1336          89 :                     GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1337          89 :                     ->m_poMaskDS != nullptr)
    1338             :             {
    1339          89 :                 ++m_poMaskDS->m_nOverviewCount;
    1340         178 :                 m_poMaskDS->m_papoOverviewDS =
    1341         178 :                     static_cast<GTiffDataset **>(CPLRealloc(
    1342          89 :                         m_poMaskDS->m_papoOverviewDS,
    1343          89 :                         m_poMaskDS->m_nOverviewCount * (sizeof(void *))));
    1344          89 :                 m_poMaskDS->m_papoOverviewDS[m_poMaskDS->m_nOverviewCount - 1] =
    1345          89 :                     cpl::down_cast<GTiffDataset *>(
    1346          89 :                         GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1347          89 :                         ->m_poMaskDS;
    1348             :             }
    1349             :         }
    1350             :     }
    1351             : 
    1352             :     // Assign color interpretation from main dataset
    1353        6179 :     const int l_nBands = GetRasterCount();
    1354        7042 :     for (int iOvr = 0; iOvr < m_nOverviewCount; ++iOvr)
    1355             :     {
    1356        2385 :         for (int i = 1; i <= l_nBands; i++)
    1357             :         {
    1358           0 :             auto poBand = dynamic_cast<GTiffRasterBand *>(
    1359        1522 :                 m_papoOverviewDS[iOvr]->GetRasterBand(i));
    1360        1522 :             if (poBand)
    1361        1521 :                 poBand->m_eBandInterp =
    1362        1522 :                     GetRasterBand(i)->GetColorInterpretation();
    1363             :         }
    1364             :     }
    1365             : 
    1366             :     /* -------------------------------------------------------------------- */
    1367             :     /*      Only keep track of subdatasets if we have more than one         */
    1368             :     /*      subdataset (pair).                                              */
    1369             :     /* -------------------------------------------------------------------- */
    1370        6178 :     if (aosSubdatasets.size() > 2)
    1371             :     {
    1372          10 :         m_oGTiffMDMD.SetMetadata(aosSubdatasets.List(), "SUBDATASETS");
    1373             :     }
    1374             : }
    1375             : 
    1376             : /************************************************************************/
    1377             : /*                         GetInternalHandle()                          */
    1378             : /************************************************************************/
    1379             : 
    1380        2107 : void *GTiffDataset::GetInternalHandle(const char * /* pszHandleName */)
    1381             : 
    1382             : {
    1383        2107 :     return m_hTIFF;
    1384             : }
    1385             : 
    1386             : /************************************************************************/
    1387             : /*                            GetFileList()                             */
    1388             : /************************************************************************/
    1389             : 
    1390        2434 : char **GTiffDataset::GetFileList()
    1391             : 
    1392             : {
    1393        2434 :     LoadGeoreferencingAndPamIfNeeded();
    1394             : 
    1395        2434 :     char **papszFileList = GDALPamDataset::GetFileList();
    1396             : 
    1397        2434 :     LoadMetadata();
    1398        2434 :     if (nullptr != m_papszMetadataFiles)
    1399             :     {
    1400          77 :         for (int i = 0; m_papszMetadataFiles[i] != nullptr; ++i)
    1401             :         {
    1402          44 :             if (CSLFindString(papszFileList, m_papszMetadataFiles[i]) < 0)
    1403             :             {
    1404             :                 papszFileList =
    1405          44 :                     CSLAddString(papszFileList, m_papszMetadataFiles[i]);
    1406             :             }
    1407             :         }
    1408             :     }
    1409             : 
    1410        2440 :     if (m_pszGeorefFilename &&
    1411           6 :         CSLFindString(papszFileList, m_pszGeorefFilename) == -1)
    1412             :     {
    1413           6 :         papszFileList = CSLAddString(papszFileList, m_pszGeorefFilename);
    1414             :     }
    1415             : 
    1416        2434 :     if (m_nXMLGeorefSrcIndex >= 0)
    1417        2434 :         LookForProjection();
    1418             : 
    1419        2435 :     if (m_pszXMLFilename &&
    1420           1 :         CSLFindString(papszFileList, m_pszXMLFilename) == -1)
    1421             :     {
    1422           1 :         papszFileList = CSLAddString(papszFileList, m_pszXMLFilename);
    1423             :     }
    1424             : 
    1425        2434 :     return papszFileList;
    1426             : }
    1427             : 
    1428             : /************************************************************************/
    1429             : /*                        GetRawBinaryLayout()                          */
    1430             : /************************************************************************/
    1431             : 
    1432           9 : bool GTiffDataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
    1433             : {
    1434           9 :     if (eAccess == GA_Update)
    1435             :     {
    1436           3 :         FlushCache(false);
    1437           3 :         Crystalize();
    1438             :     }
    1439             : 
    1440           9 :     if (m_nCompression != COMPRESSION_NONE)
    1441           1 :         return false;
    1442           8 :     if (!CPLIsPowerOfTwo(m_nBitsPerSample) || m_nBitsPerSample < 8)
    1443           0 :         return false;
    1444           8 :     const auto eDT = GetRasterBand(1)->GetRasterDataType();
    1445           8 :     if (GDALDataTypeIsComplex(eDT))
    1446           0 :         return false;
    1447             : 
    1448           8 :     toff_t *panByteCounts = nullptr;
    1449           8 :     toff_t *panOffsets = nullptr;
    1450           8 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
    1451             : 
    1452          16 :     if (!((bIsTiled &&
    1453           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
    1454           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets)) ||
    1455           5 :           (!bIsTiled &&
    1456           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
    1457           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
    1458             :     {
    1459           0 :         return false;
    1460             :     }
    1461             : 
    1462           8 :     const int nDTSize = GDALGetDataTypeSizeBytes(eDT);
    1463           8 :     vsi_l_offset nImgOffset = panOffsets[0];
    1464          16 :     GIntBig nPixelOffset = (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1465           8 :                                ? static_cast<GIntBig>(nDTSize) * nBands
    1466             :                                : nDTSize;
    1467           8 :     GIntBig nLineOffset = nPixelOffset * nRasterXSize;
    1468           8 :     GIntBig nBandOffset =
    1469           8 :         (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1) ? nDTSize : 0;
    1470           8 :     RawBinaryLayout::Interleaving eInterleaving =
    1471          12 :         (nBands == 1) ? RawBinaryLayout::Interleaving::UNKNOWN
    1472           4 :         : (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1473           4 :             ? RawBinaryLayout::Interleaving::BIP
    1474             :             : RawBinaryLayout::Interleaving::BSQ;
    1475           8 :     if (bIsTiled)
    1476             :     {
    1477             :         // Only a single block tiled file with same dimension as the raster
    1478             :         // might be acceptable
    1479           3 :         if (m_nBlockXSize != nRasterXSize || m_nBlockYSize != nRasterYSize)
    1480           1 :             return false;
    1481           2 :         if (nBands > 1 && m_nPlanarConfig != PLANARCONFIG_CONTIG)
    1482             :         {
    1483           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[1]) -
    1484           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1485           2 :             for (int i = 2; i < nBands; i++)
    1486             :             {
    1487           1 :                 if (static_cast<GIntBig>(panOffsets[i]) -
    1488           1 :                         static_cast<GIntBig>(panOffsets[i - 1]) !=
    1489             :                     nBandOffset)
    1490           0 :                     return false;
    1491             :             }
    1492             :         }
    1493             :     }
    1494             :     else
    1495             :     {
    1496           5 :         const int nStrips = DIV_ROUND_UP(nRasterYSize, m_nRowsPerStrip);
    1497           5 :         if (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1498             :         {
    1499           4 :             vsi_l_offset nLastStripEnd = panOffsets[0] + panByteCounts[0];
    1500          16 :             for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1501             :             {
    1502          12 :                 if (nLastStripEnd != panOffsets[iStrip])
    1503           0 :                     return false;
    1504          12 :                 nLastStripEnd = panOffsets[iStrip] + panByteCounts[iStrip];
    1505           4 :             }
    1506             :         }
    1507             :         else
    1508             :         {
    1509             :             // Note: we could potentially have BIL order with m_nRowsPerStrip ==
    1510             :             // 1 and if strips are ordered strip_line_1_band_1, ...,
    1511             :             // strip_line_1_band_N, strip_line2_band1, ... strip_line2_band_N,
    1512             :             // etc.... but that'd be faily exotic ! So only detect BSQ layout
    1513             :             // here
    1514           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[nStrips]) -
    1515           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1516           4 :             for (int i = 0; i < nBands; i++)
    1517             :             {
    1518           3 :                 uint32_t iStripOffset = nStrips * i;
    1519           3 :                 vsi_l_offset nLastStripEnd =
    1520           3 :                     panOffsets[iStripOffset] + panByteCounts[iStripOffset];
    1521           3 :                 for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1522             :                 {
    1523           0 :                     if (nLastStripEnd != panOffsets[iStripOffset + iStrip])
    1524           0 :                         return false;
    1525           0 :                     nLastStripEnd = panOffsets[iStripOffset + iStrip] +
    1526           0 :                                     panByteCounts[iStripOffset + iStrip];
    1527             :                 }
    1528           3 :                 if (i >= 2 && static_cast<GIntBig>(panOffsets[iStripOffset]) -
    1529           1 :                                       static_cast<GIntBig>(
    1530           1 :                                           panOffsets[iStripOffset - nStrips]) !=
    1531             :                                   nBandOffset)
    1532             :                 {
    1533           0 :                     return false;
    1534             :                 }
    1535             :             }
    1536             :         }
    1537             :     }
    1538             : 
    1539           7 :     sLayout.osRawFilename = m_pszFilename;
    1540           7 :     sLayout.eInterleaving = eInterleaving;
    1541           7 :     sLayout.eDataType = eDT;
    1542             : #ifdef CPL_LSB
    1543           7 :     sLayout.bLittleEndianOrder = !TIFFIsByteSwapped(m_hTIFF);
    1544             : #else
    1545             :     sLayout.bLittleEndianOrder = TIFFIsByteSwapped(m_hTIFF);
    1546             : #endif
    1547           7 :     sLayout.nImageOffset = nImgOffset;
    1548           7 :     sLayout.nPixelOffset = nPixelOffset;
    1549           7 :     sLayout.nLineOffset = nLineOffset;
    1550           7 :     sLayout.nBandOffset = nBandOffset;
    1551             : 
    1552           7 :     return true;
    1553             : }
    1554             : 
    1555             : /************************************************************************/
    1556             : /*               GTiffDatasetLibGeotiffErrorCallback()                  */
    1557             : /************************************************************************/
    1558             : 
    1559           0 : static void GTiffDatasetLibGeotiffErrorCallback(GTIF *, int level,
    1560             :                                                 const char *pszMsg, ...)
    1561             : {
    1562             :     va_list ap;
    1563           0 :     va_start(ap, pszMsg);
    1564           0 :     CPLErrorV((level == LIBGEOTIFF_WARNING) ? CE_Warning : CE_Failure,
    1565             :               CPLE_AppDefined, pszMsg, ap);
    1566           0 :     va_end(ap);
    1567           0 : }
    1568             : 
    1569             : /************************************************************************/
    1570             : /*                           GTIFNew()                                  */
    1571             : /************************************************************************/
    1572             : 
    1573       26298 : /* static */ GTIF *GTiffDataset::GTIFNew(TIFF *hTIFF)
    1574             : {
    1575       26298 :     GTIF *gtif = GTIFNewEx(hTIFF, GTiffDatasetLibGeotiffErrorCallback, nullptr);
    1576       26298 :     if (gtif)
    1577             :     {
    1578       26298 :         GTIFAttachPROJContext(gtif, OSRGetProjTLSContext());
    1579             :     }
    1580       26298 :     return gtif;
    1581             : }

Generated by: LCOV version 1.14