LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 688 737 93.4 %
Date: 2025-02-20 10:14:44 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       25811 : const GTIFFTag *GTiffDataset::GetTIFFTags()
      63             : {
      64       25811 :     return asTIFFTags;
      65             : }
      66             : 
      67             : /************************************************************************/
      68             : /*                            GTiffDataset()                            */
      69             : /************************************************************************/
      70             : 
      71       26959 : 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       26990 :           CPLTestBool(CPLGetConfigOption("GTIFF_DONT_WRITE_BLOCKS", "NO"))),
      91             :       m_bIsFinalized(false),
      92             :       m_bIgnoreReadErrors(
      93       26986 :           CPLTestBool(CPLGetConfigOption("GTIFF_IGNORE_READ_ERRORS", "NO"))),
      94       26989 :       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       80932 :       m_bWriteCOGLayout(false), m_bTileInterleave(false)
     103             : {
     104             :     // CPLDebug("GDAL", "sizeof(GTiffDataset) = %d bytes", static_cast<int>(
     105             :     //     sizeof(GTiffDataset)));
     106             : 
     107             :     const char *pszVirtualMemIO =
     108       26988 :         CPLGetConfigOption("GTIFF_VIRTUAL_MEM_IO", "NO");
     109       26989 :     if (EQUAL(pszVirtualMemIO, "IF_ENOUGH_RAM"))
     110           0 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::IF_ENOUGH_RAM;
     111       26989 :     else if (CPLTestBool(pszVirtualMemIO))
     112          41 :         m_eVirtualMemIOUsage = VirtualMemIOEnum::YES;
     113             : 
     114       26974 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     115       26910 : }
     116             : 
     117             : /************************************************************************/
     118             : /*                           ~GTiffDataset()                            */
     119             : /************************************************************************/
     120             : 
     121       53973 : GTiffDataset::~GTiffDataset()
     122             : 
     123             : {
     124       26987 :     GTiffDataset::Close();
     125       53970 : }
     126             : 
     127             : /************************************************************************/
     128             : /*                              Close()                                 */
     129             : /************************************************************************/
     130             : 
     131       47895 : CPLErr GTiffDataset::Close()
     132             : {
     133       47895 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     134             :     {
     135       26988 :         auto [eErr, bDroppedRef] = Finalize();
     136             : 
     137       26985 :         if (m_pszTmpFilename)
     138             :         {
     139           4 :             VSIUnlink(m_pszTmpFilename);
     140           4 :             CPLFree(m_pszTmpFilename);
     141             :         }
     142             : 
     143       26985 :         if (GDALPamDataset::Close() != CE_None)
     144           0 :             eErr = CE_Failure;
     145       26985 :         return eErr;
     146             :     }
     147       20907 :     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       27069 : std::tuple<CPLErr, bool> GTiffDataset::Finalize()
     157             : {
     158       27069 :     bool bDroppedRef = false;
     159       27069 :     if (m_bIsFinalized)
     160         162 :         return std::tuple(CE_None, bDroppedRef);
     161             : 
     162       26988 :     CPLErr eErr = CE_None;
     163       26988 :     Crystalize();
     164             : 
     165       26987 :     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       26987 :     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       26988 :     if (m_psVirtualMemIOMapping)
     184          11 :         CPLVirtualMemFree(m_psVirtualMemIOMapping);
     185       26988 :     m_psVirtualMemIOMapping = nullptr;
     186             : 
     187             :     /* -------------------------------------------------------------------- */
     188             :     /*      Fill in missing blocks with empty data.                         */
     189             :     /* -------------------------------------------------------------------- */
     190       26988 :     if (m_bFillEmptyTilesAtClosing)
     191             :     {
     192             :         /* --------------------------------------------------------------------
     193             :          */
     194             :         /*  Ensure any blocks write cached by GDAL gets pushed through libtiff.
     195             :          */
     196             :         /* --------------------------------------------------------------------
     197             :          */
     198        5381 :         if (FlushCacheInternal(true, /* at closing */
     199        5381 :                                false /* do not call FlushDirectory */) !=
     200             :             CE_None)
     201             :         {
     202           0 :             eErr = CE_Failure;
     203             :         }
     204             : 
     205        5381 :         if (FillEmptyTiles() != CE_None)
     206             :         {
     207           9 :             eErr = CE_Failure;
     208             :         }
     209        5381 :         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       26988 :     if (FlushCacheInternal(true /* at closing */, true) != CE_None)
     217             :     {
     218           7 :         eErr = CE_Failure;
     219             :     }
     220             : 
     221             :     // Destroy compression queue
     222       26985 :     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       26985 :     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       26985 :     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       25248 :         const int nOldOverviewCount = m_nOverviewCount;
     258       25248 :         m_nOverviewCount = 0;
     259       26631 :         for (int i = 0; i < nOldOverviewCount; ++i)
     260             :         {
     261        1384 :             delete m_papoOverviewDS[i];
     262        1383 :             bDroppedRef = true;
     263             :         }
     264             : 
     265       25307 :         for (int i = 0; i < m_nJPEGOverviewCountOri; ++i)
     266             :         {
     267          60 :             delete m_papoJPEGOverviewDS[i];
     268          60 :             bDroppedRef = true;
     269             :         }
     270       25247 :         m_nJPEGOverviewCount = 0;
     271       25247 :         m_nJPEGOverviewCountOri = 0;
     272       25247 :         CPLFree(m_papoJPEGOverviewDS);
     273       25246 :         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       26983 :     CPLFree(m_papoOverviewDS);
     279       26985 :     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       26985 :     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         352 :         auto poMaskDS = m_poMaskDS;
     290         352 :         m_poMaskDS = nullptr;
     291         352 :         delete poMaskDS;
     292         352 :         bDroppedRef = true;
     293             :     }
     294             : 
     295       26985 :     m_poColorTable.reset();
     296             : 
     297       26982 :     if (m_hTIFF)
     298             :     {
     299       26981 :         XTIFFClose(m_hTIFF);
     300       26987 :         m_hTIFF = nullptr;
     301             :     }
     302             : 
     303       26988 :     if (!m_poBaseDS)
     304             :     {
     305       25248 :         if (m_fpL != nullptr)
     306             :         {
     307       25248 :             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       25248 :             if (VSIFCloseL(m_fpL) != 0)
     332             :             {
     333           0 :                 eErr = CE_Failure;
     334           0 :                 ReportError(CE_Failure, CPLE_FileIO, "I/O error");
     335             :             }
     336       25248 :             m_fpL = nullptr;
     337             :         }
     338             :     }
     339             : 
     340       26988 :     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       26988 :     m_aoGCPs.clear();
     351             : 
     352       26988 :     CSLDestroy(m_papszCreationOptions);
     353       26988 :     m_papszCreationOptions = nullptr;
     354             : 
     355       26988 :     CPLFree(m_pabyTempWriteBuffer);
     356       26987 :     m_pabyTempWriteBuffer = nullptr;
     357             : 
     358       26987 :     m_bIMDRPCMetadataLoaded = false;
     359       26987 :     CSLDestroy(m_papszMetadataFiles);
     360       26986 :     m_papszMetadataFiles = nullptr;
     361             : 
     362       26986 :     VSIFree(m_pTempBufferForCommonDirectIO);
     363       26988 :     m_pTempBufferForCommonDirectIO = nullptr;
     364             : 
     365       26988 :     CPLFree(m_panMaskOffsetLsb);
     366       26987 :     m_panMaskOffsetLsb = nullptr;
     367             : 
     368       26987 :     CPLFree(m_pszVertUnit);
     369       26988 :     m_pszVertUnit = nullptr;
     370             : 
     371       26988 :     CPLFree(m_pszFilename);
     372       26988 :     m_pszFilename = nullptr;
     373             : 
     374       26988 :     CPLFree(m_pszGeorefFilename);
     375       26988 :     m_pszGeorefFilename = nullptr;
     376             : 
     377       26988 :     CPLFree(m_pszXMLFilename);
     378       26988 :     m_pszXMLFilename = nullptr;
     379             : 
     380       26988 :     m_bIsFinalized = true;
     381             : 
     382       26988 :     return std::tuple(eErr, bDroppedRef);
     383             : }
     384             : 
     385             : /************************************************************************/
     386             : /*                        CloseDependentDatasets()                      */
     387             : /************************************************************************/
     388             : 
     389          81 : int GTiffDataset::CloseDependentDatasets()
     390             : {
     391          81 :     if (m_poBaseDS)
     392           0 :         return FALSE;
     393             : 
     394          81 :     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          81 :     auto [eErr, bHasDroppedRefInFinalize] = Finalize();
     399          81 :     if (bHasDroppedRefInFinalize)
     400           1 :         bHasDroppedRef = true;
     401             : 
     402          81 :     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      434898 : 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      434898 :     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      434876 :     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      434268 :     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      433854 :     bool bCanUseMultiThreadedRead = false;
     476      433854 :     if (m_nDisableMultiThreadedRead == 0 && m_poThreadPool &&
     477      867853 :         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 size_t nBlocks =
     487         145 :             static_cast<size_t>(nXBlocks) * nYBlocks *
     488         145 :             (m_nPlanarConfig == PLANARCONFIG_CONTIG ? 1 : nBandCount);
     489         145 :         if (nBlocks > 1)
     490             :         {
     491         142 :             bCanUseMultiThreadedRead = true;
     492             :         }
     493             :     }
     494             : 
     495      433854 :     void *pBufferedData = nullptr;
     496      433854 :     const auto poFirstBand = cpl::down_cast<GTiffRasterBand *>(papoBands[0]);
     497      433853 :     const auto eDataType = poFirstBand->GetRasterDataType();
     498             : 
     499       37878 :     if (eAccess == GA_ReadOnly && eRWFlag == GF_Read &&
     500      471749 :         HasOptimizedReadMultiRange() &&
     501          17 :         !(bCanUseMultiThreadedRead &&
     502           3 :           VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF))->HasPRead()))
     503             :     {
     504          14 :         if (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG)
     505             :         {
     506          12 :             const int nBandOne = 1;
     507             :             pBufferedData =
     508          12 :                 CacheMultiRange(nXOff, nYOff, nXSize, nYSize, nBufXSize,
     509          12 :                                 nBufYSize, &nBandOne, 1, psExtraArg);
     510             :         }
     511             :         else
     512             :         {
     513             :             pBufferedData =
     514           2 :                 CacheMultiRange(nXOff, nYOff, nXSize, nYSize, nBufXSize,
     515             :                                 nBufYSize, panBandMap, nBandCount, psExtraArg);
     516             :         }
     517             :     }
     518      433840 :     else if (bCanUseMultiThreadedRead)
     519             :     {
     520         142 :         return MultiThreadedRead(nXOff, nYOff, nXSize, nYSize, pData, eBufType,
     521             :                                  nBandCount, panBandMap, nPixelSpace,
     522         142 :                                  nLineSpace, nBandSpace);
     523             :     }
     524             : 
     525             :     // Write optimization when writing whole blocks, by-passing the block cache.
     526             :     // We require the block cache to be non instantiated to simplify things
     527             :     // (otherwise we might need to evict corresponding existing blocks from the
     528             :     // block cache).
     529      202668 :     else if (eRWFlag == GF_Write && nBands > 1 &&
     530       28753 :              m_nPlanarConfig == PLANARCONFIG_CONTIG &&
     531             :              // Could be extended to "odd bit" case, but more work
     532       28273 :              m_nBitsPerSample == GDALGetDataTypeSize(eDataType) &&
     533       28262 :              nXSize == nBufXSize && nYSize == nBufYSize &&
     534       28260 :              nBandCount == nBands && !m_bLoadedBlockDirty &&
     535       28238 :              (nXOff % m_nBlockXSize) == 0 && (nYOff % m_nBlockYSize) == 0 &&
     536        2497 :              (nXOff + nXSize == nRasterXSize ||
     537      636406 :               (nXSize % m_nBlockXSize) == 0) &&
     538        2494 :              (nYOff + nYSize == nRasterYSize || (nYSize % m_nBlockYSize) == 0))
     539             :     {
     540        2372 :         bool bOptimOK = true;
     541        2372 :         bool bOrderedBands = true;
     542        9818 :         for (int i = 0; i < nBands; ++i)
     543             :         {
     544        7455 :             if (panBandMap[i] != i + 1)
     545             :             {
     546          14 :                 bOrderedBands = false;
     547             :             }
     548       14910 :             if (cpl::down_cast<GTiffRasterBand *>(papoBands[panBandMap[i] - 1])
     549        7455 :                     ->HasBlockCache())
     550             :             {
     551           9 :                 bOptimOK = false;
     552           9 :                 break;
     553             :             }
     554             :         }
     555        2372 :         if (bOptimOK)
     556             :         {
     557        2363 :             Crystalize();
     558             : 
     559        2363 :             if (m_bDebugDontWriteBlocks)
     560           0 :                 return CE_None;
     561             : 
     562        2363 :             const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
     563        2363 :             if (bOrderedBands && nXSize == m_nBlockXSize &&
     564        2142 :                 nYSize == m_nBlockYSize && eBufType == eDataType &&
     565        1178 :                 nBandSpace == nDTSize &&
     566          23 :                 nPixelSpace == static_cast<GSpacing>(nDTSize) * nBands &&
     567           5 :                 nLineSpace == nPixelSpace * m_nBlockXSize)
     568             :             {
     569             :                 // If writing one single block with the right data type and
     570             :                 // layout (interleaved per pixel), we don't need a temporary
     571             :                 // buffer
     572          10 :                 const int nBlockId = poFirstBand->ComputeBlockId(
     573           5 :                     nXOff / m_nBlockXSize, nYOff / m_nBlockYSize);
     574           5 :                 return WriteEncodedTileOrStrip(nBlockId, pData,
     575           5 :                                                /* bPreserveDataBuffer= */ true);
     576             :             }
     577             : 
     578             :             // Make sure m_poGDS->m_pabyBlockBuf is allocated.
     579             :             // We could actually use any temporary buffer
     580        2358 :             if (LoadBlockBuf(/* nBlockId = */ -1,
     581        2358 :                              /* bReadFromDisk = */ false) != CE_None)
     582             :             {
     583           0 :                 return CE_Failure;
     584             :             }
     585             : 
     586             :             // Iterate over all blocks defined by
     587             :             // [nXOff, nXOff+nXSize[ * [nYOff, nYOff+nYSize[
     588             :             // and write their content as a nBlockXSize x nBlockYSize strile
     589             :             // in a temporary buffer, before calling WriteEncodedTileOrStrip()
     590             :             // on it
     591        2358 :             const int nYBlockStart = nYOff / m_nBlockYSize;
     592        2358 :             const int nYBlockEnd = 1 + (nYOff + nYSize - 1) / m_nBlockYSize;
     593        2358 :             const int nXBlockStart = nXOff / m_nBlockXSize;
     594        2358 :             const int nXBlockEnd = 1 + (nXOff + nXSize - 1) / m_nBlockXSize;
     595       33906 :             for (int nYBlock = nYBlockStart; nYBlock < nYBlockEnd; ++nYBlock)
     596             :             {
     597             :                 const int nValidY = std::min(
     598       31552 :                     m_nBlockYSize, nRasterYSize - nYBlock * m_nBlockYSize);
     599       65857 :                 for (int nXBlock = nXBlockStart; nXBlock < nXBlockEnd;
     600             :                      ++nXBlock)
     601             :                 {
     602             :                     const int nValidX = std::min(
     603       34309 :                         m_nBlockXSize, nRasterXSize - nXBlock * m_nBlockXSize);
     604       34309 :                     if (nValidY < m_nBlockYSize || nValidX < m_nBlockXSize)
     605             :                     {
     606             :                         // Make sure padding bytes at the right/bottom of the
     607             :                         // tile are initialized to zero.
     608        1250 :                         memset(m_pabyBlockBuf, 0,
     609        1250 :                                static_cast<size_t>(m_nBlockXSize) *
     610        1250 :                                    m_nBlockYSize * nBands * nDTSize);
     611             :                     }
     612       34309 :                     const auto nBufDTSize = GDALGetDataTypeSizeBytes(eBufType);
     613       34309 :                     const GByte *pabySrcData =
     614             :                         static_cast<const GByte *>(pData) +
     615       34309 :                         static_cast<size_t>(nYBlock - nYBlockStart) *
     616       34309 :                             m_nBlockYSize * nLineSpace +
     617       34309 :                         static_cast<size_t>(nXBlock - nXBlockStart) *
     618       34309 :                             m_nBlockXSize * nPixelSpace;
     619       34309 :                     if (bOrderedBands && nBandSpace == nBufDTSize &&
     620          24 :                         nPixelSpace == nBands * nBandSpace)
     621             :                     {
     622             :                         // Input buffer is pixel interleaved
     623          17 :                         for (int iY = 0; iY < nValidY; ++iY)
     624             :                         {
     625          16 :                             GDALCopyWords64(
     626          16 :                                 pabySrcData +
     627          16 :                                     static_cast<size_t>(iY) * nLineSpace,
     628             :                                 eBufType, nBufDTSize,
     629          16 :                                 m_pabyBlockBuf + static_cast<size_t>(iY) *
     630          16 :                                                      m_nBlockXSize * nBands *
     631          16 :                                                      nDTSize,
     632             :                                 eDataType, nDTSize,
     633          16 :                                 static_cast<GPtrDiff_t>(nValidX) * nBands);
     634           1 :                         }
     635             :                     }
     636             :                     else
     637             :                     {
     638             :                         // "Random" spacing for input buffer
     639      139876 :                         for (int iBand = 0; iBand < nBands; ++iBand)
     640             :                         {
     641     4236000 :                             for (int iY = 0; iY < nValidY; ++iY)
     642             :                             {
     643     4130430 :                                 GDALCopyWords64(
     644     4130430 :                                     pabySrcData +
     645     4130430 :                                         static_cast<size_t>(iY) * nLineSpace,
     646             :                                     eBufType, static_cast<int>(nPixelSpace),
     647     4130430 :                                     m_pabyBlockBuf +
     648     4130430 :                                         (panBandMap[iBand] - 1 +
     649     4130430 :                                          static_cast<size_t>(iY) *
     650     4130430 :                                              m_nBlockXSize * nBands) *
     651     4130430 :                                             nDTSize,
     652     4130430 :                                     eDataType, nDTSize * nBands, nValidX);
     653             :                             }
     654      105568 :                             pabySrcData += nBandSpace;
     655             :                         }
     656             :                     }
     657             : 
     658             :                     const int nBlockId =
     659       34309 :                         poFirstBand->ComputeBlockId(nXBlock, nYBlock);
     660       68618 :                     if (WriteEncodedTileOrStrip(
     661       34309 :                             nBlockId, m_pabyBlockBuf,
     662       34309 :                             /* bPreserveDataBuffer= */ false) != CE_None)
     663             :                     {
     664           4 :                         return CE_Failure;
     665             :                     }
     666             :                 }
     667             :             }
     668        2354 :             return CE_None;
     669             :         }
     670             :     }
     671             : 
     672      431349 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     673      431189 :         ++m_nJPEGOverviewVisibilityCounter;
     674      431349 :     const CPLErr eErr = GDALPamDataset::IRasterIO(
     675             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
     676             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
     677             :         psExtraArg);
     678      431349 :     if (psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
     679      431189 :         m_nJPEGOverviewVisibilityCounter--;
     680             : 
     681      431349 :     if (pBufferedData)
     682             :     {
     683           8 :         VSIFree(pBufferedData);
     684           8 :         VSI_TIFFSetCachedRanges(TIFFClientdata(m_hTIFF), 0, nullptr, nullptr,
     685             :                                 nullptr);
     686             :     }
     687             : 
     688      431348 :     return eErr;
     689             : }
     690             : 
     691             : /************************************************************************/
     692             : /*                       GetGTIFFKeysFlavor()                           */
     693             : /************************************************************************/
     694             : 
     695       26605 : GTIFFKeysFlavorEnum GetGTIFFKeysFlavor(CSLConstList papszOptions)
     696             : {
     697             :     const char *pszGeoTIFFKeysFlavor =
     698       26605 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_KEYS_FLAVOR", "STANDARD");
     699       26527 :     if (EQUAL(pszGeoTIFFKeysFlavor, "ESRI_PE"))
     700           1 :         return GEOTIFF_KEYS_ESRI_PE;
     701       26526 :     return GEOTIFF_KEYS_STANDARD;
     702             : }
     703             : 
     704             : /************************************************************************/
     705             : /*                       GetGeoTIFFVersion()                            */
     706             : /************************************************************************/
     707             : 
     708       26512 : GeoTIFFVersionEnum GetGeoTIFFVersion(CSLConstList papszOptions)
     709             : {
     710             :     const char *pszVersion =
     711       26512 :         CSLFetchNameValueDef(papszOptions, "GEOTIFF_VERSION", "AUTO");
     712       26554 :     if (EQUAL(pszVersion, "1.0"))
     713           3 :         return GEOTIFF_VERSION_1_0;
     714       26551 :     if (EQUAL(pszVersion, "1.1"))
     715           5 :         return GEOTIFF_VERSION_1_1;
     716       26546 :     return GEOTIFF_VERSION_AUTO;
     717             : }
     718             : 
     719             : /************************************************************************/
     720             : /*                      InitCreationOrOpenOptions()                     */
     721             : /************************************************************************/
     722             : 
     723       25170 : void GTiffDataset::InitCreationOrOpenOptions(bool bUpdateMode,
     724             :                                              CSLConstList papszOptions)
     725             : {
     726       25170 :     InitCompressionThreads(bUpdateMode, papszOptions);
     727             : 
     728       25055 :     m_eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
     729       25046 :     m_eGeoTIFFVersion = GetGeoTIFFVersion(papszOptions);
     730       25007 : }
     731             : 
     732             : /************************************************************************/
     733             : /*                          IsBlockAvailable()                          */
     734             : /*                                                                      */
     735             : /*      Return true if the indicated strip/tile is available.  We       */
     736             : /*      establish this by testing if the stripbytecount is zero.  If    */
     737             : /*      zero then the block has never been committed to disk.           */
     738             : /************************************************************************/
     739             : 
     740     2301650 : bool GTiffDataset::IsBlockAvailable(int nBlockId, vsi_l_offset *pnOffset,
     741             :                                     vsi_l_offset *pnSize, bool *pbErrOccurred)
     742             : 
     743             : {
     744     2301650 :     if (pbErrOccurred)
     745     2256280 :         *pbErrOccurred = false;
     746             : 
     747     2301650 :     std::pair<vsi_l_offset, vsi_l_offset> oPair;
     748     2301650 :     if (m_oCacheStrileToOffsetByteCount.tryGet(nBlockId, oPair))
     749             :     {
     750         452 :         if (pnOffset)
     751         111 :             *pnOffset = oPair.first;
     752         452 :         if (pnSize)
     753           0 :             *pnSize = oPair.second;
     754         452 :         return oPair.first != 0;
     755             :     }
     756             : 
     757     2301110 :     WaitCompletionForBlock(nBlockId);
     758             : 
     759             :     // Optimization to avoid fetching the whole Strip/TileCounts and
     760             :     // Strip/TileOffsets arrays.
     761     2301110 :     if (eAccess == GA_ReadOnly && !m_bStreamingIn)
     762             :     {
     763     2184140 :         int nErrOccurred = 0;
     764             :         auto bytecount =
     765     2184140 :             TIFFGetStrileByteCountWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     766     2184180 :         if (nErrOccurred && pbErrOccurred)
     767           0 :             *pbErrOccurred = true;
     768     2184180 :         if (pnOffset)
     769             :         {
     770     2128820 :             *pnOffset =
     771     2128800 :                 TIFFGetStrileOffsetWithErr(m_hTIFF, nBlockId, &nErrOccurred);
     772     2128820 :             if (nErrOccurred && pbErrOccurred)
     773           2 :                 *pbErrOccurred = true;
     774             :         }
     775     2184190 :         if (pnSize)
     776       11949 :             *pnSize = bytecount;
     777     2184190 :         return bytecount != 0;
     778             :     }
     779             : 
     780      116976 :     toff_t *panByteCounts = nullptr;
     781      116976 :     toff_t *panOffsets = nullptr;
     782      116976 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
     783             : 
     784      150162 :     if ((bIsTiled &&
     785       33202 :          TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
     786       25056 :          (pnOffset == nullptr ||
     787      233920 :           TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets))) ||
     788       83758 :         (!bIsTiled &&
     789       83758 :          TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
     790       38635 :          (pnOffset == nullptr ||
     791       38635 :           TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
     792             :     {
     793      116960 :         if (panByteCounts == nullptr ||
     794       63691 :             (pnOffset != nullptr && panOffsets == nullptr))
     795             :         {
     796           0 :             if (pbErrOccurred)
     797           0 :                 *pbErrOccurred = true;
     798           0 :             return false;
     799             :         }
     800             :         const int nBlockCount =
     801      116960 :             bIsTiled ? TIFFNumberOfTiles(m_hTIFF) : TIFFNumberOfStrips(m_hTIFF);
     802      116960 :         if (nBlockId >= nBlockCount)
     803             :         {
     804           0 :             if (pbErrOccurred)
     805           0 :                 *pbErrOccurred = true;
     806           0 :             return false;
     807             :         }
     808             : 
     809      116960 :         if (pnOffset)
     810       63691 :             *pnOffset = panOffsets[nBlockId];
     811      116960 :         if (pnSize)
     812        7070 :             *pnSize = panByteCounts[nBlockId];
     813      116960 :         return panByteCounts[nBlockId] != 0;
     814             :     }
     815             :     else
     816             :     {
     817           0 :         if (pbErrOccurred)
     818           0 :             *pbErrOccurred = true;
     819             :     }
     820             : 
     821           0 :     return false;
     822             : }
     823             : 
     824             : /************************************************************************/
     825             : /*                           ReloadDirectory()                          */
     826             : /************************************************************************/
     827             : 
     828        6910 : void GTiffDataset::ReloadDirectory(bool bReopenHandle)
     829             : {
     830        6910 :     bool bNeedSetInvalidDir = true;
     831        6910 :     if (bReopenHandle)
     832             :     {
     833             :         // When issuing a TIFFRewriteDirectory() or when a TIFFFlush() has
     834             :         // caused a move of the directory, we would need to invalidate the
     835             :         // tif_lastdiroff member, but it is not possible to do so without
     836             :         // re-opening the TIFF handle.
     837           9 :         auto hTIFFNew = VSI_TIFFReOpen(m_hTIFF);
     838           9 :         if (hTIFFNew != nullptr)
     839             :         {
     840           9 :             m_hTIFF = hTIFFNew;
     841           9 :             bNeedSetInvalidDir = false;  // we could do it, but not needed
     842             :         }
     843             :         else
     844             :         {
     845           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     846             :                      "Cannot re-open TIFF handle for file %s. "
     847             :                      "Directory chaining may be corrupted !",
     848             :                      m_pszFilename);
     849             :         }
     850             :     }
     851        6910 :     if (bNeedSetInvalidDir)
     852             :     {
     853        6901 :         TIFFSetSubDirectory(m_hTIFF, 0);
     854             :     }
     855        6910 :     CPL_IGNORE_RET_VAL(SetDirectory());
     856        6910 : }
     857             : 
     858             : /************************************************************************/
     859             : /*                            SetDirectory()                            */
     860             : /************************************************************************/
     861             : 
     862       48009 : bool GTiffDataset::SetDirectory()
     863             : 
     864             : {
     865       48009 :     Crystalize();
     866             : 
     867       47944 :     if (TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
     868             :     {
     869       39245 :         return true;
     870             :     }
     871             : 
     872        8650 :     const int nSetDirResult = TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
     873        8650 :     if (!nSetDirResult)
     874           0 :         return false;
     875             : 
     876        8650 :     RestoreVolatileParameters(m_hTIFF);
     877             : 
     878        8649 :     return true;
     879             : }
     880             : 
     881             : /************************************************************************/
     882             : /*                     GTiffSetDeflateSubCodec()                        */
     883             : /************************************************************************/
     884             : 
     885        6397 : void GTiffSetDeflateSubCodec(TIFF *hTIFF)
     886             : {
     887             :     (void)hTIFF;
     888             : 
     889             : #if defined(TIFFTAG_DEFLATE_SUBCODEC) && defined(LIBDEFLATE_SUPPORT)
     890             :     // Mostly for strict reproducibility purposes
     891        6397 :     if (EQUAL(CPLGetConfigOption("GDAL_TIFF_DEFLATE_SUBCODEC", ""), "ZLIB"))
     892             :     {
     893        4097 :         TIFFSetField(hTIFF, TIFFTAG_DEFLATE_SUBCODEC, DEFLATE_SUBCODEC_ZLIB);
     894             :     }
     895             : #endif
     896        6397 : }
     897             : 
     898             : /************************************************************************/
     899             : /*                     RestoreVolatileParameters()                      */
     900             : /************************************************************************/
     901             : 
     902       41341 : void GTiffDataset::RestoreVolatileParameters(TIFF *hTIFF)
     903             : {
     904             : 
     905             :     /* -------------------------------------------------------------------- */
     906             :     /*      YCbCr JPEG compressed images should be translated on the fly    */
     907             :     /*      to RGB by libtiff/libjpeg unless specifically requested         */
     908             :     /*      otherwise.                                                      */
     909             :     /* -------------------------------------------------------------------- */
     910       83109 :     if (m_nCompression == COMPRESSION_JPEG &&
     911       41625 :         m_nPhotometric == PHOTOMETRIC_YCBCR &&
     912         285 :         CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
     913             :     {
     914         285 :         int nColorMode = JPEGCOLORMODE_RAW;  // Initialize to 0;
     915             : 
     916         285 :         TIFFGetField(hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode);
     917         285 :         if (nColorMode != JPEGCOLORMODE_RGB)
     918             :         {
     919         251 :             TIFFSetField(hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
     920             :         }
     921             :     }
     922             : 
     923       41340 :     if (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     924       35533 :         m_nCompression == COMPRESSION_LERC)
     925             :     {
     926        6044 :         GTiffSetDeflateSubCodec(hTIFF);
     927             :     }
     928             : 
     929             :     /* -------------------------------------------------------------------- */
     930             :     /*      Propagate any quality settings.                                 */
     931             :     /* -------------------------------------------------------------------- */
     932       41338 :     if (eAccess == GA_Update)
     933             :     {
     934             :         // Now, reset zip and jpeg quality.
     935       35153 :         if (m_nJpegQuality > 0 && m_nCompression == COMPRESSION_JPEG)
     936             :         {
     937             : #ifdef DEBUG_VERBOSE
     938             :             CPLDebug("GTiff", "Propagate JPEG_QUALITY(%d) in SetDirectory()",
     939             :                      m_nJpegQuality);
     940             : #endif
     941         185 :             TIFFSetField(hTIFF, TIFFTAG_JPEGQUALITY, m_nJpegQuality);
     942             :         }
     943       35153 :         if (m_nJpegTablesMode >= 0 && m_nCompression == COMPRESSION_JPEG)
     944         326 :             TIFFSetField(hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
     945       35153 :         if (m_nZLevel > 0 && (m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
     946          12 :                               m_nCompression == COMPRESSION_LERC))
     947          26 :             TIFFSetField(hTIFF, TIFFTAG_ZIPQUALITY, m_nZLevel);
     948       35153 :         if (m_nLZMAPreset > 0 && m_nCompression == COMPRESSION_LZMA)
     949           8 :             TIFFSetField(hTIFF, TIFFTAG_LZMAPRESET, m_nLZMAPreset);
     950       35153 :         if (m_nZSTDLevel > 0 && (m_nCompression == COMPRESSION_ZSTD ||
     951          12 :                                  m_nCompression == COMPRESSION_LERC))
     952          18 :             TIFFSetField(hTIFF, TIFFTAG_ZSTD_LEVEL, m_nZSTDLevel);
     953       35153 :         if (m_nCompression == COMPRESSION_LERC)
     954             :         {
     955         185 :             TIFFSetField(hTIFF, TIFFTAG_LERC_MAXZERROR, m_dfMaxZError);
     956             :         }
     957       35153 :         if (m_nWebPLevel > 0 && m_nCompression == COMPRESSION_WEBP)
     958         124 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LEVEL, m_nWebPLevel);
     959       35153 :         if (m_bWebPLossless && m_nCompression == COMPRESSION_WEBP)
     960          50 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
     961             : #ifdef HAVE_JXL
     962       35153 :         if (m_nCompression == COMPRESSION_JXL ||
     963       35151 :             m_nCompression == COMPRESSION_JXL_DNG_1_7)
     964             :         {
     965          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_LOSSYNESS,
     966          76 :                          m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
     967          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_EFFORT, m_nJXLEffort);
     968          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_DISTANCE, m_fJXLDistance);
     969          76 :             TIFFSetField(hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
     970          76 :                          m_fJXLAlphaDistance);
     971             :         }
     972             : #endif
     973             :     }
     974       41338 : }
     975             : 
     976             : /************************************************************************/
     977             : /*                     ComputeBlocksPerColRowAndBand()                  */
     978             : /************************************************************************/
     979             : 
     980       26941 : bool GTiffDataset::ComputeBlocksPerColRowAndBand(int l_nBands)
     981             : {
     982       26941 :     m_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, m_nBlockYSize);
     983       26941 :     m_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, m_nBlockXSize);
     984       26941 :     if (m_nBlocksPerColumn > INT_MAX / m_nBlocksPerRow)
     985             :     {
     986           1 :         ReportError(CE_Failure, CPLE_AppDefined, "Too many blocks: %d x %d",
     987             :                     m_nBlocksPerRow, m_nBlocksPerColumn);
     988           1 :         return false;
     989             :     }
     990             : 
     991             :     // Note: we could potentially go up to UINT_MAX blocks, but currently
     992             :     // we use a int nBlockId
     993       26940 :     m_nBlocksPerBand = m_nBlocksPerColumn * m_nBlocksPerRow;
     994       26940 :     if (m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
     995        1695 :         m_nBlocksPerBand > INT_MAX / l_nBands)
     996             :     {
     997           1 :         ReportError(CE_Failure, CPLE_AppDefined,
     998             :                     "Too many blocks: %d x %d x %d bands", m_nBlocksPerRow,
     999             :                     m_nBlocksPerColumn, l_nBands);
    1000           1 :         return false;
    1001             :     }
    1002       26939 :     return true;
    1003             : }
    1004             : 
    1005             : /************************************************************************/
    1006             : /*                   SetStructuralMDFromParent()                        */
    1007             : /************************************************************************/
    1008             : 
    1009        1116 : void GTiffDataset::SetStructuralMDFromParent(GTiffDataset *poParentDS)
    1010             : {
    1011        1116 :     m_bBlockOrderRowMajor = poParentDS->m_bBlockOrderRowMajor;
    1012        1116 :     m_bLeaderSizeAsUInt4 = poParentDS->m_bLeaderSizeAsUInt4;
    1013        1116 :     m_bTrailerRepeatedLast4BytesRepeated =
    1014        1116 :         poParentDS->m_bTrailerRepeatedLast4BytesRepeated;
    1015        1116 :     m_bMaskInterleavedWithImagery = poParentDS->m_bMaskInterleavedWithImagery;
    1016        1116 :     m_bWriteEmptyTiles = poParentDS->m_bWriteEmptyTiles;
    1017        1116 :     m_bTileInterleave = poParentDS->m_bTileInterleave;
    1018        1116 : }
    1019             : 
    1020             : /************************************************************************/
    1021             : /*                          ScanDirectories()                           */
    1022             : /*                                                                      */
    1023             : /*      Scan through all the directories finding overviews, masks       */
    1024             : /*      and subdatasets.                                                */
    1025             : /************************************************************************/
    1026             : 
    1027      806535 : void GTiffDataset::ScanDirectories()
    1028             : 
    1029             : {
    1030             :     /* -------------------------------------------------------------------- */
    1031             :     /*      We only scan once.  We do not scan for non-base datasets.       */
    1032             :     /* -------------------------------------------------------------------- */
    1033      806535 :     if (!m_bScanDeferred)
    1034      798847 :         return;
    1035             : 
    1036        8004 :     m_bScanDeferred = false;
    1037             : 
    1038        8004 :     if (m_poBaseDS)
    1039         316 :         return;
    1040             : 
    1041        7688 :     Crystalize();
    1042             : 
    1043        6261 :     CPLDebug("GTiff", "ScanDirectories()");
    1044             : 
    1045             :     /* ==================================================================== */
    1046             :     /*      Scan all directories.                                           */
    1047             :     /* ==================================================================== */
    1048       12522 :     CPLStringList aosSubdatasets;
    1049        6261 :     int iDirIndex = 0;
    1050             : 
    1051        6261 :     FlushDirectory();
    1052             : 
    1053        1103 :     do
    1054             :     {
    1055        7364 :         toff_t nTopDir = TIFFCurrentDirOffset(m_hTIFF);
    1056        7364 :         uint32_t nSubType = 0;
    1057             : 
    1058        7364 :         ++iDirIndex;
    1059             : 
    1060        7364 :         toff_t *tmpSubIFDOffsets = nullptr;
    1061        7364 :         toff_t *subIFDOffsets = nullptr;
    1062        7364 :         uint16_t nSubIFDs = 0;
    1063        7364 :         if (TIFFGetField(m_hTIFF, TIFFTAG_SUBIFD, &nSubIFDs,
    1064        7364 :                          &tmpSubIFDOffsets) &&
    1065             :             iDirIndex == 1)
    1066             :         {
    1067             :             subIFDOffsets =
    1068          13 :                 static_cast<toff_t *>(CPLMalloc(nSubIFDs * sizeof(toff_t)));
    1069          39 :             for (uint16_t iSubIFD = 0; iSubIFD < nSubIFDs; iSubIFD++)
    1070             :             {
    1071          26 :                 subIFDOffsets[iSubIFD] = tmpSubIFDOffsets[iSubIFD];
    1072             :             }
    1073             :         }
    1074             : 
    1075             :         // early break for backwards compatibility: if the first directory read
    1076             :         // is also the last, and there are no subIFDs, no use continuing
    1077        7364 :         if (iDirIndex == 1 && nSubIFDs == 0 && TIFFLastDirectory(m_hTIFF))
    1078             :         {
    1079        5617 :             CPLFree(subIFDOffsets);
    1080        5617 :             break;
    1081             :         }
    1082             : 
    1083        3520 :         for (uint16_t iSubIFD = 0; iSubIFD <= nSubIFDs; iSubIFD++)
    1084             :         {
    1085        1781 :             toff_t nThisDir = nTopDir;
    1086        1781 :             if (iSubIFD > 0 && iDirIndex > 1)  // don't read subIFDs if we are
    1087             :                                                // not in the original directory
    1088           8 :                 break;
    1089        1773 :             if (iSubIFD > 0)
    1090             :             {
    1091             :                 // make static analyzer happy. subIFDOffsets cannot be null if
    1092             :                 // iSubIFD>0
    1093          26 :                 assert(subIFDOffsets != nullptr);
    1094          26 :                 nThisDir = subIFDOffsets[iSubIFD - 1];
    1095             :                 // CPLDebug("GTiff", "Opened subIFD %d/%d at offset %llu.",
    1096             :                 // iSubIFD, nSubIFDs, nThisDir);
    1097          26 :                 if (!TIFFSetSubDirectory(m_hTIFF, nThisDir))
    1098           0 :                     break;
    1099             :             }
    1100             : 
    1101        1773 :             if (!TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
    1102         399 :                 nSubType = 0;
    1103             : 
    1104             :             /* Embedded overview of the main image */
    1105        1773 :             if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1106        1267 :                 (nSubType & FILETYPE_MASK) == 0 &&
    1107        1161 :                 ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1108         903 :                 m_nOverviewCount < 30 /* to avoid DoS */)
    1109             :             {
    1110         903 :                 GTiffDataset *poODS = new GTiffDataset();
    1111         903 :                 poODS->ShareLockWithParentDataset(this);
    1112         903 :                 poODS->SetStructuralMDFromParent(this);
    1113         903 :                 if (m_bHasGotSiblingFiles)
    1114         171 :                     poODS->oOvManager.TransferSiblingFiles(
    1115             :                         CSLDuplicate(GetSiblingFiles()));
    1116         903 :                 poODS->m_pszFilename = CPLStrdup(m_pszFilename);
    1117         903 :                 poODS->m_nColorTableMultiplier = m_nColorTableMultiplier;
    1118         903 :                 if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1119        1806 :                                       eAccess) != CE_None ||
    1120         903 :                     poODS->GetRasterCount() != GetRasterCount())
    1121             :                 {
    1122           0 :                     delete poODS;
    1123             :                 }
    1124             :                 else
    1125             :                 {
    1126         903 :                     CPLDebug("GTiff", "Opened %dx%d overview.",
    1127             :                              poODS->GetRasterXSize(), poODS->GetRasterYSize());
    1128         903 :                     ++m_nOverviewCount;
    1129        1806 :                     m_papoOverviewDS = static_cast<GTiffDataset **>(CPLRealloc(
    1130         903 :                         m_papoOverviewDS, m_nOverviewCount * (sizeof(void *))));
    1131         903 :                     m_papoOverviewDS[m_nOverviewCount - 1] = poODS;
    1132         903 :                     poODS->m_poBaseDS = this;
    1133         903 :                     poODS->m_bIsOverview = true;
    1134             : 
    1135             :                     // Propagate a few compression related settings that are
    1136             :                     // no preserved at the TIFF tag level, but may be set in
    1137             :                     // the GDAL_METADATA tag in the IMAGE_STRUCTURE domain
    1138             :                     // Note: this might not be totally reflecting the reality
    1139             :                     // if users have created overviews with different settings
    1140             :                     // but this is probably better than the default ones
    1141         903 :                     poODS->m_nWebPLevel = m_nWebPLevel;
    1142             :                     // below is not a copy & paste error: we transfer the
    1143             :                     // m_dfMaxZErrorOverview overview of the parent to
    1144             :                     // m_dfMaxZError of the overview
    1145         903 :                     poODS->m_dfMaxZError = m_dfMaxZErrorOverview;
    1146         903 :                     poODS->m_dfMaxZErrorOverview = m_dfMaxZErrorOverview;
    1147             : #if HAVE_JXL
    1148         903 :                     poODS->m_bJXLLossless = m_bJXLLossless;
    1149         903 :                     poODS->m_fJXLDistance = m_fJXLDistance;
    1150         903 :                     poODS->m_fJXLAlphaDistance = m_fJXLAlphaDistance;
    1151         903 :                     poODS->m_nJXLEffort = m_nJXLEffort;
    1152             : #endif
    1153             :                     // Those ones are not serialized currently..
    1154             :                     // poODS->m_nZLevel = m_nZLevel;
    1155             :                     // poODS->m_nLZMAPreset = m_nLZMAPreset;
    1156             :                     // poODS->m_nZSTDLevel = m_nZSTDLevel;
    1157         903 :                 }
    1158             :             }
    1159             :             // Embedded mask of the main image.
    1160         870 :             else if ((nSubType & FILETYPE_MASK) != 0 &&
    1161         213 :                      (nSubType & FILETYPE_REDUCEDIMAGE) == 0 &&
    1162         107 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0) &&
    1163         107 :                      m_poMaskDS == nullptr)
    1164             :             {
    1165         107 :                 m_poMaskDS = new GTiffDataset();
    1166         107 :                 m_poMaskDS->ShareLockWithParentDataset(this);
    1167         107 :                 m_poMaskDS->SetStructuralMDFromParent(this);
    1168         107 :                 m_poMaskDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1169             : 
    1170             :                 // The TIFF6 specification - page 37 - only allows 1
    1171             :                 // SamplesPerPixel and 1 BitsPerSample Here we support either 1
    1172             :                 // or 8 bit per sample and we support either 1 sample per pixel
    1173             :                 // or as many samples as in the main image We don't check the
    1174             :                 // value of the PhotometricInterpretation tag, which should be
    1175             :                 // set to "Transparency mask" (4) according to the specification
    1176             :                 // (page 36).  However, the TIFF6 specification allows image
    1177             :                 // masks to have a higher resolution than the main image, what
    1178             :                 // we don't support here.
    1179             : 
    1180         107 :                 if (m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1181         107 :                                            eAccess) != CE_None ||
    1182         107 :                     m_poMaskDS->GetRasterCount() == 0 ||
    1183         107 :                     !(m_poMaskDS->GetRasterCount() == 1 ||
    1184           3 :                       m_poMaskDS->GetRasterCount() == GetRasterCount()) ||
    1185         107 :                     m_poMaskDS->GetRasterXSize() != GetRasterXSize() ||
    1186         321 :                     m_poMaskDS->GetRasterYSize() != GetRasterYSize() ||
    1187         107 :                     m_poMaskDS->GetRasterBand(1)->GetRasterDataType() !=
    1188             :                         GDT_Byte)
    1189             :                 {
    1190           0 :                     delete m_poMaskDS;
    1191           0 :                     m_poMaskDS = nullptr;
    1192             :                 }
    1193             :                 else
    1194             :                 {
    1195         107 :                     CPLDebug("GTiff", "Opened band mask.");
    1196         107 :                     m_poMaskDS->m_poBaseDS = this;
    1197         107 :                     m_poMaskDS->m_poImageryDS = this;
    1198             : 
    1199         214 :                     m_poMaskDS->m_bPromoteTo8Bits =
    1200         107 :                         CPLTestBool(CPLGetConfigOption(
    1201             :                             "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1202             :                 }
    1203             :             }
    1204             : 
    1205             :             // Embedded mask of an overview.  The TIFF6 specification allows the
    1206             :             // combination of the FILETYPE_xxxx masks.
    1207         763 :             else if ((nSubType & FILETYPE_REDUCEDIMAGE) != 0 &&
    1208         364 :                      (nSubType & FILETYPE_MASK) != 0 &&
    1209         106 :                      ((nSubIFDs == 0 && iDirIndex != 1) || iSubIFD > 0))
    1210             :             {
    1211         106 :                 GTiffDataset *poDS = new GTiffDataset();
    1212         106 :                 poDS->ShareLockWithParentDataset(this);
    1213         106 :                 poDS->SetStructuralMDFromParent(this);
    1214         106 :                 poDS->m_pszFilename = CPLStrdup(m_pszFilename);
    1215         106 :                 if (poDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nThisDir,
    1216         106 :                                      eAccess) != CE_None ||
    1217         212 :                     poDS->GetRasterCount() == 0 ||
    1218         106 :                     poDS->GetRasterBand(1)->GetRasterDataType() != GDT_Byte)
    1219             :                 {
    1220           0 :                     delete poDS;
    1221             :                 }
    1222             :                 else
    1223             :                 {
    1224         106 :                     int i = 0;  // Used after for.
    1225         158 :                     for (; i < m_nOverviewCount; ++i)
    1226             :                     {
    1227         158 :                         auto poOvrDS = cpl::down_cast<GTiffDataset *>(
    1228         158 :                             GDALDataset::FromHandle(m_papoOverviewDS[i]));
    1229         422 :                         if (poOvrDS->m_poMaskDS == nullptr &&
    1230         106 :                             poDS->GetRasterXSize() ==
    1231         106 :                                 m_papoOverviewDS[i]->GetRasterXSize() &&
    1232         106 :                             poDS->GetRasterYSize() ==
    1233         370 :                                 m_papoOverviewDS[i]->GetRasterYSize() &&
    1234         106 :                             (poDS->GetRasterCount() == 1 ||
    1235           0 :                              poDS->GetRasterCount() == GetRasterCount()))
    1236             :                         {
    1237         106 :                             CPLDebug(
    1238             :                                 "GTiff", "Opened band mask for %dx%d overview.",
    1239             :                                 poDS->GetRasterXSize(), poDS->GetRasterYSize());
    1240         106 :                             poDS->m_poImageryDS = poOvrDS;
    1241         106 :                             poOvrDS->m_poMaskDS = poDS;
    1242         106 :                             poDS->m_bPromoteTo8Bits =
    1243         106 :                                 CPLTestBool(CPLGetConfigOption(
    1244             :                                     "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    1245         106 :                             poDS->m_poBaseDS = this;
    1246         106 :                             break;
    1247             :                         }
    1248             :                     }
    1249         106 :                     if (i == m_nOverviewCount)
    1250             :                     {
    1251           0 :                         delete poDS;
    1252             :                     }
    1253         106 :                 }
    1254             :             }
    1255         657 :             else if (!m_bSingleIFDOpened &&
    1256         652 :                      (nSubType == 0 || nSubType == FILETYPE_PAGE))
    1257             :             {
    1258         394 :                 uint32_t nXSize = 0;
    1259         394 :                 uint32_t nYSize = 0;
    1260             : 
    1261         394 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
    1262         394 :                 TIFFGetField(m_hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
    1263             : 
    1264             :                 // For Geodetic TIFF grids (GTG)
    1265             :                 // (https://proj.org/specifications/geodetictiffgrids.html)
    1266             :                 // extract the grid_name to put it in the description
    1267         788 :                 std::string osFriendlyName;
    1268         394 :                 char *pszText = nullptr;
    1269         458 :                 if (TIFFGetField(m_hTIFF, TIFFTAG_GDAL_METADATA, &pszText) &&
    1270          64 :                     strstr(pszText, "grid_name") != nullptr)
    1271             :                 {
    1272           4 :                     CPLXMLNode *psRoot = CPLParseXMLString(pszText);
    1273             :                     const CPLXMLNode *psItem =
    1274           4 :                         psRoot ? CPLGetXMLNode(psRoot, "=GDALMetadata")
    1275           4 :                                : nullptr;
    1276           4 :                     if (psItem)
    1277           4 :                         psItem = psItem->psChild;
    1278           4 :                     for (; psItem != nullptr; psItem = psItem->psNext)
    1279             :                     {
    1280             : 
    1281           4 :                         if (psItem->eType != CXT_Element ||
    1282           4 :                             !EQUAL(psItem->pszValue, "Item"))
    1283           0 :                             continue;
    1284             : 
    1285             :                         const char *pszKey =
    1286           4 :                             CPLGetXMLValue(psItem, "name", nullptr);
    1287             :                         const char *pszValue =
    1288           4 :                             CPLGetXMLValue(psItem, nullptr, nullptr);
    1289             :                         int nBand =
    1290           4 :                             atoi(CPLGetXMLValue(psItem, "sample", "-1"));
    1291           4 :                         if (pszKey && pszValue && nBand <= 0 &&
    1292           4 :                             EQUAL(pszKey, "grid_name"))
    1293             :                         {
    1294           4 :                             osFriendlyName = ": ";
    1295           4 :                             osFriendlyName += pszValue;
    1296           4 :                             break;
    1297             :                         }
    1298             :                     }
    1299             : 
    1300           4 :                     CPLDestroyXMLNode(psRoot);
    1301             :                 }
    1302             : 
    1303         394 :                 if (nXSize > INT_MAX || nYSize > INT_MAX)
    1304             :                 {
    1305           1 :                     CPLDebug("GTiff",
    1306             :                              "Skipping directory with too large image: %u x %u",
    1307             :                              nXSize, nYSize);
    1308             :                 }
    1309             :                 else
    1310             :                 {
    1311         393 :                     uint16_t nSPP = 0;
    1312         393 :                     if (!TIFFGetField(m_hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSPP))
    1313           0 :                         nSPP = 1;
    1314             : 
    1315         786 :                     CPLString osName, osDesc;
    1316             :                     osName.Printf("SUBDATASET_%d_NAME=GTIFF_DIR:%d:%s",
    1317         393 :                                   iDirIndex, iDirIndex, m_pszFilename);
    1318             :                     osDesc.Printf(
    1319             :                         "SUBDATASET_%d_DESC=Page %d (%dP x %dL x %dB)",
    1320             :                         iDirIndex, iDirIndex, static_cast<int>(nXSize),
    1321         393 :                         static_cast<int>(nYSize), nSPP);
    1322         393 :                     osDesc += osFriendlyName;
    1323             : 
    1324         393 :                     aosSubdatasets.AddString(osName);
    1325         393 :                     aosSubdatasets.AddString(osDesc);
    1326             :                 }
    1327             :             }
    1328             :         }
    1329        1747 :         CPLFree(subIFDOffsets);
    1330             : 
    1331             :         // Make sure we are stepping from the expected directory regardless
    1332             :         // of churn done processing the above.
    1333        1747 :         if (TIFFCurrentDirOffset(m_hTIFF) != nTopDir)
    1334          13 :             TIFFSetSubDirectory(m_hTIFF, nTopDir);
    1335        2850 :     } while (!m_bSingleIFDOpened && !TIFFLastDirectory(m_hTIFF) &&
    1336        1103 :              TIFFReadDirectory(m_hTIFF) != 0);
    1337             : 
    1338        6261 :     ReloadDirectory();
    1339             : 
    1340             :     // If we have a mask for the main image, loop over the overviews, and if
    1341             :     // they have a mask, let's set this mask as an overview of the main mask.
    1342        6260 :     if (m_poMaskDS != nullptr)
    1343             :     {
    1344         213 :         for (int i = 0; i < m_nOverviewCount; ++i)
    1345             :         {
    1346         106 :             if (cpl::down_cast<GTiffDataset *>(
    1347         106 :                     GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1348         106 :                     ->m_poMaskDS != nullptr)
    1349             :             {
    1350         106 :                 ++m_poMaskDS->m_nOverviewCount;
    1351         212 :                 m_poMaskDS->m_papoOverviewDS =
    1352         212 :                     static_cast<GTiffDataset **>(CPLRealloc(
    1353         106 :                         m_poMaskDS->m_papoOverviewDS,
    1354         106 :                         m_poMaskDS->m_nOverviewCount * (sizeof(void *))));
    1355         106 :                 m_poMaskDS->m_papoOverviewDS[m_poMaskDS->m_nOverviewCount - 1] =
    1356         106 :                     cpl::down_cast<GTiffDataset *>(
    1357         106 :                         GDALDataset::FromHandle(m_papoOverviewDS[i]))
    1358         106 :                         ->m_poMaskDS;
    1359             :             }
    1360             :         }
    1361             :     }
    1362             : 
    1363             :     // Assign color interpretation from main dataset
    1364        6260 :     const int l_nBands = GetRasterCount();
    1365        7163 :     for (int iOvr = 0; iOvr < m_nOverviewCount; ++iOvr)
    1366             :     {
    1367        2517 :         for (int i = 1; i <= l_nBands; i++)
    1368             :         {
    1369           0 :             auto poBand = dynamic_cast<GTiffRasterBand *>(
    1370        1615 :                 m_papoOverviewDS[iOvr]->GetRasterBand(i));
    1371        1615 :             if (poBand)
    1372        1614 :                 poBand->m_eBandInterp =
    1373        1615 :                     GetRasterBand(i)->GetColorInterpretation();
    1374             :         }
    1375             :     }
    1376             : 
    1377             :     /* -------------------------------------------------------------------- */
    1378             :     /*      Only keep track of subdatasets if we have more than one         */
    1379             :     /*      subdataset (pair).                                              */
    1380             :     /* -------------------------------------------------------------------- */
    1381        6260 :     if (aosSubdatasets.size() > 2)
    1382             :     {
    1383          10 :         m_oGTiffMDMD.SetMetadata(aosSubdatasets.List(), "SUBDATASETS");
    1384             :     }
    1385             : }
    1386             : 
    1387             : /************************************************************************/
    1388             : /*                         GetInternalHandle()                          */
    1389             : /************************************************************************/
    1390             : 
    1391        2150 : void *GTiffDataset::GetInternalHandle(const char * /* pszHandleName */)
    1392             : 
    1393             : {
    1394        2150 :     return m_hTIFF;
    1395             : }
    1396             : 
    1397             : /************************************************************************/
    1398             : /*                            GetFileList()                             */
    1399             : /************************************************************************/
    1400             : 
    1401        2454 : char **GTiffDataset::GetFileList()
    1402             : 
    1403             : {
    1404        2454 :     LoadGeoreferencingAndPamIfNeeded();
    1405             : 
    1406        2454 :     char **papszFileList = GDALPamDataset::GetFileList();
    1407             : 
    1408        2454 :     LoadMetadata();
    1409        2454 :     if (nullptr != m_papszMetadataFiles)
    1410             :     {
    1411          77 :         for (int i = 0; m_papszMetadataFiles[i] != nullptr; ++i)
    1412             :         {
    1413          44 :             if (CSLFindString(papszFileList, m_papszMetadataFiles[i]) < 0)
    1414             :             {
    1415             :                 papszFileList =
    1416          44 :                     CSLAddString(papszFileList, m_papszMetadataFiles[i]);
    1417             :             }
    1418             :         }
    1419             :     }
    1420             : 
    1421        2460 :     if (m_pszGeorefFilename &&
    1422           6 :         CSLFindString(papszFileList, m_pszGeorefFilename) == -1)
    1423             :     {
    1424           6 :         papszFileList = CSLAddString(papszFileList, m_pszGeorefFilename);
    1425             :     }
    1426             : 
    1427        2454 :     if (m_nXMLGeorefSrcIndex >= 0)
    1428        2454 :         LookForProjection();
    1429             : 
    1430        2455 :     if (m_pszXMLFilename &&
    1431           1 :         CSLFindString(papszFileList, m_pszXMLFilename) == -1)
    1432             :     {
    1433           1 :         papszFileList = CSLAddString(papszFileList, m_pszXMLFilename);
    1434             :     }
    1435             : 
    1436        2454 :     return papszFileList;
    1437             : }
    1438             : 
    1439             : /************************************************************************/
    1440             : /*                        GetRawBinaryLayout()                          */
    1441             : /************************************************************************/
    1442             : 
    1443           9 : bool GTiffDataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
    1444             : {
    1445           9 :     if (eAccess == GA_Update)
    1446             :     {
    1447           3 :         FlushCache(false);
    1448           3 :         Crystalize();
    1449             :     }
    1450             : 
    1451           9 :     if (m_nCompression != COMPRESSION_NONE)
    1452           1 :         return false;
    1453           8 :     if (!CPLIsPowerOfTwo(m_nBitsPerSample) || m_nBitsPerSample < 8)
    1454           0 :         return false;
    1455           8 :     const auto eDT = GetRasterBand(1)->GetRasterDataType();
    1456           8 :     if (GDALDataTypeIsComplex(eDT))
    1457           0 :         return false;
    1458             : 
    1459           8 :     toff_t *panByteCounts = nullptr;
    1460           8 :     toff_t *panOffsets = nullptr;
    1461           8 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(m_hTIFF));
    1462             : 
    1463          16 :     if (!((bIsTiled &&
    1464           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts) &&
    1465           3 :            TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panOffsets)) ||
    1466           5 :           (!bIsTiled &&
    1467           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts) &&
    1468           5 :            TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panOffsets))))
    1469             :     {
    1470           0 :         return false;
    1471             :     }
    1472             : 
    1473           8 :     const int nDTSize = GDALGetDataTypeSizeBytes(eDT);
    1474           8 :     vsi_l_offset nImgOffset = panOffsets[0];
    1475          16 :     GIntBig nPixelOffset = (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1476           8 :                                ? static_cast<GIntBig>(nDTSize) * nBands
    1477             :                                : nDTSize;
    1478           8 :     GIntBig nLineOffset = nPixelOffset * nRasterXSize;
    1479           8 :     GIntBig nBandOffset =
    1480           8 :         (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1) ? nDTSize : 0;
    1481           8 :     RawBinaryLayout::Interleaving eInterleaving =
    1482          12 :         (nBands == 1) ? RawBinaryLayout::Interleaving::UNKNOWN
    1483           4 :         : (m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1484           4 :             ? RawBinaryLayout::Interleaving::BIP
    1485             :             : RawBinaryLayout::Interleaving::BSQ;
    1486           8 :     if (bIsTiled)
    1487             :     {
    1488             :         // Only a single block tiled file with same dimension as the raster
    1489             :         // might be acceptable
    1490           3 :         if (m_nBlockXSize != nRasterXSize || m_nBlockYSize != nRasterYSize)
    1491           1 :             return false;
    1492           2 :         if (nBands > 1 && m_nPlanarConfig != PLANARCONFIG_CONTIG)
    1493             :         {
    1494           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[1]) -
    1495           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1496           2 :             for (int i = 2; i < nBands; i++)
    1497             :             {
    1498           1 :                 if (static_cast<GIntBig>(panOffsets[i]) -
    1499           1 :                         static_cast<GIntBig>(panOffsets[i - 1]) !=
    1500             :                     nBandOffset)
    1501           0 :                     return false;
    1502             :             }
    1503             :         }
    1504             :     }
    1505             :     else
    1506             :     {
    1507           5 :         const int nStrips = DIV_ROUND_UP(nRasterYSize, m_nRowsPerStrip);
    1508           5 :         if (nBands == 1 || m_nPlanarConfig == PLANARCONFIG_CONTIG)
    1509             :         {
    1510           4 :             vsi_l_offset nLastStripEnd = panOffsets[0] + panByteCounts[0];
    1511          16 :             for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1512             :             {
    1513          12 :                 if (nLastStripEnd != panOffsets[iStrip])
    1514           0 :                     return false;
    1515          12 :                 nLastStripEnd = panOffsets[iStrip] + panByteCounts[iStrip];
    1516           4 :             }
    1517             :         }
    1518             :         else
    1519             :         {
    1520             :             // Note: we could potentially have BIL order with m_nRowsPerStrip ==
    1521             :             // 1 and if strips are ordered strip_line_1_band_1, ...,
    1522             :             // strip_line_1_band_N, strip_line2_band1, ... strip_line2_band_N,
    1523             :             // etc.... but that'd be faily exotic ! So only detect BSQ layout
    1524             :             // here
    1525           1 :             nBandOffset = static_cast<GIntBig>(panOffsets[nStrips]) -
    1526           1 :                           static_cast<GIntBig>(panOffsets[0]);
    1527           4 :             for (int i = 0; i < nBands; i++)
    1528             :             {
    1529           3 :                 uint32_t iStripOffset = nStrips * i;
    1530           3 :                 vsi_l_offset nLastStripEnd =
    1531           3 :                     panOffsets[iStripOffset] + panByteCounts[iStripOffset];
    1532           3 :                 for (int iStrip = 1; iStrip < nStrips; iStrip++)
    1533             :                 {
    1534           0 :                     if (nLastStripEnd != panOffsets[iStripOffset + iStrip])
    1535           0 :                         return false;
    1536           0 :                     nLastStripEnd = panOffsets[iStripOffset + iStrip] +
    1537           0 :                                     panByteCounts[iStripOffset + iStrip];
    1538             :                 }
    1539           3 :                 if (i >= 2 && static_cast<GIntBig>(panOffsets[iStripOffset]) -
    1540           1 :                                       static_cast<GIntBig>(
    1541           1 :                                           panOffsets[iStripOffset - nStrips]) !=
    1542             :                                   nBandOffset)
    1543             :                 {
    1544           0 :                     return false;
    1545             :                 }
    1546             :             }
    1547             :         }
    1548             :     }
    1549             : 
    1550           7 :     sLayout.osRawFilename = m_pszFilename;
    1551           7 :     sLayout.eInterleaving = eInterleaving;
    1552           7 :     sLayout.eDataType = eDT;
    1553             : #ifdef CPL_LSB
    1554           7 :     sLayout.bLittleEndianOrder = !TIFFIsByteSwapped(m_hTIFF);
    1555             : #else
    1556             :     sLayout.bLittleEndianOrder = TIFFIsByteSwapped(m_hTIFF);
    1557             : #endif
    1558           7 :     sLayout.nImageOffset = nImgOffset;
    1559           7 :     sLayout.nPixelOffset = nPixelOffset;
    1560           7 :     sLayout.nLineOffset = nLineOffset;
    1561           7 :     sLayout.nBandOffset = nBandOffset;
    1562             : 
    1563           7 :     return true;
    1564             : }
    1565             : 
    1566             : /************************************************************************/
    1567             : /*               GTiffDatasetLibGeotiffErrorCallback()                  */
    1568             : /************************************************************************/
    1569             : 
    1570           0 : static void GTiffDatasetLibGeotiffErrorCallback(GTIF *, int level,
    1571             :                                                 const char *pszMsg, ...)
    1572             : {
    1573             :     va_list ap;
    1574           0 :     va_start(ap, pszMsg);
    1575           0 :     CPLErrorV((level == LIBGEOTIFF_WARNING) ? CE_Warning : CE_Failure,
    1576             :               CPLE_AppDefined, pszMsg, ap);
    1577           0 :     va_end(ap);
    1578           0 : }
    1579             : 
    1580             : /************************************************************************/
    1581             : /*                           GTIFNew()                                  */
    1582             : /************************************************************************/
    1583             : 
    1584       26720 : /* static */ GTIF *GTiffDataset::GTIFNew(TIFF *hTIFF)
    1585             : {
    1586       26720 :     GTIF *gtif = GTIFNewEx(hTIFF, GTiffDatasetLibGeotiffErrorCallback, nullptr);
    1587       26720 :     if (gtif)
    1588             :     {
    1589       26720 :         GTIFAttachPROJContext(gtif, OSRGetProjTLSContext());
    1590             :     }
    1591       26720 :     return gtif;
    1592             : }

Generated by: LCOV version 1.14