LCOV - code coverage report
Current view: top level - gcore - gdal_misc.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1848 2413 76.6 %
Date: 2025-05-31 00:00:17 Functions: 90 97 92.8 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL Core
       4             :  * Purpose:  Free standing functions for GDAL.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1999, Frank Warmerdam
       9             :  * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "cpl_port.h"
      15             : 
      16             : #include <cctype>
      17             : #include <cerrno>
      18             : #include <clocale>
      19             : #include <cmath>
      20             : #include <cstddef>
      21             : #include <cstdio>
      22             : #include <cstdlib>
      23             : #include <cstring>
      24             : #include <fcntl.h>
      25             : 
      26             : #include <algorithm>
      27             : #include <iostream>
      28             : #include <limits>
      29             : #include <string>
      30             : 
      31             : #include "cpl_conv.h"
      32             : #include "cpl_error.h"
      33             : #include "cpl_float.h"
      34             : #include "cpl_json.h"
      35             : #include "cpl_minixml.h"
      36             : #include "cpl_multiproc.h"
      37             : #include "cpl_string.h"
      38             : #include "cpl_vsi.h"
      39             : #ifdef EMBED_RESOURCE_FILES
      40             : #include "embedded_resources.h"
      41             : #endif
      42             : #include "gdal_version_full/gdal_version.h"
      43             : #include "gdal.h"
      44             : #include "gdal_mdreader.h"
      45             : #include "gdal_priv.h"
      46             : #include "gdal_priv_templates.hpp"
      47             : #include "ogr_core.h"
      48             : #include "ogr_spatialref.h"
      49             : #include "ogr_geos.h"
      50             : 
      51             : #include "proj.h"
      52             : 
      53             : #ifdef HAVE_CURL
      54             : #include "cpl_curl_priv.h"
      55             : #endif
      56             : 
      57        3930 : static int GetMinBitsForPair(const bool pabSigned[], const bool pabFloating[],
      58             :                              const int panBits[])
      59             : {
      60        3930 :     if (pabFloating[0] != pabFloating[1])
      61             :     {
      62         489 :         const int nNotFloatingTypeIndex = pabFloating[0] ? 1 : 0;
      63         489 :         const int nFloatingTypeIndex = pabFloating[0] ? 0 : 1;
      64             : 
      65         489 :         return std::max(panBits[nFloatingTypeIndex],
      66         489 :                         2 * panBits[nNotFloatingTypeIndex]);
      67             :     }
      68             : 
      69        3441 :     if (pabSigned[0] != pabSigned[1])
      70             :     {
      71         430 :         if (!pabSigned[0] && panBits[0] < panBits[1])
      72         329 :             return panBits[1];
      73         101 :         if (!pabSigned[1] && panBits[1] < panBits[0])
      74          23 :             return panBits[0];
      75             : 
      76          78 :         const int nUnsignedTypeIndex = pabSigned[0] ? 1 : 0;
      77          78 :         const int nSignedTypeIndex = pabSigned[0] ? 0 : 1;
      78             : 
      79          78 :         return std::max(panBits[nSignedTypeIndex],
      80          78 :                         2 * panBits[nUnsignedTypeIndex]);
      81             :     }
      82             : 
      83        3011 :     return std::max(panBits[0], panBits[1]);
      84             : }
      85             : 
      86        7860 : static int GetNonComplexDataTypeElementSizeBits(GDALDataType eDataType)
      87             : {
      88        7860 :     switch (eDataType)
      89             :     {
      90        4646 :         case GDT_Byte:
      91             :         case GDT_Int8:
      92        4646 :             return 8;
      93             : 
      94        1353 :         case GDT_UInt16:
      95             :         case GDT_Int16:
      96             :         case GDT_Float16:
      97             :         case GDT_CInt16:
      98             :         case GDT_CFloat16:
      99        1353 :             return 16;
     100             : 
     101        1276 :         case GDT_UInt32:
     102             :         case GDT_Int32:
     103             :         case GDT_Float32:
     104             :         case GDT_CInt32:
     105             :         case GDT_CFloat32:
     106        1276 :             return 32;
     107             : 
     108         585 :         case GDT_Float64:
     109             :         case GDT_CFloat64:
     110             :         case GDT_UInt64:
     111             :         case GDT_Int64:
     112         585 :             return 64;
     113             : 
     114           0 :         case GDT_Unknown:
     115             :         case GDT_TypeCount:
     116           0 :             break;
     117             :     }
     118           0 :     return 0;
     119             : }
     120             : 
     121             : /************************************************************************/
     122             : /*                         GDALDataTypeUnion()                          */
     123             : /************************************************************************/
     124             : 
     125             : /**
     126             :  * \brief Return the smallest data type that can fully express both input data
     127             :  * types.
     128             :  *
     129             :  * @param eType1 first data type.
     130             :  * @param eType2 second data type.
     131             :  *
     132             :  * @return a data type able to express eType1 and eType2.
     133             :  */
     134             : 
     135        4260 : GDALDataType CPL_STDCALL GDALDataTypeUnion(GDALDataType eType1,
     136             :                                            GDALDataType eType2)
     137             : 
     138             : {
     139        4260 :     if (eType1 == GDT_Unknown)
     140         330 :         return eType2;
     141        3930 :     if (eType2 == GDT_Unknown)
     142           0 :         return eType1;
     143             : 
     144        3930 :     const int panBits[] = {GetNonComplexDataTypeElementSizeBits(eType1),
     145        3930 :                            GetNonComplexDataTypeElementSizeBits(eType2)};
     146             : 
     147        3930 :     if (panBits[0] == 0 || panBits[1] == 0)
     148           0 :         return GDT_Unknown;
     149             : 
     150        3930 :     const bool pabSigned[] = {CPL_TO_BOOL(GDALDataTypeIsSigned(eType1)),
     151        3930 :                               CPL_TO_BOOL(GDALDataTypeIsSigned(eType2))};
     152             : 
     153        3930 :     const bool bSigned = pabSigned[0] || pabSigned[1];
     154        3930 :     const bool pabFloating[] = {CPL_TO_BOOL(GDALDataTypeIsFloating(eType1)),
     155        3930 :                                 CPL_TO_BOOL(GDALDataTypeIsFloating(eType2))};
     156        3930 :     const bool bFloating = pabFloating[0] || pabFloating[1];
     157        3930 :     const int nBits = GetMinBitsForPair(pabSigned, pabFloating, panBits);
     158        7388 :     const bool bIsComplex = CPL_TO_BOOL(GDALDataTypeIsComplex(eType1)) ||
     159        3458 :                             CPL_TO_BOOL(GDALDataTypeIsComplex(eType2));
     160             : 
     161        3930 :     return GDALFindDataType(nBits, bSigned, bFloating, bIsComplex);
     162             : }
     163             : 
     164             : /************************************************************************/
     165             : /*                        GDALDataTypeUnionWithValue()                  */
     166             : /************************************************************************/
     167             : 
     168             : /**
     169             :  * \brief Union a data type with the one found for a value
     170             :  *
     171             :  * @param eDT the first data type
     172             :  * @param dfValue the value for which to find a data type and union with eDT
     173             :  * @param bComplex if the value is complex
     174             :  *
     175             :  * @return a data type able to express eDT and dfValue.
     176             :  * @since GDAL 2.3
     177             :  */
     178         338 : GDALDataType CPL_STDCALL GDALDataTypeUnionWithValue(GDALDataType eDT,
     179             :                                                     double dfValue,
     180             :                                                     int bComplex)
     181             : {
     182         338 :     if (!bComplex && !GDALDataTypeIsComplex(eDT) && eDT != GDT_Unknown)
     183             :     {
     184             :         // Do not return `GDT_Float16` because that type is not supported everywhere
     185         331 :         const auto eDTMod = eDT == GDT_Float16 ? GDT_Float32 : eDT;
     186         331 :         if (GDALIsValueExactAs(dfValue, eDTMod))
     187             :         {
     188         311 :             return eDTMod;
     189             :         }
     190             :     }
     191             : 
     192          27 :     const GDALDataType eDT2 = GDALFindDataTypeForValue(dfValue, bComplex);
     193          27 :     return GDALDataTypeUnion(eDT, eDT2);
     194             : }
     195             : 
     196             : /************************************************************************/
     197             : /*                        GetMinBitsForValue()                          */
     198             : /************************************************************************/
     199          27 : static int GetMinBitsForValue(double dValue)
     200             : {
     201          27 :     if (round(dValue) == dValue)
     202             :     {
     203          26 :         if (dValue <= cpl::NumericLimits<GByte>::max() &&
     204           9 :             dValue >= cpl::NumericLimits<GByte>::lowest())
     205           4 :             return 8;
     206             : 
     207          18 :         if (dValue <= cpl::NumericLimits<GInt8>::max() &&
     208           5 :             dValue >= cpl::NumericLimits<GInt8>::lowest())
     209           3 :             return 8;
     210             : 
     211          14 :         if (dValue <= cpl::NumericLimits<GInt16>::max() &&
     212           4 :             dValue >= cpl::NumericLimits<GInt16>::lowest())
     213           3 :             return 16;
     214             : 
     215           9 :         if (dValue <= cpl::NumericLimits<GUInt16>::max() &&
     216           2 :             dValue >= cpl::NumericLimits<GUInt16>::lowest())
     217           1 :             return 16;
     218             : 
     219           8 :         if (dValue <= cpl::NumericLimits<GInt32>::max() &&
     220           2 :             dValue >= cpl::NumericLimits<GInt32>::lowest())
     221           2 :             return 32;
     222             : 
     223           5 :         if (dValue <= cpl::NumericLimits<GUInt32>::max() &&
     224           1 :             dValue >= cpl::NumericLimits<GUInt32>::lowest())
     225           1 :             return 32;
     226             : 
     227           3 :         if (dValue <=
     228           5 :                 static_cast<double>(cpl::NumericLimits<std::uint64_t>::max()) &&
     229           2 :             dValue >= static_cast<double>(
     230           2 :                           cpl::NumericLimits<std::uint64_t>::lowest()))
     231           2 :             return 64;
     232             :     }
     233          10 :     else if (static_cast<float>(dValue) == dValue)
     234             :     {
     235           4 :         return 32;
     236             :     }
     237             : 
     238           7 :     return 64;
     239             : }
     240             : 
     241             : /************************************************************************/
     242             : /*                        GDALFindDataType()                            */
     243             : /************************************************************************/
     244             : 
     245             : /**
     246             :  * \brief Finds the smallest data type able to support the given
     247             :  *  requirements
     248             :  *
     249             :  * @param nBits number of bits necessary
     250             :  * @param bSigned if negative values are necessary
     251             :  * @param bFloating if non-integer values necessary
     252             :  * @param bComplex if complex values are necessary
     253             :  *
     254             :  * @return a best fit GDALDataType for supporting the requirements
     255             :  * @since GDAL 2.3
     256             :  */
     257        3979 : GDALDataType CPL_STDCALL GDALFindDataType(int nBits, int bSigned, int bFloating,
     258             :                                           int bComplex)
     259             : {
     260        3979 :     if (!bFloating)
     261             :     {
     262        3077 :         if (!bComplex)
     263             :         {
     264        2581 :             if (!bSigned)
     265             :             {
     266        2193 :                 if (nBits <= 8)
     267        1963 :                     return GDT_Byte;
     268         230 :                 if (nBits <= 16)
     269         128 :                     return GDT_UInt16;
     270         102 :                 if (nBits <= 32)
     271          73 :                     return GDT_UInt32;
     272          29 :                 if (nBits <= 64)
     273          29 :                     return GDT_UInt64;
     274           0 :                 return GDT_Float64;
     275             :             }
     276             :             else  // bSigned
     277             :             {
     278         388 :                 if (nBits <= 8)
     279          14 :                     return GDT_Int8;
     280         374 :                 if (nBits <= 16)
     281         173 :                     return GDT_Int16;
     282         201 :                 if (nBits <= 32)
     283         130 :                     return GDT_Int32;
     284          71 :                 if (nBits <= 64)
     285          53 :                     return GDT_Int64;
     286          18 :                 return GDT_Float64;
     287             :             }
     288             :         }
     289             :         else  // bComplex
     290             :         {
     291         496 :             if (!bSigned)
     292             :             {
     293             :                 // We don't have complex unsigned data types, so
     294             :                 // return a large-enough complex signed type
     295             : 
     296             :                 // Do not choose CInt16 for backward compatibility
     297             :                 // if (nBits <= 15)
     298             :                 //     return GDT_CInt16;
     299           3 :                 if (nBits <= 31)
     300           3 :                     return GDT_CInt32;
     301           0 :                 return GDT_CFloat64;
     302             :             }
     303             :             else  // bSigned
     304             :             {
     305         493 :                 if (nBits <= 16)
     306         367 :                     return GDT_CInt16;
     307         126 :                 if (nBits <= 32)
     308          99 :                     return GDT_CInt32;
     309          27 :                 return GDT_CFloat64;
     310             :             }
     311             :         }
     312             :     }
     313             :     else  // bFloating
     314             :     {
     315         902 :         if (!bComplex)
     316             :         {
     317             :             // Do not choose Float16 since is not supported everywhere
     318             :             // if (nBits <= 16)
     319             :             //     return GDT_Float16;
     320         542 :             if (nBits <= 32)
     321         327 :                 return GDT_Float32;
     322         215 :             return GDT_Float64;
     323             :         }
     324             :         else  // bComplex
     325             :         {
     326             :             // Do not choose Float16 since is not supported everywhere
     327             :             // if (nBits <= 16)
     328             :             //     return GDT_CFloat16;
     329         360 :             if (nBits <= 32)
     330         160 :                 return GDT_CFloat32;
     331         200 :             return GDT_CFloat64;
     332             :         }
     333             :     }
     334             : }
     335             : 
     336             : /************************************************************************/
     337             : /*                        GDALFindDataTypeForValue()                    */
     338             : /************************************************************************/
     339             : 
     340             : /**
     341             :  * \brief Finds the smallest data type able to support the provided value
     342             :  *
     343             :  * @param dValue value to support
     344             :  * @param bComplex is the value complex
     345             :  *
     346             :  * @return a best fit GDALDataType for supporting the value
     347             :  * @since GDAL 2.3
     348             :  */
     349          27 : GDALDataType CPL_STDCALL GDALFindDataTypeForValue(double dValue, int bComplex)
     350             : {
     351             :     const bool bFloating =
     352          44 :         round(dValue) != dValue ||
     353             :         dValue >
     354          43 :             static_cast<double>(cpl::NumericLimits<std::uint64_t>::max()) ||
     355             :         dValue <
     356          16 :             static_cast<double>(cpl::NumericLimits<std::int64_t>::lowest());
     357          27 :     const bool bSigned = bFloating || dValue < 0;
     358          27 :     const int nBits = GetMinBitsForValue(dValue);
     359             : 
     360          27 :     return GDALFindDataType(nBits, bSigned, bFloating, bComplex);
     361             : }
     362             : 
     363             : /************************************************************************/
     364             : /*                        GDALGetDataTypeSizeBytes()                    */
     365             : /************************************************************************/
     366             : 
     367             : /**
     368             :  * \brief Get data type size in <b>bytes</b>.
     369             :  *
     370             :  * Returns the size of a GDT_* type in bytes.  In contrast,
     371             :  * GDALGetDataTypeSize() returns the size in <b>bits</b>.
     372             :  *
     373             :  * @param eDataType type, such as GDT_Byte.
     374             :  * @return the number of bytes or zero if it is not recognised.
     375             :  */
     376             : 
     377   245910000 : int CPL_STDCALL GDALGetDataTypeSizeBytes(GDALDataType eDataType)
     378             : 
     379             : {
     380   245910000 :     switch (eDataType)
     381             :     {
     382    80306800 :         case GDT_Byte:
     383             :         case GDT_Int8:
     384    80306800 :             return 1;
     385             : 
     386    51070900 :         case GDT_UInt16:
     387             :         case GDT_Int16:
     388             :         case GDT_Float16:
     389    51070900 :             return 2;
     390             : 
     391    77390900 :         case GDT_UInt32:
     392             :         case GDT_Int32:
     393             :         case GDT_Float32:
     394             :         case GDT_CInt16:
     395             :         case GDT_CFloat16:
     396    77390900 :             return 4;
     397             : 
     398    36760500 :         case GDT_Float64:
     399             :         case GDT_CInt32:
     400             :         case GDT_CFloat32:
     401             :         case GDT_UInt64:
     402             :         case GDT_Int64:
     403    36760500 :             return 8;
     404             : 
     405      384209 :         case GDT_CFloat64:
     406      384209 :             return 16;
     407             : 
     408       17736 :         case GDT_Unknown:
     409             :         case GDT_TypeCount:
     410       17736 :             break;
     411             :     }
     412           0 :     return 0;
     413             : }
     414             : 
     415             : /************************************************************************/
     416             : /*                        GDALGetDataTypeSizeBits()                     */
     417             : /************************************************************************/
     418             : 
     419             : /**
     420             :  * \brief Get data type size in <b>bits</b>.
     421             :  *
     422             :  * Returns the size of a GDT_* type in bits, <b>not bytes</b>!  Use
     423             :  * GDALGetDataTypeSizeBytes() for bytes.
     424             :  *
     425             :  * @param eDataType type, such as GDT_Byte.
     426             :  * @return the number of bits or zero if it is not recognised.
     427             :  */
     428             : 
     429       13416 : int CPL_STDCALL GDALGetDataTypeSizeBits(GDALDataType eDataType)
     430             : 
     431             : {
     432       13416 :     return GDALGetDataTypeSizeBytes(eDataType) * 8;
     433             : }
     434             : 
     435             : /************************************************************************/
     436             : /*                        GDALGetDataTypeSize()                         */
     437             : /************************************************************************/
     438             : 
     439             : /**
     440             :  * \brief Get data type size in bits.  <b>Deprecated</b>.
     441             :  *
     442             :  * Returns the size of a GDT_* type in bits, <b>not bytes</b>!
     443             :  *
     444             :  * Use GDALGetDataTypeSizeBytes() for bytes.
     445             :  * Use GDALGetDataTypeSizeBits() for bits.
     446             :  *
     447             :  * @param eDataType type, such as GDT_Byte.
     448             :  * @return the number of bits or zero if it is not recognised.
     449             :  */
     450             : 
     451     3913160 : int CPL_STDCALL GDALGetDataTypeSize(GDALDataType eDataType)
     452             : 
     453             : {
     454     3913160 :     return GDALGetDataTypeSizeBytes(eDataType) * 8;
     455             : }
     456             : 
     457             : /************************************************************************/
     458             : /*                       GDALDataTypeIsComplex()                        */
     459             : /************************************************************************/
     460             : 
     461             : /**
     462             :  * \brief Is data type complex?
     463             :  *
     464             :  * @return TRUE if the passed type is complex (one of GDT_CInt16, GDT_CInt32,
     465             :  * GDT_CFloat32 or GDT_CFloat64), that is it consists of a real and imaginary
     466             :  * component.
     467             :  */
     468             : 
     469      920329 : int CPL_STDCALL GDALDataTypeIsComplex(GDALDataType eDataType)
     470             : 
     471             : {
     472      920329 :     switch (eDataType)
     473             :     {
     474       14744 :         case GDT_CInt16:
     475             :         case GDT_CInt32:
     476             :         case GDT_CFloat16:
     477             :         case GDT_CFloat32:
     478             :         case GDT_CFloat64:
     479       14744 :             return TRUE;
     480             : 
     481      905574 :         case GDT_Byte:
     482             :         case GDT_Int8:
     483             :         case GDT_Int16:
     484             :         case GDT_UInt16:
     485             :         case GDT_Int32:
     486             :         case GDT_UInt32:
     487             :         case GDT_Int64:
     488             :         case GDT_UInt64:
     489             :         case GDT_Float16:
     490             :         case GDT_Float32:
     491             :         case GDT_Float64:
     492      905574 :             return FALSE;
     493             : 
     494           7 :         case GDT_Unknown:
     495             :         case GDT_TypeCount:
     496           7 :             break;
     497             :     }
     498          11 :     return FALSE;
     499             : }
     500             : 
     501             : /************************************************************************/
     502             : /*                       GDALDataTypeIsFloating()                       */
     503             : /************************************************************************/
     504             : 
     505             : /**
     506             :  * \brief Is data type floating? (might be complex)
     507             :  *
     508             :  * @return TRUE if the passed type is floating (one of GDT_Float32, GDT_Float16,
     509             :  * GDT_Float64, GDT_CFloat16, GDT_CFloat32, GDT_CFloat64)
     510             :  * @since GDAL 2.3
     511             :  */
     512             : 
     513      262254 : int CPL_STDCALL GDALDataTypeIsFloating(GDALDataType eDataType)
     514             : {
     515      262254 :     switch (eDataType)
     516             :     {
     517        6807 :         case GDT_Float16:
     518             :         case GDT_Float32:
     519             :         case GDT_Float64:
     520             :         case GDT_CFloat16:
     521             :         case GDT_CFloat32:
     522             :         case GDT_CFloat64:
     523        6807 :             return TRUE;
     524             : 
     525      255446 :         case GDT_Byte:
     526             :         case GDT_Int8:
     527             :         case GDT_Int16:
     528             :         case GDT_UInt16:
     529             :         case GDT_Int32:
     530             :         case GDT_UInt32:
     531             :         case GDT_Int64:
     532             :         case GDT_UInt64:
     533             :         case GDT_CInt16:
     534             :         case GDT_CInt32:
     535      255446 :             return FALSE;
     536             : 
     537           1 :         case GDT_Unknown:
     538             :         case GDT_TypeCount:
     539           1 :             break;
     540             :     }
     541           1 :     return FALSE;
     542             : }
     543             : 
     544             : /************************************************************************/
     545             : /*                       GDALDataTypeIsInteger()                        */
     546             : /************************************************************************/
     547             : 
     548             : /**
     549             :  * \brief Is data type integer? (might be complex)
     550             :  *
     551             :  * @return TRUE if the passed type is integer (one of GDT_Byte, GDT_Int16,
     552             :  * GDT_UInt16, GDT_Int32, GDT_UInt32, GDT_CInt16, GDT_CInt32).
     553             :  * @since GDAL 2.3
     554             :  */
     555             : 
     556      260963 : int CPL_STDCALL GDALDataTypeIsInteger(GDALDataType eDataType)
     557             : 
     558             : {
     559      260963 :     switch (eDataType)
     560             :     {
     561      258704 :         case GDT_Byte:
     562             :         case GDT_Int8:
     563             :         case GDT_Int16:
     564             :         case GDT_UInt16:
     565             :         case GDT_Int32:
     566             :         case GDT_UInt32:
     567             :         case GDT_CInt16:
     568             :         case GDT_CInt32:
     569             :         case GDT_UInt64:
     570             :         case GDT_Int64:
     571      258704 :             return TRUE;
     572             : 
     573        2259 :         case GDT_Float16:
     574             :         case GDT_Float32:
     575             :         case GDT_Float64:
     576             :         case GDT_CFloat16:
     577             :         case GDT_CFloat32:
     578             :         case GDT_CFloat64:
     579        2259 :             return FALSE;
     580             : 
     581           1 :         case GDT_Unknown:
     582             :         case GDT_TypeCount:
     583           1 :             break;
     584             :     }
     585           0 :     return FALSE;
     586             : }
     587             : 
     588             : /************************************************************************/
     589             : /*                       GDALDataTypeIsSigned()                         */
     590             : /************************************************************************/
     591             : 
     592             : /**
     593             :  * \brief Is data type signed?
     594             :  *
     595             :  * @return TRUE if the passed type is signed.
     596             :  * @since GDAL 2.3
     597             :  */
     598             : 
     599      505191 : int CPL_STDCALL GDALDataTypeIsSigned(GDALDataType eDataType)
     600             : {
     601      505191 :     switch (eDataType)
     602             :     {
     603      500303 :         case GDT_Byte:
     604             :         case GDT_UInt16:
     605             :         case GDT_UInt32:
     606             :         case GDT_UInt64:
     607      500303 :             return FALSE;
     608             : 
     609        4888 :         case GDT_Int8:
     610             :         case GDT_Int16:
     611             :         case GDT_Int32:
     612             :         case GDT_Int64:
     613             :         case GDT_Float16:
     614             :         case GDT_Float32:
     615             :         case GDT_Float64:
     616             :         case GDT_CInt16:
     617             :         case GDT_CInt32:
     618             :         case GDT_CFloat16:
     619             :         case GDT_CFloat32:
     620             :         case GDT_CFloat64:
     621        4888 :             return TRUE;
     622             : 
     623           0 :         case GDT_Unknown:
     624             :         case GDT_TypeCount:
     625           0 :             break;
     626             :     }
     627           0 :     return FALSE;
     628             : }
     629             : 
     630             : /************************************************************************/
     631             : /*                    GDALDataTypeIsConversionLossy()                   */
     632             : /************************************************************************/
     633             : 
     634             : /**
     635             :  * \brief Is conversion from eTypeFrom to eTypeTo potentially lossy
     636             :  *
     637             :  * @param eTypeFrom input datatype
     638             :  * @param eTypeTo output datatype
     639             :  * @return TRUE if conversion from eTypeFrom to eTypeTo potentially lossy.
     640             :  * @since GDAL 2.3
     641             :  */
     642             : 
     643      255791 : int CPL_STDCALL GDALDataTypeIsConversionLossy(GDALDataType eTypeFrom,
     644             :                                               GDALDataType eTypeTo)
     645             : {
     646             :     // E.g cfloat32 -> float32
     647      255791 :     if (GDALDataTypeIsComplex(eTypeFrom) && !GDALDataTypeIsComplex(eTypeTo))
     648         526 :         return TRUE;
     649             : 
     650      255265 :     eTypeFrom = GDALGetNonComplexDataType(eTypeFrom);
     651      255265 :     eTypeTo = GDALGetNonComplexDataType(eTypeTo);
     652             : 
     653      255265 :     if (GDALDataTypeIsInteger(eTypeTo))
     654             :     {
     655             :         // E.g. float32 -> int32
     656      253482 :         if (GDALDataTypeIsFloating(eTypeFrom))
     657        5153 :             return TRUE;
     658             : 
     659             :         // E.g. Int16 to UInt16
     660      248329 :         const int bIsFromSigned = GDALDataTypeIsSigned(eTypeFrom);
     661      248329 :         const int bIsToSigned = GDALDataTypeIsSigned(eTypeTo);
     662      248329 :         if (bIsFromSigned && !bIsToSigned)
     663         194 :             return TRUE;
     664             : 
     665             :         // E.g UInt32 to UInt16
     666      248135 :         const int nFromSize = GDALGetDataTypeSize(eTypeFrom);
     667      248135 :         const int nToSize = GDALGetDataTypeSize(eTypeTo);
     668      248135 :         if (nFromSize > nToSize)
     669         196 :             return TRUE;
     670             : 
     671             :         // E.g UInt16 to Int16
     672      247939 :         if (nFromSize == nToSize && !bIsFromSigned && bIsToSigned)
     673          37 :             return TRUE;
     674             : 
     675      247902 :         return FALSE;
     676             :     }
     677             : 
     678        1783 :     if (eTypeTo == GDT_Float16 &&
     679           0 :         (eTypeFrom == GDT_Int16 || eTypeFrom == GDT_UInt16 ||
     680           0 :          eTypeFrom == GDT_Int32 || eTypeFrom == GDT_UInt32 ||
     681           0 :          eTypeFrom == GDT_Int64 || eTypeFrom == GDT_UInt64 ||
     682           0 :          eTypeFrom == GDT_Float32 || eTypeFrom == GDT_Float64))
     683             :     {
     684           0 :         return TRUE;
     685             :     }
     686             : 
     687        1783 :     if (eTypeTo == GDT_Float32 &&
     688         699 :         (eTypeFrom == GDT_Int32 || eTypeFrom == GDT_UInt32 ||
     689         667 :          eTypeFrom == GDT_Int64 || eTypeFrom == GDT_UInt64 ||
     690             :          eTypeFrom == GDT_Float64))
     691             :     {
     692          96 :         return TRUE;
     693             :     }
     694             : 
     695        1687 :     if (eTypeTo == GDT_Float64 &&
     696        1039 :         (eTypeFrom == GDT_Int64 || eTypeFrom == GDT_UInt64))
     697             :     {
     698          32 :         return TRUE;
     699             :     }
     700             : 
     701        1655 :     return FALSE;
     702             : }
     703             : 
     704             : /************************************************************************/
     705             : /*                        GDALGetDataTypeName()                         */
     706             : /************************************************************************/
     707             : 
     708             : /**
     709             :  * \brief Get name of data type.
     710             :  *
     711             :  * Returns a symbolic name for the data type.  This is essentially the
     712             :  * the enumerated item name with the GDT_ prefix removed.  So GDT_Byte returns
     713             :  * "Byte".  The returned strings are static strings and should not be modified
     714             :  * or freed by the application.  These strings are useful for reporting
     715             :  * datatypes in debug statements, errors and other user output.
     716             :  *
     717             :  * @param eDataType type to get name of.
     718             :  * @return string corresponding to existing data type
     719             :  *         or NULL pointer if invalid type given.
     720             :  */
     721             : 
     722       99375 : const char *CPL_STDCALL GDALGetDataTypeName(GDALDataType eDataType)
     723             : 
     724             : {
     725       99375 :     switch (eDataType)
     726             :     {
     727        5303 :         case GDT_Unknown:
     728        5303 :             return "Unknown";
     729             : 
     730       34392 :         case GDT_Byte:
     731       34392 :             return "Byte";
     732             : 
     733        1019 :         case GDT_Int8:
     734        1019 :             return "Int8";
     735             : 
     736       10530 :         case GDT_UInt16:
     737       10530 :             return "UInt16";
     738             : 
     739       10026 :         case GDT_Int16:
     740       10026 :             return "Int16";
     741             : 
     742        8128 :         case GDT_UInt32:
     743        8128 :             return "UInt32";
     744             : 
     745        7552 :         case GDT_Int32:
     746        7552 :             return "Int32";
     747             : 
     748        1282 :         case GDT_UInt64:
     749        1282 :             return "UInt64";
     750             : 
     751        1158 :         case GDT_Int64:
     752        1158 :             return "Int64";
     753             : 
     754         491 :         case GDT_Float16:
     755         491 :             return "Float16";
     756             : 
     757        6966 :         case GDT_Float32:
     758        6966 :             return "Float32";
     759             : 
     760        4304 :         case GDT_Float64:
     761        4304 :             return "Float64";
     762             : 
     763        2217 :         case GDT_CInt16:
     764        2217 :             return "CInt16";
     765             : 
     766        2038 :         case GDT_CInt32:
     767        2038 :             return "CInt32";
     768             : 
     769         353 :         case GDT_CFloat16:
     770         353 :             return "CFloat16";
     771             : 
     772        1942 :         case GDT_CFloat32:
     773        1942 :             return "CFloat32";
     774             : 
     775        1674 :         case GDT_CFloat64:
     776        1674 :             return "CFloat64";
     777             : 
     778           0 :         case GDT_TypeCount:
     779           0 :             break;
     780             :     }
     781           0 :     return nullptr;
     782             : }
     783             : 
     784             : /************************************************************************/
     785             : /*                        GDALGetDataTypeByName()                       */
     786             : /************************************************************************/
     787             : 
     788             : /**
     789             :  * \brief Get data type by symbolic name.
     790             :  *
     791             :  * Returns a data type corresponding to the given symbolic name. This
     792             :  * function is opposite to the GDALGetDataTypeName().
     793             :  *
     794             :  * @param pszName string containing the symbolic name of the type.
     795             :  *
     796             :  * @return GDAL data type.
     797             :  */
     798             : 
     799        8012 : GDALDataType CPL_STDCALL GDALGetDataTypeByName(const char *pszName)
     800             : 
     801             : {
     802        8012 :     VALIDATE_POINTER1(pszName, "GDALGetDataTypeByName", GDT_Unknown);
     803             : 
     804       31695 :     for (int iType = 1; iType < GDT_TypeCount; iType++)
     805             :     {
     806       31663 :         const auto eType = static_cast<GDALDataType>(iType);
     807       63326 :         if (GDALGetDataTypeName(eType) != nullptr &&
     808       31663 :             EQUAL(GDALGetDataTypeName(eType), pszName))
     809             :         {
     810        7980 :             return eType;
     811             :         }
     812             :     }
     813             : 
     814          32 :     return GDT_Unknown;
     815             : }
     816             : 
     817             : /************************************************************************/
     818             : /*                      GDALAdjustValueToDataType()                     */
     819             : /************************************************************************/
     820             : 
     821             : template <class T>
     822          73 : static inline void ClampAndRound(double &dfValue, bool &bClamped,
     823             :                                  bool &bRounded)
     824             : {
     825          73 :     if (dfValue < static_cast<double>(cpl::NumericLimits<T>::lowest()))
     826             :     {
     827           6 :         bClamped = true;
     828           6 :         dfValue = static_cast<double>(cpl::NumericLimits<T>::lowest());
     829             :     }
     830          67 :     else if (dfValue > static_cast<double>(cpl::NumericLimits<T>::max()))
     831             :     {
     832           4 :         bClamped = true;
     833           4 :         dfValue = static_cast<double>(cpl::NumericLimits<T>::max());
     834             :     }
     835          63 :     else if (dfValue != static_cast<double>(static_cast<T>(dfValue)))
     836             :     {
     837           8 :         bRounded = true;
     838           8 :         dfValue = static_cast<double>(static_cast<T>(floor(dfValue + 0.5)));
     839             :     }
     840          73 : }
     841             : 
     842             : /**
     843             :  * \brief Adjust a value to the output data type
     844             :  *
     845             :  * Adjustment consist in clamping to minimum/maximum values of the data type
     846             :  * and rounding for integral types.
     847             :  *
     848             :  * @param eDT target data type.
     849             :  * @param dfValue value to adjust.
     850             :  * @param pbClamped pointer to a integer(boolean) to indicate if clamping has
     851             :  * been made, or NULL
     852             :  * @param pbRounded pointer to a integer(boolean) to indicate if rounding has
     853             :  * been made, or NULL
     854             :  *
     855             :  * @return adjusted value
     856             :  * @since GDAL 2.1
     857             :  */
     858             : 
     859         117 : double GDALAdjustValueToDataType(GDALDataType eDT, double dfValue,
     860             :                                  int *pbClamped, int *pbRounded)
     861             : {
     862         117 :     bool bClamped = false;
     863         117 :     bool bRounded = false;
     864         117 :     switch (eDT)
     865             :     {
     866          30 :         case GDT_Byte:
     867          30 :             ClampAndRound<GByte>(dfValue, bClamped, bRounded);
     868          30 :             break;
     869           8 :         case GDT_Int8:
     870           8 :             ClampAndRound<GInt8>(dfValue, bClamped, bRounded);
     871           8 :             break;
     872          11 :         case GDT_Int16:
     873          11 :             ClampAndRound<GInt16>(dfValue, bClamped, bRounded);
     874          11 :             break;
     875           6 :         case GDT_UInt16:
     876           6 :             ClampAndRound<GUInt16>(dfValue, bClamped, bRounded);
     877           6 :             break;
     878           4 :         case GDT_Int32:
     879           4 :             ClampAndRound<GInt32>(dfValue, bClamped, bRounded);
     880           4 :             break;
     881           5 :         case GDT_UInt32:
     882           5 :             ClampAndRound<GUInt32>(dfValue, bClamped, bRounded);
     883           5 :             break;
     884           4 :         case GDT_Int64:
     885           4 :             ClampAndRound<std::int64_t>(dfValue, bClamped, bRounded);
     886           4 :             break;
     887           5 :         case GDT_UInt64:
     888           5 :             ClampAndRound<std::uint64_t>(dfValue, bClamped, bRounded);
     889           5 :             break;
     890           8 :         case GDT_Float16:
     891             :         {
     892           8 :             if (!std::isfinite(dfValue))
     893           3 :                 break;
     894             : 
     895             :             // TODO: Use ClampAndRound
     896           5 :             if (dfValue < cpl::NumericLimits<GFloat16>::lowest())
     897             :             {
     898           1 :                 bClamped = TRUE;
     899           1 :                 dfValue =
     900           1 :                     static_cast<double>(cpl::NumericLimits<GFloat16>::lowest());
     901             :             }
     902           4 :             else if (dfValue > cpl::NumericLimits<GFloat16>::max())
     903             :             {
     904           1 :                 bClamped = TRUE;
     905           1 :                 dfValue =
     906           1 :                     static_cast<double>(cpl::NumericLimits<GFloat16>::max());
     907             :             }
     908             :             else
     909             :             {
     910             :                 // Intentionally lose precision.
     911             :                 // TODO(schwehr): Is the double cast really necessary?
     912             :                 // If so, why?  What will fail?
     913           3 :                 dfValue = static_cast<double>(static_cast<GFloat16>(dfValue));
     914             :             }
     915           5 :             break;
     916             :         }
     917          27 :         case GDT_Float32:
     918             :         {
     919          27 :             if (!std::isfinite(dfValue))
     920           4 :                 break;
     921             : 
     922             :             // TODO: Use ClampAndRound
     923          23 :             if (dfValue < cpl::NumericLimits<float>::lowest())
     924             :             {
     925           1 :                 bClamped = TRUE;
     926           1 :                 dfValue =
     927           1 :                     static_cast<double>(cpl::NumericLimits<float>::lowest());
     928             :             }
     929          22 :             else if (dfValue > cpl::NumericLimits<float>::max())
     930             :             {
     931           1 :                 bClamped = TRUE;
     932           1 :                 dfValue = static_cast<double>(cpl::NumericLimits<float>::max());
     933             :             }
     934             :             else
     935             :             {
     936             :                 // Intentionally lose precision.
     937             :                 // TODO(schwehr): Is the double cast really necessary?
     938             :                 // If so, why?  What will fail?
     939          21 :                 dfValue = static_cast<double>(static_cast<float>(dfValue));
     940             :             }
     941          23 :             break;
     942             :         }
     943           9 :         case GDT_Float64:
     944             :         case GDT_CInt16:
     945             :         case GDT_CInt32:
     946             :         case GDT_CFloat16:
     947             :         case GDT_CFloat32:
     948             :         case GDT_CFloat64:
     949             :         case GDT_Unknown:
     950             :         case GDT_TypeCount:
     951           9 :             break;
     952             :     }
     953         117 :     if (pbClamped)
     954         116 :         *pbClamped = bClamped;
     955         117 :     if (pbRounded)
     956         116 :         *pbRounded = bRounded;
     957         117 :     return dfValue;
     958             : }
     959             : 
     960             : /************************************************************************/
     961             : /*                         GDALIsValueExactAs()                         */
     962             : /************************************************************************/
     963             : 
     964             : /**
     965             :  * \brief Check whether the provided value can be exactly represented in a
     966             :  * data type.
     967             :  *
     968             :  * Only implemented for non-complex data types
     969             :  *
     970             :  * @param dfValue value to check.
     971             :  * @param eDT target data type.
     972             :  *
     973             :  * @return true if the provided value can be exactly represented in the
     974             :  * data type.
     975             :  * @since GDAL 3.10
     976             :  */
     977        1772 : bool GDALIsValueExactAs(double dfValue, GDALDataType eDT)
     978             : {
     979        1772 :     switch (eDT)
     980             :     {
     981         377 :         case GDT_Byte:
     982         377 :             return GDALIsValueExactAs<uint8_t>(dfValue);
     983           7 :         case GDT_Int8:
     984           7 :             return GDALIsValueExactAs<int8_t>(dfValue);
     985          71 :         case GDT_UInt16:
     986          71 :             return GDALIsValueExactAs<uint16_t>(dfValue);
     987          90 :         case GDT_Int16:
     988          90 :             return GDALIsValueExactAs<int16_t>(dfValue);
     989          11 :         case GDT_UInt32:
     990          11 :             return GDALIsValueExactAs<uint32_t>(dfValue);
     991          38 :         case GDT_Int32:
     992          38 :             return GDALIsValueExactAs<int32_t>(dfValue);
     993           9 :         case GDT_UInt64:
     994           9 :             return GDALIsValueExactAs<uint64_t>(dfValue);
     995           9 :         case GDT_Int64:
     996           9 :             return GDALIsValueExactAs<int64_t>(dfValue);
     997           0 :         case GDT_Float16:
     998           0 :             return GDALIsValueExactAs<GFloat16>(dfValue);
     999         121 :         case GDT_Float32:
    1000         121 :             return GDALIsValueExactAs<float>(dfValue);
    1001        1038 :         case GDT_Float64:
    1002        1038 :             return true;
    1003           1 :         case GDT_Unknown:
    1004             :         case GDT_CInt16:
    1005             :         case GDT_CInt32:
    1006             :         case GDT_CFloat16:
    1007             :         case GDT_CFloat32:
    1008             :         case GDT_CFloat64:
    1009             :         case GDT_TypeCount:
    1010           1 :             break;
    1011             :     }
    1012           1 :     return true;
    1013             : }
    1014             : 
    1015             : /************************************************************************/
    1016             : /*                         GDALIsValueInRangeOf()                       */
    1017             : /************************************************************************/
    1018             : 
    1019             : /**
    1020             :  * \brief Check whether the provided value can be represented in the range
    1021             :  * of the data type, possibly with rounding.
    1022             :  *
    1023             :  * Only implemented for non-complex data types
    1024             :  *
    1025             :  * @param dfValue value to check.
    1026             :  * @param eDT target data type.
    1027             :  *
    1028             :  * @return true if the provided value can be represented in the range
    1029             :  * of the data type, possibly with rounding.
    1030             :  * @since GDAL 3.11
    1031             :  */
    1032          18 : bool GDALIsValueInRangeOf(double dfValue, GDALDataType eDT)
    1033             : {
    1034          18 :     switch (eDT)
    1035             :     {
    1036           2 :         case GDT_Byte:
    1037           2 :             return GDALIsValueInRange<uint8_t>(dfValue);
    1038           1 :         case GDT_Int8:
    1039           1 :             return GDALIsValueInRange<int8_t>(dfValue);
    1040           1 :         case GDT_UInt16:
    1041           1 :             return GDALIsValueInRange<uint16_t>(dfValue);
    1042           1 :         case GDT_Int16:
    1043           1 :             return GDALIsValueInRange<int16_t>(dfValue);
    1044           1 :         case GDT_UInt32:
    1045           1 :             return GDALIsValueInRange<uint32_t>(dfValue);
    1046           1 :         case GDT_Int32:
    1047           1 :             return GDALIsValueInRange<int32_t>(dfValue);
    1048           1 :         case GDT_UInt64:
    1049           1 :             return GDALIsValueInRange<uint64_t>(dfValue);
    1050           1 :         case GDT_Int64:
    1051           1 :             return GDALIsValueInRange<int64_t>(dfValue);
    1052           1 :         case GDT_Float16:
    1053           1 :             return GDALIsValueInRange<GFloat16>(dfValue);
    1054           1 :         case GDT_Float32:
    1055           1 :             return GDALIsValueInRange<float>(dfValue);
    1056           1 :         case GDT_Float64:
    1057           1 :             return true;
    1058           6 :         case GDT_Unknown:
    1059             :         case GDT_CInt16:
    1060             :         case GDT_CInt32:
    1061             :         case GDT_CFloat16:
    1062             :         case GDT_CFloat32:
    1063             :         case GDT_CFloat64:
    1064             :         case GDT_TypeCount:
    1065           6 :             break;
    1066             :     }
    1067           6 :     return true;
    1068             : }
    1069             : 
    1070             : /************************************************************************/
    1071             : /*                        GDALGetNonComplexDataType()                   */
    1072             : /************************************************************************/
    1073             : /**
    1074             :  * \brief Return the base data type for the specified input.
    1075             :  *
    1076             :  * If the input data type is complex this function returns the base type
    1077             :  * i.e. the data type of the real and imaginary parts (non-complex).
    1078             :  * If the input data type is already non-complex, then it is returned
    1079             :  * unchanged.
    1080             :  *
    1081             :  * @param eDataType type, such as GDT_CFloat32.
    1082             :  *
    1083             :  * @return GDAL data type.
    1084             :  */
    1085      510633 : GDALDataType CPL_STDCALL GDALGetNonComplexDataType(GDALDataType eDataType)
    1086             : {
    1087      510633 :     switch (eDataType)
    1088             :     {
    1089         124 :         case GDT_CInt16:
    1090         124 :             return GDT_Int16;
    1091          51 :         case GDT_CInt32:
    1092          51 :             return GDT_Int32;
    1093          14 :         case GDT_CFloat16:
    1094          14 :             return GDT_Float16;
    1095          97 :         case GDT_CFloat32:
    1096          97 :             return GDT_Float32;
    1097          89 :         case GDT_CFloat64:
    1098          89 :             return GDT_Float64;
    1099             : 
    1100      510258 :         case GDT_Byte:
    1101             :         case GDT_UInt16:
    1102             :         case GDT_UInt32:
    1103             :         case GDT_UInt64:
    1104             :         case GDT_Int8:
    1105             :         case GDT_Int16:
    1106             :         case GDT_Int32:
    1107             :         case GDT_Int64:
    1108             :         case GDT_Float16:
    1109             :         case GDT_Float32:
    1110             :         case GDT_Float64:
    1111      510258 :             break;
    1112             : 
    1113           0 :         case GDT_Unknown:
    1114             :         case GDT_TypeCount:
    1115           0 :             break;
    1116             :     }
    1117      510258 :     return eDataType;
    1118             : }
    1119             : 
    1120             : /************************************************************************/
    1121             : /*                        GDALGetAsyncStatusTypeByName()                */
    1122             : /************************************************************************/
    1123             : /**
    1124             :  * Get AsyncStatusType by symbolic name.
    1125             :  *
    1126             :  * Returns a data type corresponding to the given symbolic name. This
    1127             :  * function is opposite to the GDALGetAsyncStatusTypeName().
    1128             :  *
    1129             :  * @param pszName string containing the symbolic name of the type.
    1130             :  *
    1131             :  * @return GDAL AsyncStatus type.
    1132             :  */
    1133             : GDALAsyncStatusType CPL_DLL CPL_STDCALL
    1134           0 : GDALGetAsyncStatusTypeByName(const char *pszName)
    1135             : {
    1136           0 :     VALIDATE_POINTER1(pszName, "GDALGetAsyncStatusTypeByName", GARIO_ERROR);
    1137             : 
    1138           0 :     for (int iType = 0; iType < GARIO_TypeCount; iType++)
    1139             :     {
    1140           0 :         const auto eType = static_cast<GDALAsyncStatusType>(iType);
    1141           0 :         if (GDALGetAsyncStatusTypeName(eType) != nullptr &&
    1142           0 :             EQUAL(GDALGetAsyncStatusTypeName(eType), pszName))
    1143             :         {
    1144           0 :             return eType;
    1145             :         }
    1146             :     }
    1147             : 
    1148           0 :     return GARIO_ERROR;
    1149             : }
    1150             : 
    1151             : /************************************************************************/
    1152             : /*                        GDALGetAsyncStatusTypeName()                 */
    1153             : /************************************************************************/
    1154             : 
    1155             : /**
    1156             :  * Get name of AsyncStatus data type.
    1157             :  *
    1158             :  * Returns a symbolic name for the AsyncStatus data type.  This is essentially
    1159             :  * the enumerated item name with the GARIO_ prefix removed.  So
    1160             :  * GARIO_COMPLETE returns "COMPLETE".  The returned strings are static strings
    1161             :  * and should not be modified or freed by the application.  These strings are
    1162             :  * useful for reporting datatypes in debug statements, errors and other user
    1163             :  * output.
    1164             :  *
    1165             :  * @param eAsyncStatusType type to get name of.
    1166             :  * @return string corresponding to type.
    1167             :  */
    1168             : 
    1169             : const char *CPL_STDCALL
    1170           0 : GDALGetAsyncStatusTypeName(GDALAsyncStatusType eAsyncStatusType)
    1171             : 
    1172             : {
    1173           0 :     switch (eAsyncStatusType)
    1174             :     {
    1175           0 :         case GARIO_PENDING:
    1176           0 :             return "PENDING";
    1177             : 
    1178           0 :         case GARIO_UPDATE:
    1179           0 :             return "UPDATE";
    1180             : 
    1181           0 :         case GARIO_ERROR:
    1182           0 :             return "ERROR";
    1183             : 
    1184           0 :         case GARIO_COMPLETE:
    1185           0 :             return "COMPLETE";
    1186             : 
    1187           0 :         default:
    1188           0 :             return nullptr;
    1189             :     }
    1190             : }
    1191             : 
    1192             : /************************************************************************/
    1193             : /*                  GDALGetPaletteInterpretationName()                  */
    1194             : /************************************************************************/
    1195             : 
    1196             : /**
    1197             :  * \brief Get name of palette interpretation
    1198             :  *
    1199             :  * Returns a symbolic name for the palette interpretation.  This is the
    1200             :  * the enumerated item name with the GPI_ prefix removed.  So GPI_Gray returns
    1201             :  * "Gray".  The returned strings are static strings and should not be modified
    1202             :  * or freed by the application.
    1203             :  *
    1204             :  * @param eInterp palette interpretation to get name of.
    1205             :  * @return string corresponding to palette interpretation.
    1206             :  */
    1207             : 
    1208           9 : const char *GDALGetPaletteInterpretationName(GDALPaletteInterp eInterp)
    1209             : 
    1210             : {
    1211           9 :     switch (eInterp)
    1212             :     {
    1213           0 :         case GPI_Gray:
    1214           0 :             return "Gray";
    1215             : 
    1216           9 :         case GPI_RGB:
    1217           9 :             return "RGB";
    1218             : 
    1219           0 :         case GPI_CMYK:
    1220           0 :             return "CMYK";
    1221             : 
    1222           0 :         case GPI_HLS:
    1223           0 :             return "HLS";
    1224             : 
    1225           0 :         default:
    1226           0 :             return "Unknown";
    1227             :     }
    1228             : }
    1229             : 
    1230             : /************************************************************************/
    1231             : /*                   GDALGetColorInterpretationName()                   */
    1232             : /************************************************************************/
    1233             : 
    1234             : /**
    1235             :  * \brief Get name of color interpretation
    1236             :  *
    1237             :  * Returns a symbolic name for the color interpretation.  This is derived from
    1238             :  * the enumerated item name with the GCI_ prefix removed, but there are some
    1239             :  * variations. So GCI_GrayIndex returns "Gray" and GCI_RedBand returns "Red".
    1240             :  * The returned strings are static strings and should not be modified
    1241             :  * or freed by the application.
    1242             :  *
    1243             :  * @param eInterp color interpretation to get name of.
    1244             :  * @return string corresponding to color interpretation
    1245             :  *         or NULL pointer if invalid enumerator given.
    1246             :  */
    1247             : 
    1248       10299 : const char *GDALGetColorInterpretationName(GDALColorInterp eInterp)
    1249             : 
    1250             : {
    1251             :     static_assert(GCI_IR_Start == GCI_RedEdgeBand + 1);
    1252             :     static_assert(GCI_NIRBand == GCI_IR_Start);
    1253             :     static_assert(GCI_SAR_Start == GCI_IR_End + 1);
    1254             :     static_assert(GCI_Max == GCI_SAR_End);
    1255             : 
    1256       10299 :     switch (eInterp)
    1257             :     {
    1258        2162 :         case GCI_Undefined:
    1259        2162 :             break;
    1260             : 
    1261        2590 :         case GCI_GrayIndex:
    1262        2590 :             return "Gray";
    1263             : 
    1264        1128 :         case GCI_PaletteIndex:
    1265        1128 :             return "Palette";
    1266             : 
    1267        1256 :         case GCI_RedBand:
    1268        1256 :             return "Red";
    1269             : 
    1270         946 :         case GCI_GreenBand:
    1271         946 :             return "Green";
    1272             : 
    1273         654 :         case GCI_BlueBand:
    1274         654 :             return "Blue";
    1275             : 
    1276         345 :         case GCI_AlphaBand:
    1277         345 :             return "Alpha";
    1278             : 
    1279         112 :         case GCI_HueBand:
    1280         112 :             return "Hue";
    1281             : 
    1282         111 :         case GCI_SaturationBand:
    1283         111 :             return "Saturation";
    1284             : 
    1285         110 :         case GCI_LightnessBand:
    1286         110 :             return "Lightness";
    1287             : 
    1288         117 :         case GCI_CyanBand:
    1289         117 :             return "Cyan";
    1290             : 
    1291          99 :         case GCI_MagentaBand:
    1292          99 :             return "Magenta";
    1293             : 
    1294          81 :         case GCI_YellowBand:
    1295          81 :             return "Yellow";
    1296             : 
    1297          62 :         case GCI_BlackBand:
    1298          62 :             return "Black";
    1299             : 
    1300          38 :         case GCI_YCbCr_YBand:
    1301          38 :             return "YCbCr_Y";
    1302             : 
    1303          35 :         case GCI_YCbCr_CbBand:
    1304          35 :             return "YCbCr_Cb";
    1305             : 
    1306          32 :         case GCI_YCbCr_CrBand:
    1307          32 :             return "YCbCr_Cr";
    1308             : 
    1309          30 :         case GCI_PanBand:
    1310          30 :             return "Pan";
    1311             : 
    1312          39 :         case GCI_CoastalBand:
    1313          39 :             return "Coastal";
    1314             : 
    1315          29 :         case GCI_RedEdgeBand:
    1316          29 :             return "RedEdge";
    1317             : 
    1318          34 :         case GCI_NIRBand:
    1319          34 :             return "NIR";
    1320             : 
    1321          26 :         case GCI_SWIRBand:
    1322          26 :             return "SWIR";
    1323             : 
    1324          23 :         case GCI_MWIRBand:
    1325          23 :             return "MWIR";
    1326             : 
    1327          22 :         case GCI_LWIRBand:
    1328          22 :             return "LWIR";
    1329             : 
    1330          21 :         case GCI_TIRBand:
    1331          21 :             return "TIR";
    1332             : 
    1333          22 :         case GCI_OtherIRBand:
    1334          22 :             return "OtherIR";
    1335             : 
    1336          19 :         case GCI_IR_Reserved_1:
    1337          19 :             return "IR_Reserved_1";
    1338             : 
    1339          18 :         case GCI_IR_Reserved_2:
    1340          18 :             return "IR_Reserved_2";
    1341             : 
    1342          17 :         case GCI_IR_Reserved_3:
    1343          17 :             return "IR_Reserved_3";
    1344             : 
    1345          16 :         case GCI_IR_Reserved_4:
    1346          16 :             return "IR_Reserved_4";
    1347             : 
    1348          15 :         case GCI_SAR_Ka_Band:
    1349          15 :             return "SAR_Ka";
    1350             : 
    1351          14 :         case GCI_SAR_K_Band:
    1352          14 :             return "SAR_K";
    1353             : 
    1354          13 :         case GCI_SAR_Ku_Band:
    1355          13 :             return "SAR_Ku";
    1356             : 
    1357          12 :         case GCI_SAR_X_Band:
    1358          12 :             return "SAR_X";
    1359             : 
    1360          11 :         case GCI_SAR_C_Band:
    1361          11 :             return "SAR_C";
    1362             : 
    1363          10 :         case GCI_SAR_S_Band:
    1364          10 :             return "SAR_S";
    1365             : 
    1366           9 :         case GCI_SAR_L_Band:
    1367           9 :             return "SAR_L";
    1368             : 
    1369           8 :         case GCI_SAR_P_Band:
    1370           8 :             return "SAR_P";
    1371             : 
    1372           7 :         case GCI_SAR_Reserved_1:
    1373           7 :             return "SAR_Reserved_1";
    1374             : 
    1375           6 :         case GCI_SAR_Reserved_2:
    1376           6 :             return "SAR_Reserved_2";
    1377             :     }
    1378        2162 :     return "Undefined";
    1379             : }
    1380             : 
    1381             : /************************************************************************/
    1382             : /*                GDALGetColorInterpretationByName()                    */
    1383             : /************************************************************************/
    1384             : 
    1385             : /**
    1386             :  * \brief Get color interpretation by symbolic name.
    1387             :  *
    1388             :  * Returns a color interpretation corresponding to the given symbolic name. This
    1389             :  * function is opposite to the GDALGetColorInterpretationName().
    1390             :  *
    1391             :  * @param pszName string containing the symbolic name of the color
    1392             :  * interpretation.
    1393             :  *
    1394             :  * @return GDAL color interpretation.
    1395             :  *
    1396             :  * @since GDAL 1.7.0
    1397             :  */
    1398             : 
    1399        1996 : GDALColorInterp GDALGetColorInterpretationByName(const char *pszName)
    1400             : 
    1401             : {
    1402        1996 :     VALIDATE_POINTER1(pszName, "GDALGetColorInterpretationByName",
    1403             :                       GCI_Undefined);
    1404             : 
    1405        8861 :     for (int iType = 0; iType <= GCI_Max; iType++)
    1406             :     {
    1407        8857 :         if (EQUAL(GDALGetColorInterpretationName(
    1408             :                       static_cast<GDALColorInterp>(iType)),
    1409             :                   pszName))
    1410             :         {
    1411        1992 :             return static_cast<GDALColorInterp>(iType);
    1412             :         }
    1413             :     }
    1414             : 
    1415             :     // Accept British English spelling
    1416           4 :     if (EQUAL(pszName, "grey"))
    1417           0 :         return GCI_GrayIndex;
    1418             : 
    1419           4 :     return GCI_Undefined;
    1420             : }
    1421             : 
    1422             : /************************************************************************/
    1423             : /*                  GDALGetColorInterpFromSTACCommonName()              */
    1424             : /************************************************************************/
    1425             : 
    1426             : static const struct
    1427             : {
    1428             :     const char *pszName;
    1429             :     GDALColorInterp eInterp;
    1430             : } asSTACCommonNames[] = {
    1431             :     {"pan", GCI_PanBand},
    1432             :     {"coastal", GCI_CoastalBand},
    1433             :     {"blue", GCI_BlueBand},
    1434             :     {"green", GCI_GreenBand},
    1435             :     {"green05", GCI_GreenBand},  // no exact match
    1436             :     {"yellow", GCI_YellowBand},
    1437             :     {"red", GCI_RedBand},
    1438             :     {"rededge", GCI_RedEdgeBand},
    1439             :     {"rededge071", GCI_RedEdgeBand},  // no exact match
    1440             :     {"rededge075", GCI_RedEdgeBand},  // no exact match
    1441             :     {"rededge078", GCI_RedEdgeBand},  // no exact match
    1442             :     {"nir", GCI_NIRBand},
    1443             :     {"nir08", GCI_NIRBand},   // no exact match
    1444             :     {"nir09", GCI_NIRBand},   // no exact match
    1445             :     {"cirrus", GCI_NIRBand},  // no exact match
    1446             :     {nullptr,
    1447             :      GCI_SWIRBand},  // so that GDALGetSTACCommonNameFromColorInterp returns null on GCI_SWIRBand
    1448             :     {"swir16", GCI_SWIRBand},  // no exact match
    1449             :     {"swir22", GCI_SWIRBand},  // no exact match
    1450             :     {"lwir", GCI_LWIRBand},
    1451             :     {"lwir11", GCI_LWIRBand},  // no exact match
    1452             :     {"lwir12", GCI_LWIRBand},  // no exact match
    1453             : };
    1454             : 
    1455             : /** Get color interpreetation from STAC eo:common_name
    1456             :  *
    1457             :  * Cf https://github.com/stac-extensions/eo?tab=readme-ov-file#common-band-names
    1458             :  *
    1459             :  * @since GDAL 3.10
    1460             :  */
    1461          22 : GDALColorInterp GDALGetColorInterpFromSTACCommonName(const char *pszName)
    1462             : {
    1463             : 
    1464          86 :     for (const auto &sAssoc : asSTACCommonNames)
    1465             :     {
    1466          86 :         if (sAssoc.pszName && EQUAL(pszName, sAssoc.pszName))
    1467          22 :             return sAssoc.eInterp;
    1468             :     }
    1469           0 :     return GCI_Undefined;
    1470             : }
    1471             : 
    1472             : /************************************************************************/
    1473             : /*                  GDALGetSTACCommonNameFromColorInterp()              */
    1474             : /************************************************************************/
    1475             : 
    1476             : /** Get STAC eo:common_name from GDAL color interpretation
    1477             :  *
    1478             :  * Cf https://github.com/stac-extensions/eo?tab=readme-ov-file#common-band-names
    1479             :  *
    1480             :  * @return nullptr if there is no match
    1481             :  *
    1482             :  * @since GDAL 3.10
    1483             :  */
    1484         103 : const char *GDALGetSTACCommonNameFromColorInterp(GDALColorInterp eInterp)
    1485             : {
    1486        1881 :     for (const auto &sAssoc : asSTACCommonNames)
    1487             :     {
    1488        1800 :         if (eInterp == sAssoc.eInterp)
    1489          22 :             return sAssoc.pszName;
    1490             :     }
    1491          81 :     return nullptr;
    1492             : }
    1493             : 
    1494             : /************************************************************************/
    1495             : /*                     GDALGetRandomRasterSample()                      */
    1496             : /************************************************************************/
    1497             : 
    1498             : /** Undocumented
    1499             :  * @param hBand undocumented.
    1500             :  * @param nSamples undocumented.
    1501             :  * @param pafSampleBuf undocumented.
    1502             :  * @return undocumented
    1503             :  */
    1504           0 : int CPL_STDCALL GDALGetRandomRasterSample(GDALRasterBandH hBand, int nSamples,
    1505             :                                           float *pafSampleBuf)
    1506             : 
    1507             : {
    1508           0 :     VALIDATE_POINTER1(hBand, "GDALGetRandomRasterSample", 0);
    1509             : 
    1510             :     GDALRasterBand *poBand;
    1511             : 
    1512           0 :     poBand = GDALRasterBand::FromHandle(
    1513             :         GDALGetRasterSampleOverview(hBand, nSamples));
    1514           0 :     CPLAssert(nullptr != poBand);
    1515             : 
    1516             :     /* -------------------------------------------------------------------- */
    1517             :     /*      Figure out the ratio of blocks we will read to get an           */
    1518             :     /*      approximate value.                                              */
    1519             :     /* -------------------------------------------------------------------- */
    1520           0 :     int bGotNoDataValue = FALSE;
    1521             : 
    1522           0 :     double dfNoDataValue = poBand->GetNoDataValue(&bGotNoDataValue);
    1523             : 
    1524           0 :     int nBlockXSize = 0;
    1525           0 :     int nBlockYSize = 0;
    1526           0 :     poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1527             : 
    1528             :     const int nBlocksPerRow =
    1529           0 :         (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
    1530             :     const int nBlocksPerColumn =
    1531           0 :         (poBand->GetYSize() + nBlockYSize - 1) / nBlockYSize;
    1532             : 
    1533           0 :     const GIntBig nBlockPixels =
    1534           0 :         static_cast<GIntBig>(nBlockXSize) * nBlockYSize;
    1535           0 :     const GIntBig nBlockCount =
    1536           0 :         static_cast<GIntBig>(nBlocksPerRow) * nBlocksPerColumn;
    1537             : 
    1538           0 :     if (nBlocksPerRow == 0 || nBlocksPerColumn == 0 || nBlockPixels == 0 ||
    1539             :         nBlockCount == 0)
    1540             :     {
    1541           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1542             :                  "GDALGetRandomRasterSample(): returning because band"
    1543             :                  " appears degenerate.");
    1544             : 
    1545           0 :         return FALSE;
    1546             :     }
    1547             : 
    1548             :     int nSampleRate = static_cast<int>(
    1549           0 :         std::max(1.0, sqrt(static_cast<double>(nBlockCount)) - 2.0));
    1550             : 
    1551           0 :     if (nSampleRate == nBlocksPerRow && nSampleRate > 1)
    1552           0 :         nSampleRate--;
    1553             : 
    1554           0 :     while (nSampleRate > 1 &&
    1555           0 :            ((nBlockCount - 1) / nSampleRate + 1) * nBlockPixels < nSamples)
    1556           0 :         nSampleRate--;
    1557             : 
    1558           0 :     int nBlockSampleRate = 1;
    1559             : 
    1560           0 :     if ((nSamples / ((nBlockCount - 1) / nSampleRate + 1)) != 0)
    1561           0 :         nBlockSampleRate = static_cast<int>(std::max<GIntBig>(
    1562           0 :             1,
    1563           0 :             nBlockPixels / (nSamples / ((nBlockCount - 1) / nSampleRate + 1))));
    1564             : 
    1565           0 :     int nActualSamples = 0;
    1566             : 
    1567           0 :     for (GIntBig iSampleBlock = 0; iSampleBlock < nBlockCount;
    1568           0 :          iSampleBlock += nSampleRate)
    1569             :     {
    1570             : 
    1571           0 :         const int iYBlock = static_cast<int>(iSampleBlock / nBlocksPerRow);
    1572           0 :         const int iXBlock = static_cast<int>(iSampleBlock % nBlocksPerRow);
    1573             : 
    1574             :         GDALRasterBlock *const poBlock =
    1575           0 :             poBand->GetLockedBlockRef(iXBlock, iYBlock);
    1576           0 :         if (poBlock == nullptr)
    1577           0 :             continue;
    1578           0 :         void *pDataRef = poBlock->GetDataRef();
    1579             : 
    1580           0 :         int iXValid = nBlockXSize;
    1581           0 :         if ((iXBlock + 1) * nBlockXSize > poBand->GetXSize())
    1582           0 :             iXValid = poBand->GetXSize() - iXBlock * nBlockXSize;
    1583             : 
    1584           0 :         int iYValid = nBlockYSize;
    1585           0 :         if ((iYBlock + 1) * nBlockYSize > poBand->GetYSize())
    1586           0 :             iYValid = poBand->GetYSize() - iYBlock * nBlockYSize;
    1587             : 
    1588           0 :         int iRemainder = 0;
    1589             : 
    1590           0 :         for (int iY = 0; iY < iYValid; iY++)
    1591             :         {
    1592           0 :             int iX = iRemainder;  // Used after for.
    1593           0 :             for (; iX < iXValid; iX += nBlockSampleRate)
    1594             :             {
    1595           0 :                 double dfValue = 0.0;
    1596           0 :                 const int iOffset = iX + iY * nBlockXSize;
    1597             : 
    1598           0 :                 switch (poBlock->GetDataType())
    1599             :                 {
    1600           0 :                     case GDT_Byte:
    1601           0 :                         dfValue =
    1602           0 :                             reinterpret_cast<const GByte *>(pDataRef)[iOffset];
    1603           0 :                         break;
    1604           0 :                     case GDT_Int8:
    1605           0 :                         dfValue =
    1606           0 :                             reinterpret_cast<const GInt8 *>(pDataRef)[iOffset];
    1607           0 :                         break;
    1608           0 :                     case GDT_UInt16:
    1609           0 :                         dfValue = reinterpret_cast<const GUInt16 *>(
    1610           0 :                             pDataRef)[iOffset];
    1611           0 :                         break;
    1612           0 :                     case GDT_Int16:
    1613           0 :                         dfValue =
    1614           0 :                             reinterpret_cast<const GInt16 *>(pDataRef)[iOffset];
    1615           0 :                         break;
    1616           0 :                     case GDT_UInt32:
    1617           0 :                         dfValue = reinterpret_cast<const GUInt32 *>(
    1618           0 :                             pDataRef)[iOffset];
    1619           0 :                         break;
    1620           0 :                     case GDT_Int32:
    1621           0 :                         dfValue =
    1622           0 :                             reinterpret_cast<const GInt32 *>(pDataRef)[iOffset];
    1623           0 :                         break;
    1624           0 :                     case GDT_UInt64:
    1625           0 :                         dfValue = static_cast<double>(
    1626             :                             reinterpret_cast<const std::uint64_t *>(
    1627           0 :                                 pDataRef)[iOffset]);
    1628           0 :                         break;
    1629           0 :                     case GDT_Int64:
    1630           0 :                         dfValue = static_cast<double>(
    1631             :                             reinterpret_cast<const std::int64_t *>(
    1632           0 :                                 pDataRef)[iOffset]);
    1633           0 :                         break;
    1634           0 :                     case GDT_Float16:
    1635             :                         dfValue = reinterpret_cast<const GFloat16 *>(
    1636           0 :                             pDataRef)[iOffset];
    1637           0 :                         break;
    1638           0 :                     case GDT_Float32:
    1639           0 :                         dfValue =
    1640           0 :                             reinterpret_cast<const float *>(pDataRef)[iOffset];
    1641           0 :                         break;
    1642           0 :                     case GDT_Float64:
    1643           0 :                         dfValue =
    1644           0 :                             reinterpret_cast<const double *>(pDataRef)[iOffset];
    1645           0 :                         break;
    1646           0 :                     case GDT_CInt16:
    1647             :                     {
    1648             :                         // TODO(schwehr): Clean up casts.
    1649           0 :                         const double dfReal = reinterpret_cast<const GInt16 *>(
    1650           0 :                             pDataRef)[iOffset * 2];
    1651           0 :                         const double dfImag = reinterpret_cast<const GInt16 *>(
    1652           0 :                             pDataRef)[iOffset * 2 + 1];
    1653           0 :                         dfValue = sqrt(dfReal * dfReal + dfImag * dfImag);
    1654           0 :                         break;
    1655             :                     }
    1656           0 :                     case GDT_CInt32:
    1657             :                     {
    1658           0 :                         const double dfReal = reinterpret_cast<const GInt32 *>(
    1659           0 :                             pDataRef)[iOffset * 2];
    1660           0 :                         const double dfImag = reinterpret_cast<const GInt32 *>(
    1661           0 :                             pDataRef)[iOffset * 2 + 1];
    1662           0 :                         dfValue = sqrt(dfReal * dfReal + dfImag * dfImag);
    1663           0 :                         break;
    1664             :                     }
    1665           0 :                     case GDT_CFloat16:
    1666             :                     {
    1667             :                         const double dfReal =
    1668             :                             reinterpret_cast<const GFloat16 *>(
    1669           0 :                                 pDataRef)[iOffset * 2];
    1670             :                         const double dfImag =
    1671             :                             reinterpret_cast<const GFloat16 *>(
    1672           0 :                                 pDataRef)[iOffset * 2 + 1];
    1673           0 :                         dfValue = sqrt(dfReal * dfReal + dfImag * dfImag);
    1674           0 :                         break;
    1675             :                     }
    1676           0 :                     case GDT_CFloat32:
    1677             :                     {
    1678           0 :                         const double dfReal = reinterpret_cast<const float *>(
    1679           0 :                             pDataRef)[iOffset * 2];
    1680           0 :                         const double dfImag = reinterpret_cast<const float *>(
    1681           0 :                             pDataRef)[iOffset * 2 + 1];
    1682           0 :                         dfValue = sqrt(dfReal * dfReal + dfImag * dfImag);
    1683           0 :                         break;
    1684             :                     }
    1685           0 :                     case GDT_CFloat64:
    1686             :                     {
    1687           0 :                         const double dfReal = reinterpret_cast<const double *>(
    1688           0 :                             pDataRef)[iOffset * 2];
    1689           0 :                         const double dfImag = reinterpret_cast<const double *>(
    1690           0 :                             pDataRef)[iOffset * 2 + 1];
    1691           0 :                         dfValue = sqrt(dfReal * dfReal + dfImag * dfImag);
    1692           0 :                         break;
    1693             :                     }
    1694           0 :                     case GDT_Unknown:
    1695             :                     case GDT_TypeCount:
    1696           0 :                         CPLAssert(false);
    1697             :                 }
    1698             : 
    1699           0 :                 if (bGotNoDataValue && dfValue == dfNoDataValue)
    1700           0 :                     continue;
    1701             : 
    1702           0 :                 if (nActualSamples < nSamples)
    1703           0 :                     pafSampleBuf[nActualSamples++] =
    1704           0 :                         static_cast<float>(dfValue);
    1705             :             }
    1706             : 
    1707           0 :             iRemainder = iX - iXValid;
    1708             :         }
    1709             : 
    1710           0 :         poBlock->DropLock();
    1711             :     }
    1712             : 
    1713           0 :     return nActualSamples;
    1714             : }
    1715             : 
    1716             : /************************************************************************/
    1717             : /*                             gdal::GCP                                */
    1718             : /************************************************************************/
    1719             : 
    1720             : namespace gdal
    1721             : {
    1722             : /** Constructor. */
    1723       25458 : GCP::GCP(const char *pszId, const char *pszInfo, double dfPixel, double dfLine,
    1724       25458 :          double dfX, double dfY, double dfZ)
    1725       25458 :     : gcp{CPLStrdup(pszId ? pszId : ""),
    1726       25458 :           CPLStrdup(pszInfo ? pszInfo : ""),
    1727             :           dfPixel,
    1728             :           dfLine,
    1729             :           dfX,
    1730             :           dfY,
    1731       25458 :           dfZ}
    1732             : {
    1733             :     static_assert(sizeof(GCP) == sizeof(GDAL_GCP));
    1734       25458 : }
    1735             : 
    1736             : /** Destructor. */
    1737      313516 : GCP::~GCP()
    1738             : {
    1739      156758 :     CPLFree(gcp.pszId);
    1740      156758 :     CPLFree(gcp.pszInfo);
    1741      156758 : }
    1742             : 
    1743             : /** Constructor from a C GDAL_GCP instance. */
    1744      106809 : GCP::GCP(const GDAL_GCP &other)
    1745      106809 :     : gcp{CPLStrdup(other.pszId),
    1746      213618 :           CPLStrdup(other.pszInfo),
    1747      106809 :           other.dfGCPPixel,
    1748      106809 :           other.dfGCPLine,
    1749      106809 :           other.dfGCPX,
    1750      106809 :           other.dfGCPY,
    1751      106809 :           other.dfGCPZ}
    1752             : {
    1753      106809 : }
    1754             : 
    1755             : /** Copy constructor. */
    1756       37931 : GCP::GCP(const GCP &other) : GCP(other.gcp)
    1757             : {
    1758       37931 : }
    1759             : 
    1760             : /** Move constructor. */
    1761       24491 : GCP::GCP(GCP &&other)
    1762       24491 :     : gcp{other.gcp.pszId,     other.gcp.pszInfo, other.gcp.dfGCPPixel,
    1763       24491 :           other.gcp.dfGCPLine, other.gcp.dfGCPX,  other.gcp.dfGCPY,
    1764       24491 :           other.gcp.dfGCPZ}
    1765             : {
    1766       24491 :     other.gcp.pszId = nullptr;
    1767       24491 :     other.gcp.pszInfo = nullptr;
    1768       24491 : }
    1769             : 
    1770             : /** Copy assignment operator. */
    1771           1 : GCP &GCP::operator=(const GCP &other)
    1772             : {
    1773           1 :     if (this != &other)
    1774             :     {
    1775           1 :         CPLFree(gcp.pszId);
    1776           1 :         CPLFree(gcp.pszInfo);
    1777           1 :         gcp = other.gcp;
    1778           1 :         gcp.pszId = CPLStrdup(other.gcp.pszId);
    1779           1 :         gcp.pszInfo = CPLStrdup(other.gcp.pszInfo);
    1780             :     }
    1781           1 :     return *this;
    1782             : }
    1783             : 
    1784             : /** Move assignment operator. */
    1785           1 : GCP &GCP::operator=(GCP &&other)
    1786             : {
    1787           1 :     if (this != &other)
    1788             :     {
    1789           1 :         CPLFree(gcp.pszId);
    1790           1 :         CPLFree(gcp.pszInfo);
    1791           1 :         gcp = other.gcp;
    1792           1 :         other.gcp.pszId = nullptr;
    1793           1 :         other.gcp.pszInfo = nullptr;
    1794             :     }
    1795           1 :     return *this;
    1796             : }
    1797             : 
    1798             : /** Set the 'id' member of the GCP. */
    1799       24455 : void GCP::SetId(const char *pszId)
    1800             : {
    1801       24455 :     CPLFree(gcp.pszId);
    1802       24455 :     gcp.pszId = CPLStrdup(pszId ? pszId : "");
    1803       24455 : }
    1804             : 
    1805             : /** Set the 'info' member of the GCP. */
    1806       24455 : void GCP::SetInfo(const char *pszInfo)
    1807             : {
    1808       24455 :     CPLFree(gcp.pszInfo);
    1809       24455 :     gcp.pszInfo = CPLStrdup(pszInfo ? pszInfo : "");
    1810       24455 : }
    1811             : 
    1812             : /** Cast a vector of gdal::GCP as a C array of GDAL_GCP. */
    1813             : /*static */
    1814         702 : const GDAL_GCP *GCP::c_ptr(const std::vector<GCP> &asGCPs)
    1815             : {
    1816         702 :     return asGCPs.empty() ? nullptr : asGCPs.front().c_ptr();
    1817             : }
    1818             : 
    1819             : /** Creates a vector of GDAL::GCP from a C array of GDAL_GCP. */
    1820             : /*static*/
    1821         314 : std::vector<GCP> GCP::fromC(const GDAL_GCP *pasGCPList, int nGCPCount)
    1822             : {
    1823         314 :     return std::vector<GCP>(pasGCPList, pasGCPList + nGCPCount);
    1824             : }
    1825             : 
    1826             : } /* namespace gdal */
    1827             : 
    1828             : /************************************************************************/
    1829             : /*                            GDALInitGCPs()                            */
    1830             : /************************************************************************/
    1831             : 
    1832             : /** Initialize an array of GCPs.
    1833             :  *
    1834             :  * Numeric values are initialized to 0 and strings to the empty string ""
    1835             :  * allocated with CPLStrdup()
    1836             :  * An array initialized with GDALInitGCPs() must be de-initialized with
    1837             :  * GDALDeinitGCPs().
    1838             :  *
    1839             :  * @param nCount number of GCPs in psGCP
    1840             :  * @param psGCP array of GCPs of size nCount.
    1841             :  */
    1842        1254 : void CPL_STDCALL GDALInitGCPs(int nCount, GDAL_GCP *psGCP)
    1843             : 
    1844             : {
    1845        1254 :     if (nCount > 0)
    1846             :     {
    1847         613 :         VALIDATE_POINTER0(psGCP, "GDALInitGCPs");
    1848             :     }
    1849             : 
    1850        5969 :     for (int iGCP = 0; iGCP < nCount; iGCP++)
    1851             :     {
    1852        4715 :         memset(psGCP, 0, sizeof(GDAL_GCP));
    1853        4715 :         psGCP->pszId = CPLStrdup("");
    1854        4715 :         psGCP->pszInfo = CPLStrdup("");
    1855        4715 :         psGCP++;
    1856             :     }
    1857             : }
    1858             : 
    1859             : /************************************************************************/
    1860             : /*                           GDALDeinitGCPs()                           */
    1861             : /************************************************************************/
    1862             : 
    1863             : /** De-initialize an array of GCPs (initialized with GDALInitGCPs())
    1864             :  *
    1865             :  * @param nCount number of GCPs in psGCP
    1866             :  * @param psGCP array of GCPs of size nCount.
    1867             :  */
    1868        1372 : void CPL_STDCALL GDALDeinitGCPs(int nCount, GDAL_GCP *psGCP)
    1869             : 
    1870             : {
    1871        1372 :     if (nCount > 0)
    1872             :     {
    1873         459 :         VALIDATE_POINTER0(psGCP, "GDALDeinitGCPs");
    1874             :     }
    1875             : 
    1876        6195 :     for (int iGCP = 0; iGCP < nCount; iGCP++)
    1877             :     {
    1878        4823 :         CPLFree(psGCP->pszId);
    1879        4823 :         CPLFree(psGCP->pszInfo);
    1880        4823 :         psGCP++;
    1881             :     }
    1882             : }
    1883             : 
    1884             : /************************************************************************/
    1885             : /*                         GDALDuplicateGCPs()                          */
    1886             : /************************************************************************/
    1887             : 
    1888             : /** Duplicate an array of GCPs
    1889             :  *
    1890             :  * The return must be freed with GDALDeinitGCPs() followed by CPLFree()
    1891             :  *
    1892             :  * @param nCount number of GCPs in psGCP
    1893             :  * @param pasGCPList array of GCPs of size nCount.
    1894             :  */
    1895         726 : GDAL_GCP *CPL_STDCALL GDALDuplicateGCPs(int nCount, const GDAL_GCP *pasGCPList)
    1896             : 
    1897             : {
    1898             :     GDAL_GCP *pasReturn =
    1899         726 :         static_cast<GDAL_GCP *>(CPLMalloc(sizeof(GDAL_GCP) * nCount));
    1900         726 :     GDALInitGCPs(nCount, pasReturn);
    1901             : 
    1902        3954 :     for (int iGCP = 0; iGCP < nCount; iGCP++)
    1903             :     {
    1904        3228 :         CPLFree(pasReturn[iGCP].pszId);
    1905        3228 :         pasReturn[iGCP].pszId = CPLStrdup(pasGCPList[iGCP].pszId);
    1906             : 
    1907        3228 :         CPLFree(pasReturn[iGCP].pszInfo);
    1908        3228 :         pasReturn[iGCP].pszInfo = CPLStrdup(pasGCPList[iGCP].pszInfo);
    1909             : 
    1910        3228 :         pasReturn[iGCP].dfGCPPixel = pasGCPList[iGCP].dfGCPPixel;
    1911        3228 :         pasReturn[iGCP].dfGCPLine = pasGCPList[iGCP].dfGCPLine;
    1912        3228 :         pasReturn[iGCP].dfGCPX = pasGCPList[iGCP].dfGCPX;
    1913        3228 :         pasReturn[iGCP].dfGCPY = pasGCPList[iGCP].dfGCPY;
    1914        3228 :         pasReturn[iGCP].dfGCPZ = pasGCPList[iGCP].dfGCPZ;
    1915             :     }
    1916             : 
    1917         726 :     return pasReturn;
    1918             : }
    1919             : 
    1920             : /************************************************************************/
    1921             : /*                       GDALFindAssociatedFile()                       */
    1922             : /************************************************************************/
    1923             : 
    1924             : /**
    1925             :  * \brief Find file with alternate extension.
    1926             :  *
    1927             :  * Finds the file with the indicated extension, substituting it in place
    1928             :  * of the extension of the base filename.  Generally used to search for
    1929             :  * associated files like world files .RPB files, etc.  If necessary, the
    1930             :  * extension will be tried in both upper and lower case.  If a sibling file
    1931             :  * list is available it will be used instead of doing VSIStatExL() calls to
    1932             :  * probe the file system.
    1933             :  *
    1934             :  * Note that the result is a dynamic CPLString so this method should not
    1935             :  * be used in a situation where there could be cross heap issues.  It is
    1936             :  * generally imprudent for application built on GDAL to use this function
    1937             :  * unless they are sure they will always use the same runtime heap as GDAL.
    1938             :  *
    1939             :  * @param pszBaseFilename the filename relative to which to search.
    1940             :  * @param pszExt the target extension in either upper or lower case.
    1941             :  * @param papszSiblingFiles the list of files in the same directory as
    1942             :  * pszBaseFilename or NULL if they are not known.
    1943             :  * @param nFlags special options controlling search.  None defined yet, just
    1944             :  * pass 0.
    1945             :  *
    1946             :  * @return an empty string if the target is not found, otherwise the target
    1947             :  * file with similar path style as the pszBaseFilename.
    1948             :  */
    1949             : 
    1950             : /**/
    1951             : /**/
    1952             : 
    1953       39188 : CPLString GDALFindAssociatedFile(const char *pszBaseFilename,
    1954             :                                  const char *pszExt,
    1955             :                                  CSLConstList papszSiblingFiles,
    1956             :                                  CPL_UNUSED int nFlags)
    1957             : 
    1958             : {
    1959       78376 :     CPLString osTarget = CPLResetExtensionSafe(pszBaseFilename, pszExt);
    1960             : 
    1961       78112 :     if (papszSiblingFiles == nullptr ||
    1962             :         // cppcheck-suppress knownConditionTrueFalse
    1963       38924 :         !GDALCanReliablyUseSiblingFileList(osTarget.c_str()))
    1964             :     {
    1965             :         VSIStatBufL sStatBuf;
    1966             : 
    1967         264 :         if (VSIStatExL(osTarget, &sStatBuf, VSI_STAT_EXISTS_FLAG) != 0)
    1968             :         {
    1969         249 :             CPLString osAltExt = pszExt;
    1970             : 
    1971         249 :             if (islower(static_cast<unsigned char>(pszExt[0])))
    1972           0 :                 osAltExt = osAltExt.toupper();
    1973             :             else
    1974         249 :                 osAltExt = osAltExt.tolower();
    1975             : 
    1976         249 :             osTarget = CPLResetExtensionSafe(pszBaseFilename, osAltExt);
    1977             : 
    1978         249 :             if (VSIStatExL(osTarget, &sStatBuf, VSI_STAT_EXISTS_FLAG) != 0)
    1979         247 :                 return "";
    1980             :         }
    1981             :     }
    1982             :     else
    1983             :     {
    1984             :         const int iSibling =
    1985       38924 :             CSLFindString(papszSiblingFiles, CPLGetFilename(osTarget));
    1986       38924 :         if (iSibling < 0)
    1987       38873 :             return "";
    1988             : 
    1989          51 :         osTarget.resize(osTarget.size() - strlen(papszSiblingFiles[iSibling]));
    1990          51 :         osTarget += papszSiblingFiles[iSibling];
    1991             :     }
    1992             : 
    1993          68 :     return osTarget;
    1994             : }
    1995             : 
    1996             : /************************************************************************/
    1997             : /*                         GDALLoadOziMapFile()                         */
    1998             : /************************************************************************/
    1999             : 
    2000             : /** Helper function for translator implementer wanting support for OZI .map
    2001             :  *
    2002             :  * @param pszFilename filename of .tab file
    2003             :  * @param padfGeoTransform output geotransform. Must hold 6 doubles.
    2004             :  * @param ppszWKT output pointer to a string that will be allocated with
    2005             :  * CPLMalloc().
    2006             :  * @param pnGCPCount output pointer to GCP count.
    2007             :  * @param ppasGCPs outputer pointer to an array of GCPs.
    2008             :  * @return TRUE in case of success, FALSE otherwise.
    2009             :  */
    2010           0 : int CPL_STDCALL GDALLoadOziMapFile(const char *pszFilename,
    2011             :                                    double *padfGeoTransform, char **ppszWKT,
    2012             :                                    int *pnGCPCount, GDAL_GCP **ppasGCPs)
    2013             : 
    2014             : {
    2015           0 :     VALIDATE_POINTER1(pszFilename, "GDALLoadOziMapFile", FALSE);
    2016           0 :     VALIDATE_POINTER1(padfGeoTransform, "GDALLoadOziMapFile", FALSE);
    2017           0 :     VALIDATE_POINTER1(pnGCPCount, "GDALLoadOziMapFile", FALSE);
    2018           0 :     VALIDATE_POINTER1(ppasGCPs, "GDALLoadOziMapFile", FALSE);
    2019             : 
    2020           0 :     char **papszLines = CSLLoad2(pszFilename, 1000, 200, nullptr);
    2021             : 
    2022           0 :     if (!papszLines)
    2023           0 :         return FALSE;
    2024             : 
    2025           0 :     int nLines = CSLCount(papszLines);
    2026             : 
    2027             :     // Check the OziExplorer Map file signature
    2028           0 :     if (nLines < 5 ||
    2029           0 :         !STARTS_WITH_CI(papszLines[0], "OziExplorer Map Data File Version "))
    2030             :     {
    2031           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2032             :                  "GDALLoadOziMapFile(): file \"%s\" is not in OziExplorer Map "
    2033             :                  "format.",
    2034             :                  pszFilename);
    2035           0 :         CSLDestroy(papszLines);
    2036           0 :         return FALSE;
    2037             :     }
    2038             : 
    2039           0 :     OGRSpatialReference oSRS;
    2040           0 :     OGRErr eErr = OGRERR_NONE;
    2041             : 
    2042             :     /* The Map Scale Factor has been introduced recently on the 6th line */
    2043             :     /* and is a trick that is used to just change that line without changing */
    2044             :     /* the rest of the MAP file but providing an imagery that is smaller or
    2045             :      * larger */
    2046             :     /* so we have to correct the pixel/line values read in the .MAP file so they
    2047             :      */
    2048             :     /* match the actual imagery dimension. Well, this is a bad summary of what
    2049             :      */
    2050             :     /* is explained at
    2051             :      * http://tech.groups.yahoo.com/group/OziUsers-L/message/12484 */
    2052           0 :     double dfMSF = 1;
    2053             : 
    2054           0 :     for (int iLine = 5; iLine < nLines; iLine++)
    2055             :     {
    2056           0 :         if (STARTS_WITH_CI(papszLines[iLine], "MSF,"))
    2057             :         {
    2058           0 :             dfMSF = CPLAtof(papszLines[iLine] + 4);
    2059           0 :             if (dfMSF <= 0.01) /* Suspicious values */
    2060             :             {
    2061           0 :                 CPLDebug("OZI", "Suspicious MSF value : %s", papszLines[iLine]);
    2062           0 :                 dfMSF = 1;
    2063             :             }
    2064             :         }
    2065             :     }
    2066             : 
    2067           0 :     eErr = oSRS.importFromOzi(papszLines);
    2068           0 :     if (eErr == OGRERR_NONE)
    2069             :     {
    2070           0 :         if (ppszWKT != nullptr)
    2071           0 :             oSRS.exportToWkt(ppszWKT);
    2072             :     }
    2073             : 
    2074           0 :     int nCoordinateCount = 0;
    2075             :     // TODO(schwehr): Initialize asGCPs.
    2076             :     GDAL_GCP asGCPs[30];
    2077             : 
    2078             :     // Iterate all lines in the MAP-file
    2079           0 :     for (int iLine = 5; iLine < nLines; iLine++)
    2080             :     {
    2081           0 :         char **papszTok = CSLTokenizeString2(
    2082           0 :             papszLines[iLine], ",",
    2083             :             CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES);
    2084             : 
    2085           0 :         if (CSLCount(papszTok) < 12)
    2086             :         {
    2087           0 :             CSLDestroy(papszTok);
    2088           0 :             continue;
    2089             :         }
    2090             : 
    2091           0 :         if (CSLCount(papszTok) >= 17 && STARTS_WITH_CI(papszTok[0], "Point") &&
    2092           0 :             !EQUAL(papszTok[2], "") && !EQUAL(papszTok[3], "") &&
    2093             :             nCoordinateCount < static_cast<int>(CPL_ARRAYSIZE(asGCPs)))
    2094             :         {
    2095           0 :             bool bReadOk = false;
    2096           0 :             double dfLon = 0.0;
    2097           0 :             double dfLat = 0.0;
    2098             : 
    2099           0 :             if (!EQUAL(papszTok[6], "") && !EQUAL(papszTok[7], "") &&
    2100           0 :                 !EQUAL(papszTok[9], "") && !EQUAL(papszTok[10], ""))
    2101             :             {
    2102             :                 // Set geographical coordinates of the pixels
    2103           0 :                 dfLon = CPLAtofM(papszTok[9]) + CPLAtofM(papszTok[10]) / 60.0;
    2104           0 :                 dfLat = CPLAtofM(papszTok[6]) + CPLAtofM(papszTok[7]) / 60.0;
    2105           0 :                 if (EQUAL(papszTok[11], "W"))
    2106           0 :                     dfLon = -dfLon;
    2107           0 :                 if (EQUAL(papszTok[8], "S"))
    2108           0 :                     dfLat = -dfLat;
    2109             : 
    2110             :                 // Transform from the geographical coordinates into projected
    2111             :                 // coordinates.
    2112           0 :                 if (eErr == OGRERR_NONE)
    2113             :                 {
    2114           0 :                     OGRSpatialReference *poLongLat = oSRS.CloneGeogCS();
    2115             : 
    2116           0 :                     if (poLongLat)
    2117             :                     {
    2118           0 :                         oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2119           0 :                         poLongLat->SetAxisMappingStrategy(
    2120             :                             OAMS_TRADITIONAL_GIS_ORDER);
    2121             : 
    2122             :                         OGRCoordinateTransformation *poTransform =
    2123           0 :                             OGRCreateCoordinateTransformation(poLongLat, &oSRS);
    2124           0 :                         if (poTransform)
    2125             :                         {
    2126           0 :                             bReadOk = CPL_TO_BOOL(
    2127             :                                 poTransform->Transform(1, &dfLon, &dfLat));
    2128           0 :                             delete poTransform;
    2129             :                         }
    2130           0 :                         delete poLongLat;
    2131             :                     }
    2132           0 :                 }
    2133             :             }
    2134           0 :             else if (!EQUAL(papszTok[14], "") && !EQUAL(papszTok[15], ""))
    2135             :             {
    2136             :                 // Set cartesian coordinates of the pixels.
    2137           0 :                 dfLon = CPLAtofM(papszTok[14]);
    2138           0 :                 dfLat = CPLAtofM(papszTok[15]);
    2139           0 :                 bReadOk = true;
    2140             : 
    2141             :                 // if ( EQUAL(papszTok[16], "S") )
    2142             :                 //     dfLat = -dfLat;
    2143             :             }
    2144             : 
    2145           0 :             if (bReadOk)
    2146             :             {
    2147           0 :                 GDALInitGCPs(1, asGCPs + nCoordinateCount);
    2148             : 
    2149             :                 // Set pixel/line part
    2150           0 :                 asGCPs[nCoordinateCount].dfGCPPixel =
    2151           0 :                     CPLAtofM(papszTok[2]) / dfMSF;
    2152           0 :                 asGCPs[nCoordinateCount].dfGCPLine =
    2153           0 :                     CPLAtofM(papszTok[3]) / dfMSF;
    2154             : 
    2155           0 :                 asGCPs[nCoordinateCount].dfGCPX = dfLon;
    2156           0 :                 asGCPs[nCoordinateCount].dfGCPY = dfLat;
    2157             : 
    2158           0 :                 nCoordinateCount++;
    2159             :             }
    2160             :         }
    2161             : 
    2162           0 :         CSLDestroy(papszTok);
    2163             :     }
    2164             : 
    2165           0 :     CSLDestroy(papszLines);
    2166             : 
    2167           0 :     if (nCoordinateCount == 0)
    2168             :     {
    2169           0 :         CPLDebug("GDAL", "GDALLoadOziMapFile(\"%s\") did read no GCPs.",
    2170             :                  pszFilename);
    2171           0 :         return FALSE;
    2172             :     }
    2173             : 
    2174             :     /* -------------------------------------------------------------------- */
    2175             :     /*      Try to convert the GCPs into a geotransform definition, if      */
    2176             :     /*      possible.  Otherwise we will need to use them as GCPs.          */
    2177             :     /* -------------------------------------------------------------------- */
    2178           0 :     if (!GDALGCPsToGeoTransform(
    2179             :             nCoordinateCount, asGCPs, padfGeoTransform,
    2180           0 :             CPLTestBool(CPLGetConfigOption("OZI_APPROX_GEOTRANSFORM", "NO"))))
    2181             :     {
    2182           0 :         if (pnGCPCount && ppasGCPs)
    2183             :         {
    2184           0 :             CPLDebug(
    2185             :                 "GDAL",
    2186             :                 "GDALLoadOziMapFile(%s) found file, was not able to derive a\n"
    2187             :                 "first order geotransform.  Using points as GCPs.",
    2188             :                 pszFilename);
    2189             : 
    2190           0 :             *ppasGCPs = static_cast<GDAL_GCP *>(
    2191           0 :                 CPLCalloc(sizeof(GDAL_GCP), nCoordinateCount));
    2192           0 :             memcpy(*ppasGCPs, asGCPs, sizeof(GDAL_GCP) * nCoordinateCount);
    2193           0 :             *pnGCPCount = nCoordinateCount;
    2194             :         }
    2195             :     }
    2196             :     else
    2197             :     {
    2198           0 :         GDALDeinitGCPs(nCoordinateCount, asGCPs);
    2199             :     }
    2200             : 
    2201           0 :     return TRUE;
    2202             : }
    2203             : 
    2204             : /************************************************************************/
    2205             : /*                       GDALReadOziMapFile()                           */
    2206             : /************************************************************************/
    2207             : 
    2208             : /** Helper function for translator implementer wanting support for OZI .map
    2209             :  *
    2210             :  * @param pszBaseFilename filename whose basename will help building the .map
    2211             :  * filename.
    2212             :  * @param padfGeoTransform output geotransform. Must hold 6 doubles.
    2213             :  * @param ppszWKT output pointer to a string that will be allocated with
    2214             :  * CPLMalloc().
    2215             :  * @param pnGCPCount output pointer to GCP count.
    2216             :  * @param ppasGCPs outputer pointer to an array of GCPs.
    2217             :  * @return TRUE in case of success, FALSE otherwise.
    2218             :  */
    2219           0 : int CPL_STDCALL GDALReadOziMapFile(const char *pszBaseFilename,
    2220             :                                    double *padfGeoTransform, char **ppszWKT,
    2221             :                                    int *pnGCPCount, GDAL_GCP **ppasGCPs)
    2222             : 
    2223             : {
    2224             :     /* -------------------------------------------------------------------- */
    2225             :     /*      Try lower case, then upper case.                                */
    2226             :     /* -------------------------------------------------------------------- */
    2227           0 :     std::string osOzi = CPLResetExtensionSafe(pszBaseFilename, "map");
    2228             : 
    2229           0 :     VSILFILE *fpOzi = VSIFOpenL(osOzi.c_str(), "rt");
    2230             : 
    2231           0 :     if (fpOzi == nullptr && VSIIsCaseSensitiveFS(osOzi.c_str()))
    2232             :     {
    2233           0 :         osOzi = CPLResetExtensionSafe(pszBaseFilename, "MAP");
    2234           0 :         fpOzi = VSIFOpenL(osOzi.c_str(), "rt");
    2235             :     }
    2236             : 
    2237           0 :     if (fpOzi == nullptr)
    2238           0 :         return FALSE;
    2239             : 
    2240           0 :     CPL_IGNORE_RET_VAL(VSIFCloseL(fpOzi));
    2241             : 
    2242             :     /* -------------------------------------------------------------------- */
    2243             :     /*      We found the file, now load and parse it.                       */
    2244             :     /* -------------------------------------------------------------------- */
    2245           0 :     return GDALLoadOziMapFile(osOzi.c_str(), padfGeoTransform, ppszWKT,
    2246           0 :                               pnGCPCount, ppasGCPs);
    2247             : }
    2248             : 
    2249             : /************************************************************************/
    2250             : /*                         GDALLoadTabFile()                            */
    2251             : /*                                                                      */
    2252             : /************************************************************************/
    2253             : 
    2254             : /** Helper function for translator implementer wanting support for MapInfo
    2255             :  * .tab files.
    2256             :  *
    2257             :  * @param pszFilename filename of .tab
    2258             :  * @param padfGeoTransform output geotransform. Must hold 6 doubles.
    2259             :  * @param ppszWKT output pointer to a string that will be allocated with
    2260             :  * CPLMalloc().
    2261             :  * @param pnGCPCount output pointer to GCP count.
    2262             :  * @param ppasGCPs outputer pointer to an array of GCPs.
    2263             :  * @return TRUE in case of success, FALSE otherwise.
    2264             :  */
    2265          14 : int CPL_STDCALL GDALLoadTabFile(const char *pszFilename,
    2266             :                                 double *padfGeoTransform, char **ppszWKT,
    2267             :                                 int *pnGCPCount, GDAL_GCP **ppasGCPs)
    2268             : 
    2269             : {
    2270          14 :     char **papszLines = CSLLoad2(pszFilename, 1000, 200, nullptr);
    2271             : 
    2272          14 :     if (!papszLines)
    2273           0 :         return FALSE;
    2274             : 
    2275          14 :     char **papszTok = nullptr;
    2276          14 :     bool bTypeRasterFound = false;
    2277          14 :     bool bInsideTableDef = false;
    2278          14 :     int nCoordinateCount = 0;
    2279             :     GDAL_GCP asGCPs[256];  // TODO(schwehr): Initialize.
    2280          14 :     const int numLines = CSLCount(papszLines);
    2281             : 
    2282             :     // Iterate all lines in the TAB-file
    2283         196 :     for (int iLine = 0; iLine < numLines; iLine++)
    2284             :     {
    2285         182 :         CSLDestroy(papszTok);
    2286             :         papszTok =
    2287         182 :             CSLTokenizeStringComplex(papszLines[iLine], " \t(),;", TRUE, FALSE);
    2288             : 
    2289         182 :         if (CSLCount(papszTok) < 2)
    2290          28 :             continue;
    2291             : 
    2292             :         // Did we find table definition
    2293         154 :         if (EQUAL(papszTok[0], "Definition") && EQUAL(papszTok[1], "Table"))
    2294             :         {
    2295          14 :             bInsideTableDef = TRUE;
    2296             :         }
    2297         140 :         else if (bInsideTableDef && (EQUAL(papszTok[0], "Type")))
    2298             :         {
    2299             :             // Only RASTER-type will be handled
    2300          14 :             if (EQUAL(papszTok[1], "RASTER"))
    2301             :             {
    2302          14 :                 bTypeRasterFound = true;
    2303             :             }
    2304             :             else
    2305             :             {
    2306           0 :                 CSLDestroy(papszTok);
    2307           0 :                 CSLDestroy(papszLines);
    2308           0 :                 return FALSE;
    2309             :             }
    2310             :         }
    2311          84 :         else if (bTypeRasterFound && bInsideTableDef &&
    2312         210 :                  CSLCount(papszTok) > 4 && EQUAL(papszTok[4], "Label") &&
    2313             :                  nCoordinateCount < static_cast<int>(CPL_ARRAYSIZE(asGCPs)))
    2314             :         {
    2315          56 :             GDALInitGCPs(1, asGCPs + nCoordinateCount);
    2316             : 
    2317          56 :             asGCPs[nCoordinateCount].dfGCPPixel = CPLAtofM(papszTok[2]);
    2318          56 :             asGCPs[nCoordinateCount].dfGCPLine = CPLAtofM(papszTok[3]);
    2319          56 :             asGCPs[nCoordinateCount].dfGCPX = CPLAtofM(papszTok[0]);
    2320          56 :             asGCPs[nCoordinateCount].dfGCPY = CPLAtofM(papszTok[1]);
    2321          56 :             if (papszTok[5] != nullptr)
    2322             :             {
    2323          56 :                 CPLFree(asGCPs[nCoordinateCount].pszId);
    2324          56 :                 asGCPs[nCoordinateCount].pszId = CPLStrdup(papszTok[5]);
    2325             :             }
    2326             : 
    2327          56 :             nCoordinateCount++;
    2328             :         }
    2329          70 :         else if (bTypeRasterFound && bInsideTableDef &&
    2330          28 :                  EQUAL(papszTok[0], "CoordSys") && ppszWKT != nullptr)
    2331             :         {
    2332          28 :             OGRSpatialReference oSRS;
    2333             : 
    2334          14 :             if (oSRS.importFromMICoordSys(papszLines[iLine]) == OGRERR_NONE)
    2335          28 :                 oSRS.exportToWkt(ppszWKT);
    2336             :         }
    2337          70 :         else if (EQUAL(papszTok[0], "Units") && CSLCount(papszTok) > 1 &&
    2338          14 :                  EQUAL(papszTok[1], "degree"))
    2339             :         {
    2340             :             /*
    2341             :             ** If we have units of "degree", but a projected coordinate
    2342             :             ** system we need to convert it to geographic.  See to01_02.TAB.
    2343             :             */
    2344           0 :             if (ppszWKT != nullptr && *ppszWKT != nullptr &&
    2345           0 :                 STARTS_WITH_CI(*ppszWKT, "PROJCS"))
    2346             :             {
    2347           0 :                 OGRSpatialReference oSRS;
    2348           0 :                 oSRS.importFromWkt(*ppszWKT);
    2349             : 
    2350           0 :                 OGRSpatialReference oSRSGeogCS;
    2351           0 :                 oSRSGeogCS.CopyGeogCSFrom(&oSRS);
    2352           0 :                 CPLFree(*ppszWKT);
    2353             : 
    2354           0 :                 oSRSGeogCS.exportToWkt(ppszWKT);
    2355             :             }
    2356             :         }
    2357             :     }
    2358             : 
    2359          14 :     CSLDestroy(papszTok);
    2360          14 :     CSLDestroy(papszLines);
    2361             : 
    2362          14 :     if (nCoordinateCount == 0)
    2363             :     {
    2364           0 :         CPLDebug("GDAL", "GDALLoadTabFile(%s) did not get any GCPs.",
    2365             :                  pszFilename);
    2366           0 :         return FALSE;
    2367             :     }
    2368             : 
    2369             :     /* -------------------------------------------------------------------- */
    2370             :     /*      Try to convert the GCPs into a geotransform definition, if      */
    2371             :     /*      possible.  Otherwise we will need to use them as GCPs.          */
    2372             :     /* -------------------------------------------------------------------- */
    2373          14 :     if (!GDALGCPsToGeoTransform(
    2374             :             nCoordinateCount, asGCPs, padfGeoTransform,
    2375          14 :             CPLTestBool(CPLGetConfigOption("TAB_APPROX_GEOTRANSFORM", "NO"))))
    2376             :     {
    2377           0 :         if (pnGCPCount && ppasGCPs)
    2378             :         {
    2379           0 :             CPLDebug("GDAL",
    2380             :                      "GDALLoadTabFile(%s) found file, was not able to derive a "
    2381             :                      "first order geotransform.  Using points as GCPs.",
    2382             :                      pszFilename);
    2383             : 
    2384           0 :             *ppasGCPs = static_cast<GDAL_GCP *>(
    2385           0 :                 CPLCalloc(sizeof(GDAL_GCP), nCoordinateCount));
    2386           0 :             memcpy(*ppasGCPs, asGCPs, sizeof(GDAL_GCP) * nCoordinateCount);
    2387           0 :             *pnGCPCount = nCoordinateCount;
    2388             :         }
    2389             :     }
    2390             :     else
    2391             :     {
    2392          14 :         GDALDeinitGCPs(nCoordinateCount, asGCPs);
    2393             :     }
    2394             : 
    2395          14 :     return TRUE;
    2396             : }
    2397             : 
    2398             : /************************************************************************/
    2399             : /*                         GDALReadTabFile()                            */
    2400             : /************************************************************************/
    2401             : 
    2402             : /** Helper function for translator implementer wanting support for MapInfo
    2403             :  * .tab files.
    2404             :  *
    2405             :  * @param pszBaseFilename filename whose basename will help building the .tab
    2406             :  * filename.
    2407             :  * @param padfGeoTransform output geotransform. Must hold 6 doubles.
    2408             :  * @param ppszWKT output pointer to a string that will be allocated with
    2409             :  * CPLMalloc().
    2410             :  * @param pnGCPCount output pointer to GCP count.
    2411             :  * @param ppasGCPs outputer pointer to an array of GCPs.
    2412             :  * @return TRUE in case of success, FALSE otherwise.
    2413             :  */
    2414           0 : int CPL_STDCALL GDALReadTabFile(const char *pszBaseFilename,
    2415             :                                 double *padfGeoTransform, char **ppszWKT,
    2416             :                                 int *pnGCPCount, GDAL_GCP **ppasGCPs)
    2417             : 
    2418             : {
    2419           0 :     return GDALReadTabFile2(pszBaseFilename, padfGeoTransform, ppszWKT,
    2420           0 :                             pnGCPCount, ppasGCPs, nullptr, nullptr);
    2421             : }
    2422             : 
    2423        5775 : int GDALReadTabFile2(const char *pszBaseFilename, double *padfGeoTransform,
    2424             :                      char **ppszWKT, int *pnGCPCount, GDAL_GCP **ppasGCPs,
    2425             :                      CSLConstList papszSiblingFiles, char **ppszTabFileNameOut)
    2426             : {
    2427        5775 :     if (ppszTabFileNameOut)
    2428        5775 :         *ppszTabFileNameOut = nullptr;
    2429             : 
    2430        5775 :     if (!GDALCanFileAcceptSidecarFile(pszBaseFilename))
    2431           0 :         return FALSE;
    2432             : 
    2433       11550 :     std::string osTAB = CPLResetExtensionSafe(pszBaseFilename, "tab");
    2434             : 
    2435       11500 :     if (papszSiblingFiles &&
    2436             :         // cppcheck-suppress knownConditionTrueFalse
    2437        5725 :         GDALCanReliablyUseSiblingFileList(osTAB.c_str()))
    2438             :     {
    2439             :         int iSibling =
    2440        5725 :             CSLFindString(papszSiblingFiles, CPLGetFilename(osTAB.c_str()));
    2441        5725 :         if (iSibling >= 0)
    2442             :         {
    2443          14 :             CPLString osTabFilename = pszBaseFilename;
    2444          28 :             osTabFilename.resize(strlen(pszBaseFilename) -
    2445          14 :                                  strlen(CPLGetFilename(pszBaseFilename)));
    2446          14 :             osTabFilename += papszSiblingFiles[iSibling];
    2447          14 :             if (GDALLoadTabFile(osTabFilename, padfGeoTransform, ppszWKT,
    2448          14 :                                 pnGCPCount, ppasGCPs))
    2449             :             {
    2450          14 :                 if (ppszTabFileNameOut)
    2451          14 :                     *ppszTabFileNameOut = CPLStrdup(osTabFilename);
    2452          14 :                 return TRUE;
    2453             :             }
    2454             :         }
    2455        5711 :         return FALSE;
    2456             :     }
    2457             : 
    2458             :     /* -------------------------------------------------------------------- */
    2459             :     /*      Try lower case, then upper case.                                */
    2460             :     /* -------------------------------------------------------------------- */
    2461             : 
    2462          50 :     VSILFILE *fpTAB = VSIFOpenL(osTAB.c_str(), "rt");
    2463             : 
    2464          50 :     if (fpTAB == nullptr && VSIIsCaseSensitiveFS(osTAB.c_str()))
    2465             :     {
    2466          50 :         osTAB = CPLResetExtensionSafe(pszBaseFilename, "TAB");
    2467          50 :         fpTAB = VSIFOpenL(osTAB.c_str(), "rt");
    2468             :     }
    2469             : 
    2470          50 :     if (fpTAB == nullptr)
    2471          50 :         return FALSE;
    2472             : 
    2473           0 :     CPL_IGNORE_RET_VAL(VSIFCloseL(fpTAB));
    2474             : 
    2475             :     /* -------------------------------------------------------------------- */
    2476             :     /*      We found the file, now load and parse it.                       */
    2477             :     /* -------------------------------------------------------------------- */
    2478           0 :     if (GDALLoadTabFile(osTAB.c_str(), padfGeoTransform, ppszWKT, pnGCPCount,
    2479           0 :                         ppasGCPs))
    2480             :     {
    2481           0 :         if (ppszTabFileNameOut)
    2482           0 :             *ppszTabFileNameOut = CPLStrdup(osTAB.c_str());
    2483           0 :         return TRUE;
    2484             :     }
    2485           0 :     return FALSE;
    2486             : }
    2487             : 
    2488             : /************************************************************************/
    2489             : /*                         GDALLoadWorldFile()                          */
    2490             : /************************************************************************/
    2491             : 
    2492             : /**
    2493             :  * \brief Read ESRI world file.
    2494             :  *
    2495             :  * This function reads an ESRI style world file, and formats a geotransform
    2496             :  * from its contents.
    2497             :  *
    2498             :  * The world file contains an affine transformation with the parameters
    2499             :  * in a different order than in a geotransform array.
    2500             :  *
    2501             :  * <ul>
    2502             :  * <li> geotransform[1] : width of pixel
    2503             :  * <li> geotransform[4] : rotational coefficient, zero for north up images.
    2504             :  * <li> geotransform[2] : rotational coefficient, zero for north up images.
    2505             :  * <li> geotransform[5] : height of pixel (but negative)
    2506             :  * <li> geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2] : x
    2507             :  * offset to center of top left pixel. <li> geotransform[3] + 0.5 *
    2508             :  * geotransform[4] + 0.5 * geotransform[5] : y offset to center of top left
    2509             :  * pixel.
    2510             :  * </ul>
    2511             :  *
    2512             :  * @param pszFilename the world file name.
    2513             :  * @param padfGeoTransform the six double array into which the
    2514             :  * geotransformation should be placed.
    2515             :  *
    2516             :  * @return TRUE on success or FALSE on failure.
    2517             :  */
    2518             : 
    2519          67 : int CPL_STDCALL GDALLoadWorldFile(const char *pszFilename,
    2520             :                                   double *padfGeoTransform)
    2521             : 
    2522             : {
    2523          67 :     VALIDATE_POINTER1(pszFilename, "GDALLoadWorldFile", FALSE);
    2524          67 :     VALIDATE_POINTER1(padfGeoTransform, "GDALLoadWorldFile", FALSE);
    2525             : 
    2526          67 :     char **papszLines = CSLLoad2(pszFilename, 100, 100, nullptr);
    2527             : 
    2528          67 :     if (!papszLines)
    2529           0 :         return FALSE;
    2530             : 
    2531          67 :     double world[6] = {0.0};
    2532             :     // reads the first 6 non-empty lines
    2533          67 :     int nLines = 0;
    2534          67 :     const int nLinesCount = CSLCount(papszLines);
    2535         469 :     for (int i = 0;
    2536         469 :          i < nLinesCount && nLines < static_cast<int>(CPL_ARRAYSIZE(world));
    2537             :          ++i)
    2538             :     {
    2539         402 :         CPLString line(papszLines[i]);
    2540         402 :         if (line.Trim().empty())
    2541           0 :             continue;
    2542             : 
    2543         402 :         world[nLines] = CPLAtofM(line);
    2544         402 :         ++nLines;
    2545             :     }
    2546             : 
    2547          67 :     if (nLines == 6 && (world[0] != 0.0 || world[2] != 0.0) &&
    2548          67 :         (world[3] != 0.0 || world[1] != 0.0))
    2549             :     {
    2550          67 :         padfGeoTransform[0] = world[4];
    2551          67 :         padfGeoTransform[1] = world[0];
    2552          67 :         padfGeoTransform[2] = world[2];
    2553          67 :         padfGeoTransform[3] = world[5];
    2554          67 :         padfGeoTransform[4] = world[1];
    2555          67 :         padfGeoTransform[5] = world[3];
    2556             : 
    2557             :         // correct for center of pixel vs. top left of pixel
    2558          67 :         padfGeoTransform[0] -= 0.5 * padfGeoTransform[1];
    2559          67 :         padfGeoTransform[0] -= 0.5 * padfGeoTransform[2];
    2560          67 :         padfGeoTransform[3] -= 0.5 * padfGeoTransform[4];
    2561          67 :         padfGeoTransform[3] -= 0.5 * padfGeoTransform[5];
    2562             : 
    2563          67 :         CSLDestroy(papszLines);
    2564             : 
    2565          67 :         return TRUE;
    2566             :     }
    2567             :     else
    2568             :     {
    2569           0 :         CPLDebug("GDAL",
    2570             :                  "GDALLoadWorldFile(%s) found file, but it was corrupt.",
    2571             :                  pszFilename);
    2572           0 :         CSLDestroy(papszLines);
    2573           0 :         return FALSE;
    2574             :     }
    2575             : }
    2576             : 
    2577             : /************************************************************************/
    2578             : /*                         GDALReadWorldFile()                          */
    2579             : /************************************************************************/
    2580             : 
    2581             : /**
    2582             :  * \brief Read ESRI world file.
    2583             :  *
    2584             :  * This function reads an ESRI style world file, and formats a geotransform
    2585             :  * from its contents.  It does the same as GDALLoadWorldFile() function, but
    2586             :  * it will form the filename for the worldfile from the filename of the raster
    2587             :  * file referred and the suggested extension.  If no extension is provided,
    2588             :  * the code will internally try the unix style and windows style world file
    2589             :  * extensions (eg. for .tif these would be .tfw and .tifw).
    2590             :  *
    2591             :  * The world file contains an affine transformation with the parameters
    2592             :  * in a different order than in a geotransform array.
    2593             :  *
    2594             :  * <ul>
    2595             :  * <li> geotransform[1] : width of pixel
    2596             :  * <li> geotransform[4] : rotational coefficient, zero for north up images.
    2597             :  * <li> geotransform[2] : rotational coefficient, zero for north up images.
    2598             :  * <li> geotransform[5] : height of pixel (but negative)
    2599             :  * <li> geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2] : x
    2600             :  * offset to center of top left pixel. <li> geotransform[3] + 0.5 *
    2601             :  * geotransform[4] + 0.5 * geotransform[5] : y offset to center of top left
    2602             :  * pixel.
    2603             :  * </ul>
    2604             :  *
    2605             :  * @param pszBaseFilename the target raster file.
    2606             :  * @param pszExtension the extension to use (i.e. "wld") or NULL to derive it
    2607             :  * from the pszBaseFilename
    2608             :  * @param padfGeoTransform the six double array into which the
    2609             :  * geotransformation should be placed.
    2610             :  *
    2611             :  * @return TRUE on success or FALSE on failure.
    2612             :  */
    2613             : 
    2614         821 : int CPL_STDCALL GDALReadWorldFile(const char *pszBaseFilename,
    2615             :                                   const char *pszExtension,
    2616             :                                   double *padfGeoTransform)
    2617             : 
    2618             : {
    2619         821 :     return GDALReadWorldFile2(pszBaseFilename, pszExtension, padfGeoTransform,
    2620         821 :                               nullptr, nullptr);
    2621             : }
    2622             : 
    2623       28889 : int GDALReadWorldFile2(const char *pszBaseFilename, const char *pszExtension,
    2624             :                        double *padfGeoTransform, CSLConstList papszSiblingFiles,
    2625             :                        char **ppszWorldFileNameOut)
    2626             : {
    2627       28889 :     VALIDATE_POINTER1(pszBaseFilename, "GDALReadWorldFile", FALSE);
    2628       28889 :     VALIDATE_POINTER1(padfGeoTransform, "GDALReadWorldFile", FALSE);
    2629             : 
    2630       28889 :     if (ppszWorldFileNameOut)
    2631       27065 :         *ppszWorldFileNameOut = nullptr;
    2632             : 
    2633       28889 :     if (!GDALCanFileAcceptSidecarFile(pszBaseFilename))
    2634         202 :         return FALSE;
    2635             : 
    2636             :     /* -------------------------------------------------------------------- */
    2637             :     /*      If we aren't given an extension, try both the unix and          */
    2638             :     /*      windows style extensions.                                       */
    2639             :     /* -------------------------------------------------------------------- */
    2640       28687 :     if (pszExtension == nullptr)
    2641             :     {
    2642       13862 :         const std::string oBaseExt = CPLGetExtensionSafe(pszBaseFilename);
    2643             : 
    2644        6931 :         if (oBaseExt.length() < 2)
    2645         149 :             return FALSE;
    2646             : 
    2647             :         // windows version - first + last + 'w'
    2648        6782 :         char szDerivedExtension[100] = {'\0'};
    2649        6782 :         szDerivedExtension[0] = oBaseExt[0];
    2650        6782 :         szDerivedExtension[1] = oBaseExt[oBaseExt.length() - 1];
    2651        6782 :         szDerivedExtension[2] = 'w';
    2652        6782 :         szDerivedExtension[3] = '\0';
    2653             : 
    2654        6782 :         if (GDALReadWorldFile2(pszBaseFilename, szDerivedExtension,
    2655             :                                padfGeoTransform, papszSiblingFiles,
    2656        6782 :                                ppszWorldFileNameOut))
    2657          52 :             return TRUE;
    2658             : 
    2659             :         // unix version - extension + 'w'
    2660        6730 :         if (oBaseExt.length() > sizeof(szDerivedExtension) - 2)
    2661           0 :             return FALSE;
    2662             : 
    2663        6730 :         snprintf(szDerivedExtension, sizeof(szDerivedExtension), "%sw",
    2664             :                  oBaseExt.c_str());
    2665        6730 :         return GDALReadWorldFile2(pszBaseFilename, szDerivedExtension,
    2666             :                                   padfGeoTransform, papszSiblingFiles,
    2667        6730 :                                   ppszWorldFileNameOut);
    2668             :     }
    2669             : 
    2670             :     /* -------------------------------------------------------------------- */
    2671             :     /*      Skip the leading period in the extension if there is one.       */
    2672             :     /* -------------------------------------------------------------------- */
    2673       21756 :     if (*pszExtension == '.')
    2674        1413 :         pszExtension++;
    2675             : 
    2676             :     /* -------------------------------------------------------------------- */
    2677             :     /*      Generate upper and lower case versions of the extension.        */
    2678             :     /* -------------------------------------------------------------------- */
    2679       21756 :     char szExtUpper[32] = {'\0'};
    2680       21756 :     char szExtLower[32] = {'\0'};
    2681       21756 :     CPLStrlcpy(szExtUpper, pszExtension, sizeof(szExtUpper));
    2682       21756 :     CPLStrlcpy(szExtLower, pszExtension, sizeof(szExtLower));
    2683             : 
    2684       94277 :     for (int i = 0; szExtUpper[i] != '\0'; i++)
    2685             :     {
    2686       72521 :         szExtUpper[i] = static_cast<char>(
    2687       72521 :             CPLToupper(static_cast<unsigned char>(szExtUpper[i])));
    2688       72521 :         szExtLower[i] = static_cast<char>(
    2689       72521 :             CPLTolower(static_cast<unsigned char>(szExtLower[i])));
    2690             :     }
    2691             : 
    2692       43512 :     std::string osTFW = CPLResetExtensionSafe(pszBaseFilename, szExtLower);
    2693             : 
    2694       42437 :     if (papszSiblingFiles &&
    2695             :         // cppcheck-suppress knownConditionTrueFalse
    2696       20681 :         GDALCanReliablyUseSiblingFileList(osTFW.c_str()))
    2697             :     {
    2698             :         const int iSibling =
    2699       20681 :             CSLFindString(papszSiblingFiles, CPLGetFilename(osTFW.c_str()));
    2700       20681 :         if (iSibling >= 0)
    2701             :         {
    2702          65 :             CPLString osTFWFilename = pszBaseFilename;
    2703         130 :             osTFWFilename.resize(strlen(pszBaseFilename) -
    2704          65 :                                  strlen(CPLGetFilename(pszBaseFilename)));
    2705          65 :             osTFWFilename += papszSiblingFiles[iSibling];
    2706          65 :             if (GDALLoadWorldFile(osTFWFilename, padfGeoTransform))
    2707             :             {
    2708          65 :                 if (ppszWorldFileNameOut)
    2709          62 :                     *ppszWorldFileNameOut = CPLStrdup(osTFWFilename);
    2710          65 :                 return TRUE;
    2711             :             }
    2712             :         }
    2713       20616 :         return FALSE;
    2714             :     }
    2715             : 
    2716             :     /* -------------------------------------------------------------------- */
    2717             :     /*      Try lower case, then upper case.                                */
    2718             :     /* -------------------------------------------------------------------- */
    2719             : 
    2720             :     VSIStatBufL sStatBuf;
    2721             :     bool bGotTFW =
    2722        1075 :         VSIStatExL(osTFW.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0;
    2723             : 
    2724        1075 :     if (!bGotTFW && VSIIsCaseSensitiveFS(osTFW.c_str()))
    2725             :     {
    2726        1073 :         osTFW = CPLResetExtensionSafe(pszBaseFilename, szExtUpper);
    2727        1073 :         bGotTFW =
    2728        1073 :             VSIStatExL(osTFW.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0;
    2729             :     }
    2730             : 
    2731        1075 :     if (!bGotTFW)
    2732        1073 :         return FALSE;
    2733             : 
    2734             :     /* -------------------------------------------------------------------- */
    2735             :     /*      We found the file, now load and parse it.                       */
    2736             :     /* -------------------------------------------------------------------- */
    2737           2 :     if (GDALLoadWorldFile(osTFW.c_str(), padfGeoTransform))
    2738             :     {
    2739           2 :         if (ppszWorldFileNameOut)
    2740           1 :             *ppszWorldFileNameOut = CPLStrdup(osTFW.c_str());
    2741           2 :         return TRUE;
    2742             :     }
    2743           0 :     return FALSE;
    2744             : }
    2745             : 
    2746             : /************************************************************************/
    2747             : /*                         GDALWriteWorldFile()                         */
    2748             : /*                                                                      */
    2749             : /*      Helper function for translator implementer wanting              */
    2750             : /*      support for ESRI world files.                                   */
    2751             : /************************************************************************/
    2752             : 
    2753             : /**
    2754             :  * \brief Write ESRI world file.
    2755             :  *
    2756             :  * This function writes an ESRI style world file from the passed geotransform.
    2757             :  *
    2758             :  * The world file contains an affine transformation with the parameters
    2759             :  * in a different order than in a geotransform array.
    2760             :  *
    2761             :  * <ul>
    2762             :  * <li> geotransform[1] : width of pixel
    2763             :  * <li> geotransform[4] : rotational coefficient, zero for north up images.
    2764             :  * <li> geotransform[2] : rotational coefficient, zero for north up images.
    2765             :  * <li> geotransform[5] : height of pixel (but negative)
    2766             :  * <li> geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2] : x
    2767             :  * offset to center of top left pixel. <li> geotransform[3] + 0.5 *
    2768             :  * geotransform[4] + 0.5 * geotransform[5] : y offset to center of top left
    2769             :  * pixel.
    2770             :  * </ul>
    2771             :  *
    2772             :  * @param pszBaseFilename the target raster file.
    2773             :  * @param pszExtension the extension to use (i.e. "wld"). Must not be NULL
    2774             :  * @param padfGeoTransform the six double array from which the
    2775             :  * geotransformation should be read.
    2776             :  *
    2777             :  * @return TRUE on success or FALSE on failure.
    2778             :  */
    2779             : 
    2780          13 : int CPL_STDCALL GDALWriteWorldFile(const char *pszBaseFilename,
    2781             :                                    const char *pszExtension,
    2782             :                                    double *padfGeoTransform)
    2783             : 
    2784             : {
    2785          13 :     VALIDATE_POINTER1(pszBaseFilename, "GDALWriteWorldFile", FALSE);
    2786          13 :     VALIDATE_POINTER1(pszExtension, "GDALWriteWorldFile", FALSE);
    2787          13 :     VALIDATE_POINTER1(padfGeoTransform, "GDALWriteWorldFile", FALSE);
    2788             : 
    2789             :     /* -------------------------------------------------------------------- */
    2790             :     /*      Prepare the text to write to the file.                          */
    2791             :     /* -------------------------------------------------------------------- */
    2792          26 :     CPLString osTFWText;
    2793             : 
    2794             :     osTFWText.Printf("%.10f\n%.10f\n%.10f\n%.10f\n%.10f\n%.10f\n",
    2795          13 :                      padfGeoTransform[1], padfGeoTransform[4],
    2796          13 :                      padfGeoTransform[2], padfGeoTransform[5],
    2797          13 :                      padfGeoTransform[0] + 0.5 * padfGeoTransform[1] +
    2798          13 :                          0.5 * padfGeoTransform[2],
    2799          13 :                      padfGeoTransform[3] + 0.5 * padfGeoTransform[4] +
    2800          13 :                          0.5 * padfGeoTransform[5]);
    2801             : 
    2802             :     /* -------------------------------------------------------------------- */
    2803             :     /*      Update extension, and write to disk.                            */
    2804             :     /* -------------------------------------------------------------------- */
    2805             :     const std::string osTFW =
    2806          26 :         CPLResetExtensionSafe(pszBaseFilename, pszExtension);
    2807          13 :     VSILFILE *const fpTFW = VSIFOpenL(osTFW.c_str(), "wt");
    2808          13 :     if (fpTFW == nullptr)
    2809           0 :         return FALSE;
    2810             : 
    2811             :     const int bRet =
    2812          13 :         VSIFWriteL(osTFWText.c_str(), osTFWText.size(), 1, fpTFW) == 1;
    2813          13 :     if (VSIFCloseL(fpTFW) != 0)
    2814           0 :         return FALSE;
    2815             : 
    2816          13 :     return bRet;
    2817             : }
    2818             : 
    2819             : /************************************************************************/
    2820             : /*                          GDALVersionInfo()                           */
    2821             : /************************************************************************/
    2822             : 
    2823             : /**
    2824             :  * \brief Get runtime version information.
    2825             :  *
    2826             :  * Available pszRequest values:
    2827             :  * <ul>
    2828             :  * <li> "VERSION_NUM": Returns GDAL_VERSION_NUM formatted as a string.  i.e.
    2829             :  * "30603000", e.g for GDAL 3.6.3.0</li>
    2830             :  * <li> "RELEASE_DATE": Returns GDAL_RELEASE_DATE formatted as a
    2831             :  * string. i.e. "20230312".</li>
    2832             :  * <li> "RELEASE_NAME": Returns the GDAL_RELEASE_NAME. ie. "3.6.3"</li>
    2833             :  * <li> "RELEASE_NICKNAME": (>= 3.11) Returns the GDAL_RELEASE_NICKNAME.
    2834             :  * (may be empty)</li>
    2835             :  * <li> "\--version": Returns one line version message suitable for
    2836             :  * use in response to \--version requests.  i.e. "GDAL 3.6.3, released
    2837             :  * 2023/03/12"</li>
    2838             :  * <li> "LICENSE": Returns the content of the LICENSE.TXT file from
    2839             :  * the GDAL_DATA directory.
    2840             :  * </li>
    2841             :  * <li> "BUILD_INFO": List of NAME=VALUE pairs separated by newlines
    2842             :  * with information on build time options.</li>
    2843             :  * </ul>
    2844             :  *
    2845             :  * @param pszRequest the type of version info desired, as listed above.
    2846             :  *
    2847             :  * @return an internal string containing the requested information.
    2848             :  */
    2849             : 
    2850        4854 : const char *CPL_STDCALL GDALVersionInfo(const char *pszRequest)
    2851             : 
    2852             : {
    2853             :     /* -------------------------------------------------------------------- */
    2854             :     /*      Try to capture as much build information as practical.          */
    2855             :     /* -------------------------------------------------------------------- */
    2856        4854 :     if (pszRequest != nullptr && EQUAL(pszRequest, "BUILD_INFO"))
    2857             :     {
    2858        1428 :         CPLString osBuildInfo;
    2859             : 
    2860             : #define STRINGIFY_HELPER(x) #x
    2861             : #define STRINGIFY(x) STRINGIFY_HELPER(x)
    2862             : 
    2863             : #ifdef ESRI_BUILD
    2864             :         osBuildInfo += "ESRI_BUILD=YES\n";
    2865             : #endif
    2866             : #ifdef PAM_ENABLED
    2867             :         osBuildInfo += "PAM_ENABLED=YES\n";
    2868             : #endif
    2869         714 :         osBuildInfo += "OGR_ENABLED=YES\n";  // Deprecated.  Always yes.
    2870             : #ifdef HAVE_CURL
    2871         714 :         osBuildInfo += "CURL_ENABLED=YES\n";
    2872         714 :         osBuildInfo += "CURL_VERSION=" LIBCURL_VERSION "\n";
    2873             : #endif
    2874             : #ifdef HAVE_GEOS
    2875         714 :         osBuildInfo += "GEOS_ENABLED=YES\n";
    2876             : #ifdef GEOS_CAPI_VERSION
    2877         714 :         osBuildInfo += "GEOS_VERSION=" GEOS_CAPI_VERSION "\n";
    2878             : #endif
    2879             : #endif
    2880             :         osBuildInfo +=
    2881             :             "PROJ_BUILD_VERSION=" STRINGIFY(PROJ_VERSION_MAJOR) "." STRINGIFY(
    2882         714 :                 PROJ_VERSION_MINOR) "." STRINGIFY(PROJ_VERSION_PATCH) "\n";
    2883         714 :         osBuildInfo += "PROJ_RUNTIME_VERSION=";
    2884         714 :         osBuildInfo += proj_info().version;
    2885         714 :         osBuildInfo += '\n';
    2886             : 
    2887             : #ifdef __VERSION__
    2888             : #ifdef __clang_version__
    2889             :         osBuildInfo += "COMPILER=clang " __clang_version__ "\n";
    2890             : #elif defined(__GNUC__)
    2891         714 :         osBuildInfo += "COMPILER=GCC " __VERSION__ "\n";
    2892             : #elif defined(__INTEL_COMPILER)
    2893             :         osBuildInfo += "COMPILER=" __VERSION__ "\n";
    2894             : #else
    2895             :         // STRINGIFY() as we're not sure if its a int or a string
    2896             :         osBuildInfo += "COMPILER=unknown compiler " STRINGIFY(__VERSION__) "\n";
    2897             : #endif
    2898             : #elif defined(_MSC_FULL_VER)
    2899             :         osBuildInfo += "COMPILER=MSVC " STRINGIFY(_MSC_FULL_VER) "\n";
    2900             : #elif defined(__INTEL_COMPILER)
    2901             :         osBuildInfo +=
    2902             :             "COMPILER=Intel compiler " STRINGIFY(__INTEL_COMPILER) "\n";
    2903             : #endif
    2904             : #ifdef CMAKE_UNITY_BUILD
    2905             :         osBuildInfo += "CMAKE_UNITY_BUILD=YES\n";
    2906             : #endif
    2907             : #ifdef EMBED_RESOURCE_FILES
    2908             :         osBuildInfo += "EMBED_RESOURCE_FILES=YES\n";
    2909             : #endif
    2910             : #ifdef USE_ONLY_EMBEDDED_RESOURCE_FILES
    2911             :         osBuildInfo += "USE_ONLY_EMBEDDED_RESOURCE_FILES=YES\n";
    2912             : #endif
    2913             : 
    2914             : #undef STRINGIFY_HELPER
    2915             : #undef STRINGIFY
    2916             : 
    2917         714 :         CPLFree(CPLGetTLS(CTLS_VERSIONINFO));
    2918         714 :         CPLSetTLS(CTLS_VERSIONINFO, CPLStrdup(osBuildInfo), TRUE);
    2919         714 :         return static_cast<char *>(CPLGetTLS(CTLS_VERSIONINFO));
    2920             :     }
    2921             : 
    2922             :     /* -------------------------------------------------------------------- */
    2923             :     /*      LICENSE is a special case. We try to find and read the          */
    2924             :     /*      LICENSE.TXT file from the GDAL_DATA directory and return it     */
    2925             :     /* -------------------------------------------------------------------- */
    2926        4140 :     if (pszRequest != nullptr && EQUAL(pszRequest, "LICENSE"))
    2927             :     {
    2928             : #if defined(EMBED_RESOURCE_FILES) && defined(USE_ONLY_EMBEDDED_RESOURCE_FILES)
    2929             :         return GDALGetEmbeddedLicense();
    2930             : #else
    2931             :         char *pszResultLicence =
    2932           4 :             reinterpret_cast<char *>(CPLGetTLS(CTLS_VERSIONINFO_LICENCE));
    2933           4 :         if (pszResultLicence != nullptr)
    2934             :         {
    2935           0 :             return pszResultLicence;
    2936             :         }
    2937             : 
    2938           4 :         VSILFILE *fp = nullptr;
    2939             : #ifndef USE_ONLY_EMBEDDED_RESOURCE_FILES
    2940             : #ifdef EMBED_RESOURCE_FILES
    2941             :         CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    2942             : #endif
    2943           4 :         const char *pszFilename = CPLFindFile("etc", "LICENSE.TXT");
    2944           4 :         if (pszFilename != nullptr)
    2945           4 :             fp = VSIFOpenL(pszFilename, "r");
    2946           4 :         if (fp != nullptr)
    2947             :         {
    2948           4 :             if (VSIFSeekL(fp, 0, SEEK_END) == 0)
    2949             :             {
    2950             :                 // TODO(schwehr): Handle if VSITellL returns a value too large
    2951             :                 // for size_t.
    2952           4 :                 const size_t nLength = static_cast<size_t>(VSIFTellL(fp) + 1);
    2953           4 :                 if (VSIFSeekL(fp, SEEK_SET, 0) == 0)
    2954             :                 {
    2955             :                     pszResultLicence =
    2956           4 :                         static_cast<char *>(VSICalloc(1, nLength));
    2957           4 :                     if (pszResultLicence)
    2958           4 :                         CPL_IGNORE_RET_VAL(
    2959           4 :                             VSIFReadL(pszResultLicence, 1, nLength - 1, fp));
    2960             :                 }
    2961             :             }
    2962             : 
    2963           4 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
    2964             :         }
    2965             : #endif
    2966             : 
    2967             : #ifdef EMBED_RESOURCE_FILES
    2968             :         if (!fp)
    2969             :         {
    2970             :             return GDALGetEmbeddedLicense();
    2971             :         }
    2972             : #endif
    2973             : 
    2974           4 :         if (!pszResultLicence)
    2975             :         {
    2976             :             pszResultLicence =
    2977           0 :                 CPLStrdup("GDAL/OGR is released under the MIT license.\n"
    2978             :                           "The LICENSE.TXT distributed with GDAL/OGR should\n"
    2979             :                           "contain additional details.\n");
    2980             :         }
    2981             : 
    2982           4 :         CPLSetTLS(CTLS_VERSIONINFO_LICENCE, pszResultLicence, TRUE);
    2983           4 :         return pszResultLicence;
    2984             : #endif
    2985             :     }
    2986             : 
    2987             :     /* -------------------------------------------------------------------- */
    2988             :     /*      All other strings are fairly small.                             */
    2989             :     /* -------------------------------------------------------------------- */
    2990        8272 :     CPLString osVersionInfo;
    2991             : 
    2992        4136 :     if (pszRequest == nullptr || EQUAL(pszRequest, "VERSION_NUM"))
    2993        2564 :         osVersionInfo.Printf("%d", GDAL_VERSION_NUM);
    2994        1572 :     else if (EQUAL(pszRequest, "RELEASE_DATE"))
    2995           1 :         osVersionInfo.Printf("%d", GDAL_RELEASE_DATE);
    2996        1571 :     else if (EQUAL(pszRequest, "RELEASE_NAME"))
    2997        1217 :         osVersionInfo.Printf(GDAL_RELEASE_NAME);
    2998         354 :     else if (EQUAL(pszRequest, "RELEASE_NICKNAME"))
    2999           0 :         osVersionInfo.Printf("%s", GDAL_RELEASE_NICKNAME);
    3000             :     else  // --version
    3001             :     {
    3002         354 :         osVersionInfo = "GDAL " GDAL_RELEASE_NAME;
    3003         354 :         if (GDAL_RELEASE_NICKNAME[0])
    3004             :         {
    3005           0 :             osVersionInfo += " \"" GDAL_RELEASE_NICKNAME "\"";
    3006             :         }
    3007         708 :         osVersionInfo += CPLString().Printf(
    3008             :             ", released %d/%02d/%02d", GDAL_RELEASE_DATE / 10000,
    3009         354 :             (GDAL_RELEASE_DATE % 10000) / 100, GDAL_RELEASE_DATE % 100);
    3010             : #if defined(__GNUC__) && !defined(__OPTIMIZE__)
    3011             :         // Cf https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
    3012             :         // also true for CLang
    3013         354 :         osVersionInfo += " (debug build)";
    3014             : #elif defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL == 2
    3015             :         // https://docs.microsoft.com/en-us/cpp/standard-library/iterator-debug-level?view=msvc-170
    3016             :         // In release mode, the compiler generates an error if you specify
    3017             :         // _ITERATOR_DEBUG_LEVEL as 2.
    3018             :         osVersionInfo += " (debug build)";
    3019             : #endif
    3020             :     }
    3021             : 
    3022        4136 :     CPLFree(CPLGetTLS(CTLS_VERSIONINFO));  // clear old value.
    3023        4136 :     CPLSetTLS(CTLS_VERSIONINFO, CPLStrdup(osVersionInfo), TRUE);
    3024        4136 :     return static_cast<char *>(CPLGetTLS(CTLS_VERSIONINFO));
    3025             : }
    3026             : 
    3027             : /************************************************************************/
    3028             : /*                         GDALCheckVersion()                           */
    3029             : /************************************************************************/
    3030             : 
    3031             : /** Return TRUE if GDAL library version at runtime matches
    3032             :    nVersionMajor.nVersionMinor.
    3033             : 
    3034             :     The purpose of this method is to ensure that calling code will run
    3035             :     with the GDAL version it is compiled for. It is primarily intended
    3036             :     for external plugins.
    3037             : 
    3038             :     @param nVersionMajor Major version to be tested against
    3039             :     @param nVersionMinor Minor version to be tested against
    3040             :     @param pszCallingComponentName If not NULL, in case of version mismatch, the
    3041             :    method will issue a failure mentioning the name of the calling component.
    3042             : 
    3043             :     @return TRUE if GDAL library version at runtime matches
    3044             :     nVersionMajor.nVersionMinor, FALSE otherwise.
    3045             :   */
    3046       27497 : int CPL_STDCALL GDALCheckVersion(int nVersionMajor, int nVersionMinor,
    3047             :                                  const char *pszCallingComponentName)
    3048             : {
    3049       27497 :     if (nVersionMajor == GDAL_VERSION_MAJOR &&
    3050             :         nVersionMinor == GDAL_VERSION_MINOR)
    3051       27497 :         return TRUE;
    3052             : 
    3053           0 :     if (pszCallingComponentName)
    3054             :     {
    3055           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3056             :                  "%s was compiled against GDAL %d.%d, but "
    3057             :                  "the current library version is %d.%d",
    3058             :                  pszCallingComponentName, nVersionMajor, nVersionMinor,
    3059             :                  GDAL_VERSION_MAJOR, GDAL_VERSION_MINOR);
    3060             :     }
    3061           0 :     return FALSE;
    3062             : }
    3063             : 
    3064             : /************************************************************************/
    3065             : /*                            GDALDecToDMS()                            */
    3066             : /************************************************************************/
    3067             : 
    3068             : /** Translate a decimal degrees value to a DMS string with hemisphere.
    3069             :  */
    3070         550 : const char *CPL_STDCALL GDALDecToDMS(double dfAngle, const char *pszAxis,
    3071             :                                      int nPrecision)
    3072             : 
    3073             : {
    3074         550 :     return CPLDecToDMS(dfAngle, pszAxis, nPrecision);
    3075             : }
    3076             : 
    3077             : /************************************************************************/
    3078             : /*                         GDALPackedDMSToDec()                         */
    3079             : /************************************************************************/
    3080             : 
    3081             : /**
    3082             :  * \brief Convert a packed DMS value (DDDMMMSSS.SS) into decimal degrees.
    3083             :  *
    3084             :  * See CPLPackedDMSToDec().
    3085             :  */
    3086             : 
    3087           4 : double CPL_STDCALL GDALPackedDMSToDec(double dfPacked)
    3088             : 
    3089             : {
    3090           4 :     return CPLPackedDMSToDec(dfPacked);
    3091             : }
    3092             : 
    3093             : /************************************************************************/
    3094             : /*                         GDALDecToPackedDMS()                         */
    3095             : /************************************************************************/
    3096             : 
    3097             : /**
    3098             :  * \brief Convert decimal degrees into packed DMS value (DDDMMMSSS.SS).
    3099             :  *
    3100             :  * See CPLDecToPackedDMS().
    3101             :  */
    3102             : 
    3103           4 : double CPL_STDCALL GDALDecToPackedDMS(double dfDec)
    3104             : 
    3105             : {
    3106           4 :     return CPLDecToPackedDMS(dfDec);
    3107             : }
    3108             : 
    3109             : /************************************************************************/
    3110             : /*                       GDALGCPsToGeoTransform()                       */
    3111             : /************************************************************************/
    3112             : 
    3113             : /**
    3114             :  * \brief Generate Geotransform from GCPs.
    3115             :  *
    3116             :  * Given a set of GCPs perform first order fit as a geotransform.
    3117             :  *
    3118             :  * Due to imprecision in the calculations the fit algorithm will often
    3119             :  * return non-zero rotational coefficients even if given perfectly non-rotated
    3120             :  * inputs.  A special case has been implemented for corner corner coordinates
    3121             :  * given in TL, TR, BR, BL order.  So when using this to get a geotransform
    3122             :  * from 4 corner coordinates, pass them in this order.
    3123             :  *
    3124             :  * Starting with GDAL 2.2.2, if bApproxOK = FALSE, the
    3125             :  * GDAL_GCPS_TO_GEOTRANSFORM_APPROX_OK configuration option will be read. If
    3126             :  * set to YES, then bApproxOK will be overridden with TRUE.
    3127             :  * Starting with GDAL 2.2.2, when exact fit is asked, the
    3128             :  * GDAL_GCPS_TO_GEOTRANSFORM_APPROX_THRESHOLD configuration option can be set to
    3129             :  * give the maximum error threshold in pixel. The default is 0.25.
    3130             :  *
    3131             :  * @param nGCPCount the number of GCPs being passed in.
    3132             :  * @param pasGCPs the list of GCP structures.
    3133             :  * @param padfGeoTransform the six double array in which the affine
    3134             :  * geotransformation will be returned.
    3135             :  * @param bApproxOK If FALSE the function will fail if the geotransform is not
    3136             :  * essentially an exact fit (within 0.25 pixel) for all GCPs.
    3137             :  *
    3138             :  * @return TRUE on success or FALSE if there aren't enough points to prepare a
    3139             :  * geotransform, the pointers are ill-determined or if bApproxOK is FALSE
    3140             :  * and the fit is poor.
    3141             :  */
    3142             : 
    3143             : // TODO(schwehr): Add consts to args.
    3144         605 : int CPL_STDCALL GDALGCPsToGeoTransform(int nGCPCount, const GDAL_GCP *pasGCPs,
    3145             :                                        double *padfGeoTransform, int bApproxOK)
    3146             : 
    3147             : {
    3148         605 :     double dfPixelThreshold = 0.25;
    3149         605 :     if (!bApproxOK)
    3150             :     {
    3151         591 :         bApproxOK = CPLTestBool(
    3152             :             CPLGetConfigOption("GDAL_GCPS_TO_GEOTRANSFORM_APPROX_OK", "NO"));
    3153         591 :         if (!bApproxOK)
    3154             :         {
    3155             :             // coverity[tainted_data]
    3156         591 :             dfPixelThreshold = CPLAtof(CPLGetConfigOption(
    3157             :                 "GDAL_GCPS_TO_GEOTRANSFORM_APPROX_THRESHOLD", "0.25"));
    3158             :         }
    3159             :     }
    3160             : 
    3161             :     /* -------------------------------------------------------------------- */
    3162             :     /*      Recognise a few special cases.                                  */
    3163             :     /* -------------------------------------------------------------------- */
    3164         605 :     if (nGCPCount < 2)
    3165          16 :         return FALSE;
    3166             : 
    3167         589 :     if (nGCPCount == 2)
    3168             :     {
    3169           2 :         if (pasGCPs[1].dfGCPPixel == pasGCPs[0].dfGCPPixel ||
    3170           2 :             pasGCPs[1].dfGCPLine == pasGCPs[0].dfGCPLine)
    3171           0 :             return FALSE;
    3172             : 
    3173           2 :         padfGeoTransform[1] = (pasGCPs[1].dfGCPX - pasGCPs[0].dfGCPX) /
    3174           2 :                               (pasGCPs[1].dfGCPPixel - pasGCPs[0].dfGCPPixel);
    3175           2 :         padfGeoTransform[2] = 0.0;
    3176             : 
    3177           2 :         padfGeoTransform[4] = 0.0;
    3178           2 :         padfGeoTransform[5] = (pasGCPs[1].dfGCPY - pasGCPs[0].dfGCPY) /
    3179           2 :                               (pasGCPs[1].dfGCPLine - pasGCPs[0].dfGCPLine);
    3180             : 
    3181           2 :         padfGeoTransform[0] = pasGCPs[0].dfGCPX -
    3182           2 :                               pasGCPs[0].dfGCPPixel * padfGeoTransform[1] -
    3183           2 :                               pasGCPs[0].dfGCPLine * padfGeoTransform[2];
    3184             : 
    3185           2 :         padfGeoTransform[3] = pasGCPs[0].dfGCPY -
    3186           2 :                               pasGCPs[0].dfGCPPixel * padfGeoTransform[4] -
    3187           2 :                               pasGCPs[0].dfGCPLine * padfGeoTransform[5];
    3188             : 
    3189           2 :         return TRUE;
    3190             :     }
    3191             : 
    3192             :     /* -------------------------------------------------------------------- */
    3193             :     /*      Special case of 4 corner coordinates of a non-rotated           */
    3194             :     /*      image.  The points must be in TL-TR-BR-BL order for now.        */
    3195             :     /*      This case helps avoid some imprecision in the general           */
    3196             :     /*      calculations.                                                   */
    3197             :     /* -------------------------------------------------------------------- */
    3198         587 :     if (nGCPCount == 4 && pasGCPs[0].dfGCPLine == pasGCPs[1].dfGCPLine &&
    3199         291 :         pasGCPs[2].dfGCPLine == pasGCPs[3].dfGCPLine &&
    3200         291 :         pasGCPs[0].dfGCPPixel == pasGCPs[3].dfGCPPixel &&
    3201         290 :         pasGCPs[1].dfGCPPixel == pasGCPs[2].dfGCPPixel &&
    3202         290 :         pasGCPs[0].dfGCPLine != pasGCPs[2].dfGCPLine &&
    3203         287 :         pasGCPs[0].dfGCPPixel != pasGCPs[1].dfGCPPixel &&
    3204         287 :         pasGCPs[0].dfGCPY == pasGCPs[1].dfGCPY &&
    3205         261 :         pasGCPs[2].dfGCPY == pasGCPs[3].dfGCPY &&
    3206         259 :         pasGCPs[0].dfGCPX == pasGCPs[3].dfGCPX &&
    3207         259 :         pasGCPs[1].dfGCPX == pasGCPs[2].dfGCPX &&
    3208         259 :         pasGCPs[0].dfGCPY != pasGCPs[2].dfGCPY &&
    3209         184 :         pasGCPs[0].dfGCPX != pasGCPs[1].dfGCPX)
    3210             :     {
    3211         184 :         padfGeoTransform[1] = (pasGCPs[1].dfGCPX - pasGCPs[0].dfGCPX) /
    3212         184 :                               (pasGCPs[1].dfGCPPixel - pasGCPs[0].dfGCPPixel);
    3213         184 :         padfGeoTransform[2] = 0.0;
    3214         184 :         padfGeoTransform[4] = 0.0;
    3215         184 :         padfGeoTransform[5] = (pasGCPs[2].dfGCPY - pasGCPs[1].dfGCPY) /
    3216         184 :                               (pasGCPs[2].dfGCPLine - pasGCPs[1].dfGCPLine);
    3217             : 
    3218         184 :         padfGeoTransform[0] =
    3219         184 :             pasGCPs[0].dfGCPX - pasGCPs[0].dfGCPPixel * padfGeoTransform[1];
    3220         184 :         padfGeoTransform[3] =
    3221         184 :             pasGCPs[0].dfGCPY - pasGCPs[0].dfGCPLine * padfGeoTransform[5];
    3222         184 :         return TRUE;
    3223             :     }
    3224             : 
    3225             :     /* -------------------------------------------------------------------- */
    3226             :     /*      Compute source and destination ranges so we can normalize       */
    3227             :     /*      the values to make the least squares computation more stable.   */
    3228             :     /* -------------------------------------------------------------------- */
    3229         403 :     double min_pixel = pasGCPs[0].dfGCPPixel;
    3230         403 :     double max_pixel = pasGCPs[0].dfGCPPixel;
    3231         403 :     double min_line = pasGCPs[0].dfGCPLine;
    3232         403 :     double max_line = pasGCPs[0].dfGCPLine;
    3233         403 :     double min_geox = pasGCPs[0].dfGCPX;
    3234         403 :     double max_geox = pasGCPs[0].dfGCPX;
    3235         403 :     double min_geoy = pasGCPs[0].dfGCPY;
    3236         403 :     double max_geoy = pasGCPs[0].dfGCPY;
    3237             : 
    3238        1710 :     for (int i = 1; i < nGCPCount; ++i)
    3239             :     {
    3240        1307 :         min_pixel = std::min(min_pixel, pasGCPs[i].dfGCPPixel);
    3241        1307 :         max_pixel = std::max(max_pixel, pasGCPs[i].dfGCPPixel);
    3242        1307 :         min_line = std::min(min_line, pasGCPs[i].dfGCPLine);
    3243        1307 :         max_line = std::max(max_line, pasGCPs[i].dfGCPLine);
    3244        1307 :         min_geox = std::min(min_geox, pasGCPs[i].dfGCPX);
    3245        1307 :         max_geox = std::max(max_geox, pasGCPs[i].dfGCPX);
    3246        1307 :         min_geoy = std::min(min_geoy, pasGCPs[i].dfGCPY);
    3247        1307 :         max_geoy = std::max(max_geoy, pasGCPs[i].dfGCPY);
    3248             :     }
    3249             : 
    3250         403 :     double EPS = 1.0e-12;
    3251             : 
    3252         803 :     if (std::abs(max_pixel - min_pixel) < EPS ||
    3253         800 :         std::abs(max_line - min_line) < EPS ||
    3254        1203 :         std::abs(max_geox - min_geox) < EPS ||
    3255         325 :         std::abs(max_geoy - min_geoy) < EPS)
    3256             :     {
    3257          78 :         return FALSE;  // degenerate in at least one dimension.
    3258             :     }
    3259             : 
    3260             :     double pl_normalize[6], geo_normalize[6];
    3261             : 
    3262         325 :     pl_normalize[0] = -min_pixel / (max_pixel - min_pixel);
    3263         325 :     pl_normalize[1] = 1.0 / (max_pixel - min_pixel);
    3264         325 :     pl_normalize[2] = 0.0;
    3265         325 :     pl_normalize[3] = -min_line / (max_line - min_line);
    3266         325 :     pl_normalize[4] = 0.0;
    3267         325 :     pl_normalize[5] = 1.0 / (max_line - min_line);
    3268             : 
    3269         325 :     geo_normalize[0] = -min_geox / (max_geox - min_geox);
    3270         325 :     geo_normalize[1] = 1.0 / (max_geox - min_geox);
    3271         325 :     geo_normalize[2] = 0.0;
    3272         325 :     geo_normalize[3] = -min_geoy / (max_geoy - min_geoy);
    3273         325 :     geo_normalize[4] = 0.0;
    3274         325 :     geo_normalize[5] = 1.0 / (max_geoy - min_geoy);
    3275             : 
    3276             :     /* -------------------------------------------------------------------- */
    3277             :     /* In the general case, do a least squares error approximation by       */
    3278             :     /* solving the equation Sum[(A - B*x + C*y - Lon)^2] = minimum          */
    3279             :     /* -------------------------------------------------------------------- */
    3280             : 
    3281         325 :     double sum_x = 0.0;
    3282         325 :     double sum_y = 0.0;
    3283         325 :     double sum_xy = 0.0;
    3284         325 :     double sum_xx = 0.0;
    3285         325 :     double sum_yy = 0.0;
    3286         325 :     double sum_Lon = 0.0;
    3287         325 :     double sum_Lonx = 0.0;
    3288         325 :     double sum_Lony = 0.0;
    3289         325 :     double sum_Lat = 0.0;
    3290         325 :     double sum_Latx = 0.0;
    3291         325 :     double sum_Laty = 0.0;
    3292             : 
    3293        1723 :     for (int i = 0; i < nGCPCount; ++i)
    3294             :     {
    3295             :         double pixel, line, geox, geoy;
    3296             : 
    3297        1398 :         GDALApplyGeoTransform(pl_normalize, pasGCPs[i].dfGCPPixel,
    3298        1398 :                               pasGCPs[i].dfGCPLine, &pixel, &line);
    3299        1398 :         GDALApplyGeoTransform(geo_normalize, pasGCPs[i].dfGCPX,
    3300        1398 :                               pasGCPs[i].dfGCPY, &geox, &geoy);
    3301             : 
    3302        1398 :         sum_x += pixel;
    3303        1398 :         sum_y += line;
    3304        1398 :         sum_xy += pixel * line;
    3305        1398 :         sum_xx += pixel * pixel;
    3306        1398 :         sum_yy += line * line;
    3307        1398 :         sum_Lon += geox;
    3308        1398 :         sum_Lonx += geox * pixel;
    3309        1398 :         sum_Lony += geox * line;
    3310        1398 :         sum_Lat += geoy;
    3311        1398 :         sum_Latx += geoy * pixel;
    3312        1398 :         sum_Laty += geoy * line;
    3313             :     }
    3314             : 
    3315         325 :     const double divisor = nGCPCount * (sum_xx * sum_yy - sum_xy * sum_xy) +
    3316         325 :                            2 * sum_x * sum_y * sum_xy - sum_y * sum_y * sum_xx -
    3317         325 :                            sum_x * sum_x * sum_yy;
    3318             : 
    3319             :     /* -------------------------------------------------------------------- */
    3320             :     /*      If the divisor is zero, there is no valid solution.             */
    3321             :     /* -------------------------------------------------------------------- */
    3322         325 :     if (divisor == 0.0)
    3323           0 :         return FALSE;
    3324             : 
    3325             :     /* -------------------------------------------------------------------- */
    3326             :     /*      Compute top/left origin.                                        */
    3327             :     /* -------------------------------------------------------------------- */
    3328         325 :     double gt_normalized[6] = {0.0};
    3329         325 :     gt_normalized[0] = (sum_Lon * (sum_xx * sum_yy - sum_xy * sum_xy) +
    3330         325 :                         sum_Lonx * (sum_y * sum_xy - sum_x * sum_yy) +
    3331         325 :                         sum_Lony * (sum_x * sum_xy - sum_y * sum_xx)) /
    3332             :                        divisor;
    3333             : 
    3334         325 :     gt_normalized[3] = (sum_Lat * (sum_xx * sum_yy - sum_xy * sum_xy) +
    3335         325 :                         sum_Latx * (sum_y * sum_xy - sum_x * sum_yy) +
    3336         325 :                         sum_Laty * (sum_x * sum_xy - sum_y * sum_xx)) /
    3337             :                        divisor;
    3338             : 
    3339             :     /* -------------------------------------------------------------------- */
    3340             :     /*      Compute X related coefficients.                                 */
    3341             :     /* -------------------------------------------------------------------- */
    3342         325 :     gt_normalized[1] = (sum_Lon * (sum_y * sum_xy - sum_x * sum_yy) +
    3343         325 :                         sum_Lonx * (nGCPCount * sum_yy - sum_y * sum_y) +
    3344         325 :                         sum_Lony * (sum_x * sum_y - sum_xy * nGCPCount)) /
    3345             :                        divisor;
    3346             : 
    3347         325 :     gt_normalized[2] = (sum_Lon * (sum_x * sum_xy - sum_y * sum_xx) +
    3348         325 :                         sum_Lonx * (sum_x * sum_y - nGCPCount * sum_xy) +
    3349         325 :                         sum_Lony * (nGCPCount * sum_xx - sum_x * sum_x)) /
    3350             :                        divisor;
    3351             : 
    3352             :     /* -------------------------------------------------------------------- */
    3353             :     /*      Compute Y related coefficients.                                 */
    3354             :     /* -------------------------------------------------------------------- */
    3355         325 :     gt_normalized[4] = (sum_Lat * (sum_y * sum_xy - sum_x * sum_yy) +
    3356         325 :                         sum_Latx * (nGCPCount * sum_yy - sum_y * sum_y) +
    3357         325 :                         sum_Laty * (sum_x * sum_y - sum_xy * nGCPCount)) /
    3358             :                        divisor;
    3359             : 
    3360         325 :     gt_normalized[5] = (sum_Lat * (sum_x * sum_xy - sum_y * sum_xx) +
    3361         325 :                         sum_Latx * (sum_x * sum_y - nGCPCount * sum_xy) +
    3362         325 :                         sum_Laty * (nGCPCount * sum_xx - sum_x * sum_x)) /
    3363             :                        divisor;
    3364             : 
    3365             :     /* -------------------------------------------------------------------- */
    3366             :     /*      Compose the resulting transformation with the normalization     */
    3367             :     /*      geotransformations.                                             */
    3368             :     /* -------------------------------------------------------------------- */
    3369         325 :     double gt1p2[6] = {0.0};
    3370         325 :     double inv_geo_normalize[6] = {0.0};
    3371         325 :     if (!GDALInvGeoTransform(geo_normalize, inv_geo_normalize))
    3372           0 :         return FALSE;
    3373             : 
    3374         325 :     GDALComposeGeoTransforms(pl_normalize, gt_normalized, gt1p2);
    3375         325 :     GDALComposeGeoTransforms(gt1p2, inv_geo_normalize, padfGeoTransform);
    3376             : 
    3377             :     // "Hour-glass" like shape of GCPs. Cf https://github.com/OSGeo/gdal/issues/11618
    3378         649 :     if (std::abs(padfGeoTransform[1]) <= 1e-15 ||
    3379         324 :         std::abs(padfGeoTransform[5]) <= 1e-15)
    3380             :     {
    3381           2 :         return FALSE;
    3382             :     }
    3383             : 
    3384             :     /* -------------------------------------------------------------------- */
    3385             :     /*      Now check if any of the input points fit this poorly.           */
    3386             :     /* -------------------------------------------------------------------- */
    3387         323 :     if (!bApproxOK)
    3388             :     {
    3389             :         // FIXME? Not sure if it is the more accurate way of computing
    3390             :         // pixel size
    3391             :         double dfPixelSize =
    3392             :             0.5 *
    3393         314 :             (std::abs(padfGeoTransform[1]) + std::abs(padfGeoTransform[2]) +
    3394         314 :              std::abs(padfGeoTransform[4]) + std::abs(padfGeoTransform[5]));
    3395         314 :         if (dfPixelSize == 0.0)
    3396             :         {
    3397           0 :             CPLDebug("GDAL", "dfPixelSize = 0");
    3398           0 :             return FALSE;
    3399             :         }
    3400             : 
    3401        1643 :         for (int i = 0; i < nGCPCount; i++)
    3402             :         {
    3403        1335 :             const double dfErrorX =
    3404        1335 :                 (pasGCPs[i].dfGCPPixel * padfGeoTransform[1] +
    3405        1335 :                  pasGCPs[i].dfGCPLine * padfGeoTransform[2] +
    3406        1335 :                  padfGeoTransform[0]) -
    3407        1335 :                 pasGCPs[i].dfGCPX;
    3408        1335 :             const double dfErrorY =
    3409        1335 :                 (pasGCPs[i].dfGCPPixel * padfGeoTransform[4] +
    3410        1335 :                  pasGCPs[i].dfGCPLine * padfGeoTransform[5] +
    3411        1335 :                  padfGeoTransform[3]) -
    3412        1335 :                 pasGCPs[i].dfGCPY;
    3413             : 
    3414        2667 :             if (std::abs(dfErrorX) > dfPixelThreshold * dfPixelSize ||
    3415        1332 :                 std::abs(dfErrorY) > dfPixelThreshold * dfPixelSize)
    3416             :             {
    3417           6 :                 CPLDebug("GDAL",
    3418             :                          "dfErrorX/dfPixelSize = %.2f, "
    3419             :                          "dfErrorY/dfPixelSize = %.2f",
    3420           6 :                          std::abs(dfErrorX) / dfPixelSize,
    3421           6 :                          std::abs(dfErrorY) / dfPixelSize);
    3422           6 :                 return FALSE;
    3423             :             }
    3424             :         }
    3425             :     }
    3426             : 
    3427         317 :     return TRUE;
    3428             : }
    3429             : 
    3430             : /************************************************************************/
    3431             : /*                      GDALComposeGeoTransforms()                      */
    3432             : /************************************************************************/
    3433             : 
    3434             : /**
    3435             :  * \brief Compose two geotransforms.
    3436             :  *
    3437             :  * The resulting geotransform is the equivalent to padfGT1 and then padfGT2
    3438             :  * being applied to a point.
    3439             :  *
    3440             :  * @param padfGT1 the first geotransform, six values.
    3441             :  * @param padfGT2 the second geotransform, six values.
    3442             :  * @param padfGTOut the output geotransform, six values, may safely be the same
    3443             :  * array as padfGT1 or padfGT2.
    3444             :  */
    3445             : 
    3446         650 : void GDALComposeGeoTransforms(const double *padfGT1, const double *padfGT2,
    3447             :                               double *padfGTOut)
    3448             : 
    3449             : {
    3450         650 :     double gtwrk[6] = {0.0};
    3451             :     // We need to think of the geotransform in a more normal form to do
    3452             :     // the matrix multiple:
    3453             :     //
    3454             :     //  __                     __
    3455             :     //  | gt[1]   gt[2]   gt[0] |
    3456             :     //  | gt[4]   gt[5]   gt[3] |
    3457             :     //  |  0.0     0.0     1.0  |
    3458             :     //  --                     --
    3459             :     //
    3460             :     // Then we can use normal matrix multiplication to produce the
    3461             :     // composed transformation.  I don't actually reform the matrix
    3462             :     // explicitly which is why the following may seem kind of spagettish.
    3463             : 
    3464         650 :     gtwrk[1] = padfGT2[1] * padfGT1[1] + padfGT2[2] * padfGT1[4];
    3465         650 :     gtwrk[2] = padfGT2[1] * padfGT1[2] + padfGT2[2] * padfGT1[5];
    3466         650 :     gtwrk[0] =
    3467         650 :         padfGT2[1] * padfGT1[0] + padfGT2[2] * padfGT1[3] + padfGT2[0] * 1.0;
    3468             : 
    3469         650 :     gtwrk[4] = padfGT2[4] * padfGT1[1] + padfGT2[5] * padfGT1[4];
    3470         650 :     gtwrk[5] = padfGT2[4] * padfGT1[2] + padfGT2[5] * padfGT1[5];
    3471         650 :     gtwrk[3] =
    3472         650 :         padfGT2[4] * padfGT1[0] + padfGT2[5] * padfGT1[3] + padfGT2[3] * 1.0;
    3473         650 :     memcpy(padfGTOut, gtwrk, sizeof(gtwrk));
    3474         650 : }
    3475             : 
    3476             : /************************************************************************/
    3477             : /*                      StripIrrelevantOptions()                        */
    3478             : /************************************************************************/
    3479             : 
    3480          10 : static void StripIrrelevantOptions(CPLXMLNode *psCOL, int nOptions)
    3481             : {
    3482          10 :     if (psCOL == nullptr)
    3483           0 :         return;
    3484          10 :     if (nOptions == 0)
    3485           5 :         nOptions = GDAL_OF_RASTER;
    3486          10 :     if ((nOptions & GDAL_OF_RASTER) != 0 && (nOptions & GDAL_OF_VECTOR) != 0)
    3487           2 :         return;
    3488             : 
    3489           8 :     CPLXMLNode *psPrev = nullptr;
    3490         175 :     for (CPLXMLNode *psIter = psCOL->psChild; psIter;)
    3491             :     {
    3492         167 :         if (psIter->eType == CXT_Element)
    3493             :         {
    3494         167 :             CPLXMLNode *psScope = CPLGetXMLNode(psIter, "scope");
    3495         167 :             bool bStrip = false;
    3496         167 :             if (nOptions == GDAL_OF_RASTER && psScope && psScope->psChild &&
    3497          35 :                 psScope->psChild->pszValue &&
    3498          35 :                 EQUAL(psScope->psChild->pszValue, "vector"))
    3499             :             {
    3500           1 :                 bStrip = true;
    3501             :             }
    3502         166 :             else if (nOptions == GDAL_OF_VECTOR && psScope &&
    3503          35 :                      psScope->psChild && psScope->psChild->pszValue &&
    3504          35 :                      EQUAL(psScope->psChild->pszValue, "raster"))
    3505             :             {
    3506          33 :                 bStrip = true;
    3507             :             }
    3508         167 :             if (psScope)
    3509             :             {
    3510          70 :                 CPLRemoveXMLChild(psIter, psScope);
    3511          70 :                 CPLDestroyXMLNode(psScope);
    3512             :             }
    3513             : 
    3514         167 :             CPLXMLNode *psNext = psIter->psNext;
    3515         167 :             if (bStrip)
    3516             :             {
    3517          34 :                 if (psPrev)
    3518          13 :                     psPrev->psNext = psNext;
    3519          21 :                 else if (psCOL->psChild == psIter)
    3520          21 :                     psCOL->psChild = psNext;
    3521          34 :                 psIter->psNext = nullptr;
    3522          34 :                 CPLDestroyXMLNode(psIter);
    3523          34 :                 psIter = psNext;
    3524             :             }
    3525             :             else
    3526             :             {
    3527         133 :                 psPrev = psIter;
    3528         133 :                 psIter = psNext;
    3529             :             }
    3530             :         }
    3531             :         else
    3532             :         {
    3533           0 :             psIter = psIter->psNext;
    3534             :         }
    3535             :     }
    3536             : }
    3537             : 
    3538             : /************************************************************************/
    3539             : /*                         GDALPrintDriverList()                        */
    3540             : /************************************************************************/
    3541             : 
    3542             : /** Print on stdout the driver list */
    3543           9 : std::string GDALPrintDriverList(int nOptions, bool bJSON)
    3544             : {
    3545           9 :     if (nOptions == 0)
    3546           2 :         nOptions = GDAL_OF_RASTER;
    3547             : 
    3548           9 :     if (bJSON)
    3549             :     {
    3550           6 :         auto poDM = GetGDALDriverManager();
    3551          12 :         CPLJSONArray oArray;
    3552           6 :         const int nDriverCount = poDM->GetDriverCount();
    3553        1330 :         for (int iDr = 0; iDr < nDriverCount; ++iDr)
    3554             :         {
    3555        1324 :             auto poDriver = poDM->GetDriver(iDr);
    3556        1324 :             CSLConstList papszMD = poDriver->GetMetadata();
    3557             : 
    3558        1765 :             if (nOptions == GDAL_OF_RASTER &&
    3559         441 :                 !CPLFetchBool(papszMD, GDAL_DCAP_RASTER, false))
    3560         612 :                 continue;
    3561        1627 :             if (nOptions == GDAL_OF_VECTOR &&
    3562         441 :                 !CPLFetchBool(papszMD, GDAL_DCAP_VECTOR, false))
    3563         265 :                 continue;
    3564         921 :             if (nOptions == GDAL_OF_GNM &&
    3565           0 :                 !CPLFetchBool(papszMD, GDAL_DCAP_GNM, false))
    3566           0 :                 continue;
    3567        1142 :             if (nOptions == GDAL_OF_MULTIDIM_RASTER &&
    3568         221 :                 !CPLFetchBool(papszMD, GDAL_DCAP_MULTIDIM_RASTER, false))
    3569         209 :                 continue;
    3570             : 
    3571        1424 :             CPLJSONObject oJDriver;
    3572         712 :             oJDriver.Set("short_name", poDriver->GetDescription());
    3573         712 :             if (const char *pszLongName =
    3574         712 :                     CSLFetchNameValue(papszMD, GDAL_DMD_LONGNAME))
    3575         712 :                 oJDriver.Set("long_name", pszLongName);
    3576        1424 :             CPLJSONArray oJScopes;
    3577         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_RASTER, false))
    3578         509 :                 oJScopes.Add("raster");
    3579         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_MULTIDIM_RASTER, false))
    3580          56 :                 oJScopes.Add("multidimensional_raster");
    3581         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_VECTOR, false))
    3582         310 :                 oJScopes.Add("vector");
    3583         712 :             oJDriver.Add("scopes", oJScopes);
    3584        1424 :             CPLJSONArray oJCaps;
    3585         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_OPEN, false))
    3586         706 :                 oJCaps.Add("open");
    3587         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_CREATE, false))
    3588         290 :                 oJCaps.Add("create");
    3589         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_CREATECOPY, false))
    3590         190 :                 oJCaps.Add("create_copy");
    3591         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_UPDATE, false))
    3592         105 :                 oJCaps.Add("update");
    3593         712 :             if (CPLFetchBool(papszMD, GDAL_DCAP_VIRTUALIO, false))
    3594         583 :                 oJCaps.Add("virtual_io");
    3595         712 :             oJDriver.Add("capabilities", oJCaps);
    3596             : 
    3597         712 :             if (const char *pszExtensions = CSLFetchNameValueDef(
    3598             :                     papszMD, GDAL_DMD_EXTENSIONS,
    3599             :                     CSLFetchNameValue(papszMD, GDAL_DMD_EXTENSION)))
    3600             :             {
    3601             :                 const CPLStringList aosExt(
    3602         948 :                     CSLTokenizeString2(pszExtensions, " ", 0));
    3603         474 :                 CPLJSONArray oJExts;
    3604        1117 :                 for (int i = 0; i < aosExt.size(); ++i)
    3605             :                 {
    3606         643 :                     oJExts.Add(aosExt[i]);
    3607             :                 }
    3608         474 :                 oJDriver.Add("file_extensions", oJExts);
    3609             :             }
    3610             : 
    3611         712 :             oArray.Add(oJDriver);
    3612             :         }
    3613             : 
    3614           6 :         return oArray.Format(CPLJSONObject::PrettyFormat::Pretty);
    3615             :     }
    3616             : 
    3617           6 :     std::string ret;
    3618             :     ret = "Supported Formats: (ro:read-only, rw:read-write, "
    3619             :           "+:write from scratch, u:update, "
    3620           3 :           "v:virtual-I/O s:subdatasets)\n";
    3621         663 :     for (int iDr = 0; iDr < GDALGetDriverCount(); iDr++)
    3622             :     {
    3623         660 :         GDALDriverH hDriver = GDALGetDriver(iDr);
    3624             : 
    3625         660 :         const char *pszRFlag = "", *pszWFlag, *pszVirtualIO, *pszSubdatasets;
    3626         660 :         CSLConstList papszMD = GDALGetMetadata(hDriver, nullptr);
    3627             : 
    3628         880 :         if (nOptions == GDAL_OF_RASTER &&
    3629         220 :             !CPLFetchBool(papszMD, GDAL_DCAP_RASTER, false))
    3630         333 :             continue;
    3631        1031 :         if (nOptions == GDAL_OF_VECTOR &&
    3632         440 :             !CPLFetchBool(papszMD, GDAL_DCAP_VECTOR, false))
    3633         264 :             continue;
    3634         327 :         if (nOptions == GDAL_OF_GNM &&
    3635           0 :             !CPLFetchBool(papszMD, GDAL_DCAP_GNM, false))
    3636           0 :             continue;
    3637         327 :         if (nOptions == GDAL_OF_MULTIDIM_RASTER &&
    3638           0 :             !CPLFetchBool(papszMD, GDAL_DCAP_MULTIDIM_RASTER, false))
    3639           0 :             continue;
    3640             : 
    3641         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_OPEN, false))
    3642         324 :             pszRFlag = "r";
    3643             : 
    3644         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_CREATE, false))
    3645         153 :             pszWFlag = "w+";
    3646         174 :         else if (CPLFetchBool(papszMD, GDAL_DCAP_CREATECOPY, false))
    3647          29 :             pszWFlag = "w";
    3648             :         else
    3649         145 :             pszWFlag = "o";
    3650             : 
    3651         327 :         const char *pszUpdate = "";
    3652         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_UPDATE, false))
    3653          55 :             pszUpdate = "u";
    3654             : 
    3655         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_VIRTUALIO, false))
    3656         258 :             pszVirtualIO = "v";
    3657             :         else
    3658          69 :             pszVirtualIO = "";
    3659             : 
    3660         327 :         if (CPLFetchBool(papszMD, GDAL_DMD_SUBDATASETS, false))
    3661          44 :             pszSubdatasets = "s";
    3662             :         else
    3663         283 :             pszSubdatasets = "";
    3664             : 
    3665         654 :         CPLString osKind;
    3666         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_RASTER, false))
    3667         193 :             osKind = "raster";
    3668         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_MULTIDIM_RASTER, false))
    3669             :         {
    3670          20 :             if (!osKind.empty())
    3671          20 :                 osKind += ',';
    3672          20 :             osKind += "multidimensional raster";
    3673             :         }
    3674         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_VECTOR, false))
    3675             :         {
    3676         197 :             if (!osKind.empty())
    3677          63 :                 osKind += ',';
    3678         197 :             osKind += "vector";
    3679             :         }
    3680         327 :         if (CPLFetchBool(papszMD, GDAL_DCAP_GNM, false))
    3681             :         {
    3682           0 :             if (!osKind.empty())
    3683           0 :                 osKind += ',';
    3684           0 :             osKind += "geography network";
    3685             :         }
    3686         327 :         if (osKind.empty())
    3687           0 :             osKind = "unknown kind";
    3688             : 
    3689         654 :         std::string osExtensions;
    3690         327 :         if (const char *pszExtensions = CSLFetchNameValueDef(
    3691             :                 papszMD, GDAL_DMD_EXTENSIONS,
    3692             :                 CSLFetchNameValue(papszMD, GDAL_DMD_EXTENSION)))
    3693             :         {
    3694             :             const CPLStringList aosExt(
    3695         440 :                 CSLTokenizeString2(pszExtensions, " ", 0));
    3696         530 :             for (int i = 0; i < aosExt.size(); ++i)
    3697             :             {
    3698         310 :                 if (i == 0)
    3699         219 :                     osExtensions = " (*.";
    3700             :                 else
    3701          91 :                     osExtensions += ", *.";
    3702         310 :                 osExtensions += aosExt[i];
    3703             :             }
    3704         220 :             if (!osExtensions.empty())
    3705         219 :                 osExtensions += ')';
    3706             :         }
    3707             : 
    3708             :         ret += CPLSPrintf("  %s -%s- (%s%s%s%s%s): %s%s\n", /*ok*/
    3709             :                           GDALGetDriverShortName(hDriver), osKind.c_str(),
    3710             :                           pszRFlag, pszWFlag, pszUpdate, pszVirtualIO,
    3711             :                           pszSubdatasets, GDALGetDriverLongName(hDriver),
    3712         327 :                           osExtensions.c_str());
    3713             :     }
    3714             : 
    3715           3 :     return ret;
    3716             : }
    3717             : 
    3718             : /************************************************************************/
    3719             : /*                    GDALGeneralCmdLineProcessor()                     */
    3720             : /************************************************************************/
    3721             : 
    3722             : /**
    3723             :  * \brief General utility option processing.
    3724             :  *
    3725             :  * This function is intended to provide a variety of generic commandline
    3726             :  * options for all GDAL commandline utilities.  It takes care of the following
    3727             :  * commandline options:
    3728             :  *
    3729             :  *  \--version: report version of GDAL in use.
    3730             :  *  \--build: report build info about GDAL in use.
    3731             :  *  \--license: report GDAL license info.
    3732             :  *  \--formats: report all format drivers configured. Can be used with -json since 3.10
    3733             :  *  \--format [format]: report details of one format driver.
    3734             :  *  \--optfile filename: expand an option file into the argument list.
    3735             :  *  \--config key value: set system configuration option.
    3736             :  *  \--config key=value: set system configuration option (since GDAL 3.9)
    3737             :  *  \--debug [on/off/value]: set debug level.
    3738             :  *  \--mempreload dir: preload directory contents into /vsimem
    3739             :  *  \--pause: Pause for user input (allows time to attach debugger)
    3740             :  *  \--locale [locale]: Install a locale using setlocale() (debugging)
    3741             :  *  \--help-general: report detailed help on general options.
    3742             :  *
    3743             :  * The argument array is replaced "in place" and should be freed with
    3744             :  * CSLDestroy() when no longer needed.  The typical usage looks something
    3745             :  * like the following.  Note that the formats should be registered so that
    3746             :  * the \--formats and \--format options will work properly.
    3747             :  *
    3748             :  *  int main( int argc, char ** argv )
    3749             :  *  {
    3750             :  *    GDALAllRegister();
    3751             :  *
    3752             :  *    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    3753             :  *    if( argc < 1 )
    3754             :  *        exit( -argc );
    3755             :  *
    3756             :  * @param nArgc number of values in the argument list.
    3757             :  * @param ppapszArgv pointer to the argument list array (will be updated in
    3758             :  * place).
    3759             :  * @param nOptions a or-able combination of GDAL_OF_RASTER and GDAL_OF_VECTOR
    3760             :  *                 to determine which drivers should be displayed by \--formats.
    3761             :  *                 If set to 0, GDAL_OF_RASTER is assumed.
    3762             :  *
    3763             :  * @return updated nArgc argument count.  Return of 0 requests terminate
    3764             :  * without error, return of -1 requests exit with error code.
    3765             :  */
    3766             : 
    3767        1314 : int CPL_STDCALL GDALGeneralCmdLineProcessor(int nArgc, char ***ppapszArgv,
    3768             :                                             int nOptions)
    3769             : 
    3770             : {
    3771        2628 :     CPLStringList aosReturn;
    3772             :     int iArg;
    3773        1314 :     char **papszArgv = *ppapszArgv;
    3774             : 
    3775             :     /* -------------------------------------------------------------------- */
    3776             :     /*      Preserve the program name.                                      */
    3777             :     /* -------------------------------------------------------------------- */
    3778        1314 :     aosReturn.AddString(papszArgv[0]);
    3779             : 
    3780             :     /* ==================================================================== */
    3781             :     /*      Loop over all arguments.                                        */
    3782             :     /* ==================================================================== */
    3783             : 
    3784             :     // Start with --debug, so that "my_command --config UNKNOWN_CONFIG_OPTION --debug on"
    3785             :     // detects and warns about a unknown config option.
    3786        8118 :     for (iArg = 1; iArg < nArgc; iArg++)
    3787             :     {
    3788        6806 :         if (EQUAL(papszArgv[iArg], "--config") && iArg + 2 < nArgc &&
    3789          39 :             EQUAL(papszArgv[iArg + 1], "CPL_DEBUG"))
    3790             :         {
    3791           0 :             if (iArg + 1 >= nArgc)
    3792             :             {
    3793           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3794             :                          "--config option given without a key=value argument.");
    3795           0 :                 return -1;
    3796             :             }
    3797             : 
    3798           0 :             const char *pszArg = papszArgv[iArg + 1];
    3799           0 :             if (strchr(pszArg, '=') != nullptr)
    3800             :             {
    3801           0 :                 char *pszKey = nullptr;
    3802           0 :                 const char *pszValue = CPLParseNameValue(pszArg, &pszKey);
    3803           0 :                 if (pszKey && !EQUAL(pszKey, "CPL_DEBUG") && pszValue)
    3804             :                 {
    3805           0 :                     CPLSetConfigOption(pszKey, pszValue);
    3806             :                 }
    3807           0 :                 CPLFree(pszKey);
    3808           0 :                 ++iArg;
    3809             :             }
    3810             :             else
    3811             :             {
    3812             :                 // cppcheck-suppress knownConditionTrueFalse
    3813           0 :                 if (iArg + 2 >= nArgc)
    3814             :                 {
    3815           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3816             :                              "--config option given without a key and value "
    3817             :                              "argument.");
    3818           0 :                     return -1;
    3819             :                 }
    3820             : 
    3821           0 :                 if (!EQUAL(papszArgv[iArg + 1], "CPL_DEBUG"))
    3822           0 :                     CPLSetConfigOption(papszArgv[iArg + 1],
    3823           0 :                                        papszArgv[iArg + 2]);
    3824             : 
    3825           0 :                 iArg += 2;
    3826           0 :             }
    3827             :         }
    3828        6806 :         else if (EQUAL(papszArgv[iArg], "--debug"))
    3829             :         {
    3830          13 :             if (iArg + 1 >= nArgc)
    3831             :             {
    3832           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3833             :                          "--debug option given without debug level.");
    3834           2 :                 return -1;
    3835             :             }
    3836             : 
    3837          11 :             CPLSetConfigOption("CPL_DEBUG", papszArgv[iArg + 1]);
    3838          11 :             iArg += 1;
    3839             :         }
    3840             :     }
    3841             : 
    3842        7925 :     for (iArg = 1; iArg < nArgc; iArg++)
    3843             :     {
    3844             :         /* --------------------------------------------------------------------
    3845             :          */
    3846             :         /*      --version */
    3847             :         /* --------------------------------------------------------------------
    3848             :          */
    3849        6703 :         if (EQUAL(papszArgv[iArg], "--version"))
    3850             :         {
    3851          64 :             printf("%s\n", GDALVersionInfo("--version")); /*ok*/
    3852          64 :             return 0;
    3853             :         }
    3854             : 
    3855             :         /* --------------------------------------------------------------------
    3856             :          */
    3857             :         /*      --build */
    3858             :         /* --------------------------------------------------------------------
    3859             :          */
    3860        6639 :         else if (EQUAL(papszArgv[iArg], "--build"))
    3861             :         {
    3862           1 :             printf("%s", GDALVersionInfo("BUILD_INFO")); /*ok*/
    3863           1 :             return 0;
    3864             :         }
    3865             : 
    3866             :         /* --------------------------------------------------------------------
    3867             :          */
    3868             :         /*      --license */
    3869             :         /* --------------------------------------------------------------------
    3870             :          */
    3871        6638 :         else if (EQUAL(papszArgv[iArg], "--license"))
    3872             :         {
    3873           1 :             printf("%s\n", GDALVersionInfo("LICENSE")); /*ok*/
    3874           1 :             return 0;
    3875             :         }
    3876             : 
    3877             :         /* --------------------------------------------------------------------
    3878             :          */
    3879             :         /*      --config */
    3880             :         /* --------------------------------------------------------------------
    3881             :          */
    3882        6637 :         else if (EQUAL(papszArgv[iArg], "--config"))
    3883             :         {
    3884          45 :             if (iArg + 1 >= nArgc)
    3885             :             {
    3886           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3887             :                          "--config option given without a key=value argument.");
    3888           2 :                 return -1;
    3889             :             }
    3890             : 
    3891          43 :             const char *pszArg = papszArgv[iArg + 1];
    3892          43 :             if (strchr(pszArg, '=') != nullptr)
    3893             :             {
    3894           3 :                 char *pszKey = nullptr;
    3895           3 :                 const char *pszValue = CPLParseNameValue(pszArg, &pszKey);
    3896           3 :                 if (pszKey && !EQUAL(pszKey, "CPL_DEBUG") && pszValue)
    3897             :                 {
    3898           3 :                     CPLSetConfigOption(pszKey, pszValue);
    3899             :                 }
    3900           3 :                 CPLFree(pszKey);
    3901           3 :                 ++iArg;
    3902             :             }
    3903             :             else
    3904             :             {
    3905          40 :                 if (iArg + 2 >= nArgc)
    3906             :                 {
    3907           2 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3908             :                              "--config option given without a key and value "
    3909             :                              "argument.");
    3910           2 :                     return -1;
    3911             :                 }
    3912             : 
    3913          38 :                 if (!EQUAL(papszArgv[iArg + 1], "CPL_DEBUG"))
    3914          38 :                     CPLSetConfigOption(papszArgv[iArg + 1],
    3915          38 :                                        papszArgv[iArg + 2]);
    3916             : 
    3917          38 :                 iArg += 2;
    3918             :             }
    3919             :         }
    3920             : 
    3921             :         /* --------------------------------------------------------------------
    3922             :          */
    3923             :         /*      --mempreload */
    3924             :         /* --------------------------------------------------------------------
    3925             :          */
    3926        6592 :         else if (EQUAL(papszArgv[iArg], "--mempreload"))
    3927             :         {
    3928           4 :             if (iArg + 1 >= nArgc)
    3929             :             {
    3930           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3931             :                          "--mempreload option given without directory path.");
    3932           2 :                 return -1;
    3933             :             }
    3934             : 
    3935           2 :             char **papszFiles = VSIReadDir(papszArgv[iArg + 1]);
    3936           2 :             if (CSLCount(papszFiles) == 0)
    3937             :             {
    3938           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3939             :                          "--mempreload given invalid or empty directory.");
    3940           0 :                 return -1;
    3941             :             }
    3942             : 
    3943         495 :             for (int i = 0; papszFiles[i] != nullptr; i++)
    3944             :             {
    3945         493 :                 if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], ".."))
    3946          72 :                     continue;
    3947             : 
    3948         489 :                 std::string osOldPath;
    3949         489 :                 CPLString osNewPath;
    3950         489 :                 osOldPath = CPLFormFilenameSafe(papszArgv[iArg + 1],
    3951         489 :                                                 papszFiles[i], nullptr);
    3952         489 :                 osNewPath.Printf("/vsimem/%s", papszFiles[i]);
    3953             : 
    3954             :                 VSIStatBufL sStatBuf;
    3955         978 :                 if (VSIStatL(osOldPath.c_str(), &sStatBuf) != 0 ||
    3956         489 :                     VSI_ISDIR(sStatBuf.st_mode))
    3957             :                 {
    3958          68 :                     CPLDebug("VSI", "Skipping preload of %s.",
    3959             :                              osOldPath.c_str());
    3960          68 :                     continue;
    3961             :                 }
    3962             : 
    3963         421 :                 CPLDebug("VSI", "Preloading %s to %s.", osOldPath.c_str(),
    3964             :                          osNewPath.c_str());
    3965             : 
    3966         421 :                 if (CPLCopyFile(osNewPath, osOldPath.c_str()) != 0)
    3967             :                 {
    3968           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3969             :                              "Failed to copy %s to /vsimem", osOldPath.c_str());
    3970           0 :                     return -1;
    3971             :                 }
    3972             :             }
    3973             : 
    3974           2 :             CSLDestroy(papszFiles);
    3975           2 :             iArg += 1;
    3976             :         }
    3977             : 
    3978             :         /* --------------------------------------------------------------------
    3979             :          */
    3980             :         /*      --debug */
    3981             :         /* --------------------------------------------------------------------
    3982             :          */
    3983        6588 :         else if (EQUAL(papszArgv[iArg], "--debug"))
    3984             :         {
    3985          11 :             if (iArg + 1 >= nArgc)
    3986             :             {
    3987           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3988             :                          "--debug option given without debug level.");
    3989           0 :                 return -1;
    3990             :             }
    3991             : 
    3992          11 :             iArg += 1;
    3993             :         }
    3994             : 
    3995             :         /* --------------------------------------------------------------------
    3996             :          */
    3997             :         /*      --optfile */
    3998             :         /* --------------------------------------------------------------------
    3999             :          */
    4000        6577 :         else if (EQUAL(papszArgv[iArg], "--optfile"))
    4001             :         {
    4002          11 :             if (iArg + 1 >= nArgc)
    4003             :             {
    4004           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4005             :                          "--optfile option given without filename.");
    4006           5 :                 return -1;
    4007             :             }
    4008             : 
    4009           9 :             VSILFILE *fpOptFile = VSIFOpenL(papszArgv[iArg + 1], "rb");
    4010             : 
    4011           9 :             if (fpOptFile == nullptr)
    4012             :             {
    4013           4 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4014             :                          "Unable to open optfile '%s'.\n%s",
    4015           2 :                          papszArgv[iArg + 1], VSIStrerror(errno));
    4016           2 :                 return -1;
    4017             :             }
    4018             : 
    4019             :             const char *pszLine;
    4020           7 :             CPLStringList aosArgvOptfile;
    4021             :             // dummy value as first argument to please
    4022             :             // GDALGeneralCmdLineProcessor()
    4023           7 :             aosArgvOptfile.AddString("");
    4024           7 :             bool bHasOptfile = false;
    4025          23 :             while ((pszLine = CPLReadLineL(fpOptFile)) != nullptr)
    4026             :             {
    4027          16 :                 if (pszLine[0] == '#' || strlen(pszLine) == 0)
    4028           3 :                     continue;
    4029             : 
    4030          13 :                 char **papszTokens = CSLTokenizeString(pszLine);
    4031          13 :                 for (int i = 0;
    4032          45 :                      papszTokens != nullptr && papszTokens[i] != nullptr; i++)
    4033             :                 {
    4034          32 :                     if (EQUAL(papszTokens[i], "--optfile"))
    4035             :                     {
    4036             :                         // To avoid potential recursion
    4037           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
    4038             :                                  "--optfile not supported in a option file");
    4039           0 :                         bHasOptfile = true;
    4040             :                     }
    4041          32 :                     aosArgvOptfile.AddStringDirectly(papszTokens[i]);
    4042          32 :                     papszTokens[i] = nullptr;
    4043             :                 }
    4044          13 :                 CSLDestroy(papszTokens);
    4045             :             }
    4046             : 
    4047           7 :             VSIFCloseL(fpOptFile);
    4048             : 
    4049           7 :             char **papszArgvOptfile = aosArgvOptfile.StealList();
    4050           7 :             if (!bHasOptfile)
    4051             :             {
    4052           7 :                 char **papszArgvOptfileBefore = papszArgvOptfile;
    4053           7 :                 if (GDALGeneralCmdLineProcessor(CSLCount(papszArgvOptfile),
    4054             :                                                 &papszArgvOptfile,
    4055           7 :                                                 nOptions) < 0)
    4056             :                 {
    4057           1 :                     CSLDestroy(papszArgvOptfile);
    4058           1 :                     return -1;
    4059             :                 }
    4060           6 :                 CSLDestroy(papszArgvOptfileBefore);
    4061             :             }
    4062             : 
    4063           6 :             char **papszIter = papszArgvOptfile + 1;
    4064          36 :             while (*papszIter)
    4065             :             {
    4066          30 :                 aosReturn.AddString(*papszIter);
    4067          30 :                 ++papszIter;
    4068             :             }
    4069           6 :             CSLDestroy(papszArgvOptfile);
    4070             : 
    4071           6 :             iArg += 1;
    4072             :         }
    4073             : 
    4074             :         /* --------------------------------------------------------------------
    4075             :          */
    4076             :         /*      --formats */
    4077             :         /* --------------------------------------------------------------------
    4078             :          */
    4079        6566 :         else if (EQUAL(papszArgv[iArg], "--formats"))
    4080             :         {
    4081           5 :             bool bJSON = false;
    4082          10 :             for (int i = 1; i < nArgc; i++)
    4083             :             {
    4084           7 :                 if (strcmp(papszArgv[i], "-json") == 0 ||
    4085           5 :                     strcmp(papszArgv[i], "--json") == 0)
    4086             :                 {
    4087           2 :                     bJSON = true;
    4088           2 :                     break;
    4089             :                 }
    4090             :             }
    4091             : 
    4092           5 :             printf("%s", GDALPrintDriverList(nOptions, bJSON).c_str()); /*ok*/
    4093             : 
    4094           5 :             return 0;
    4095             :         }
    4096             : 
    4097             :         /* --------------------------------------------------------------------
    4098             :          */
    4099             :         /*      --format */
    4100             :         /* --------------------------------------------------------------------
    4101             :          */
    4102        6561 :         else if (EQUAL(papszArgv[iArg], "--format"))
    4103             :         {
    4104             :             GDALDriverH hDriver;
    4105             :             char **papszMD;
    4106             : 
    4107           6 :             if (iArg + 1 >= nArgc)
    4108             :             {
    4109           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4110             :                          "--format option given without a format code.");
    4111           1 :                 return -1;
    4112             :             }
    4113             : 
    4114           5 :             hDriver = GDALGetDriverByName(papszArgv[iArg + 1]);
    4115           5 :             if (hDriver == nullptr)
    4116             :             {
    4117           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4118             :                          "--format option given with format '%s', but that "
    4119             :                          "format not\nrecognised.  Use the --formats option "
    4120             :                          "to get a list of available formats,\n"
    4121             :                          "and use the short code (i.e. GTiff or HFA) as the "
    4122             :                          "format identifier.\n",
    4123           1 :                          papszArgv[iArg + 1]);
    4124           1 :                 return -1;
    4125             :             }
    4126             : 
    4127           4 :             printf("Format Details:\n"); /*ok*/
    4128           4 :             printf(/*ok*/ "  Short Name: %s\n",
    4129             :                    GDALGetDriverShortName(hDriver));
    4130           4 :             printf(/*ok*/ "  Long Name: %s\n", GDALGetDriverLongName(hDriver));
    4131             : 
    4132           4 :             papszMD = GDALGetMetadata(hDriver, nullptr);
    4133           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_RASTER, false))
    4134           4 :                 printf("  Supports: Raster\n"); /*ok*/
    4135           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_MULTIDIM_RASTER, false))
    4136           1 :                 printf("  Supports: Multidimensional raster\n"); /*ok*/
    4137           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_VECTOR, false))
    4138           3 :                 printf("  Supports: Vector\n"); /*ok*/
    4139           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_GNM, false))
    4140           0 :                 printf("  Supports: Geography Network\n"); /*ok*/
    4141             : 
    4142             :             const char *pszExt =
    4143           4 :                 CSLFetchNameValue(papszMD, GDAL_DMD_EXTENSIONS);
    4144           4 :             if (pszExt != nullptr)
    4145           3 :                 printf("  Extension%s: %s\n", /*ok*/
    4146           3 :                        (strchr(pszExt, ' ') ? "s" : ""), pszExt);
    4147             : 
    4148           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_MIMETYPE))
    4149           1 :                 printf("  Mime Type: %s\n", /*ok*/
    4150             :                        CSLFetchNameValue(papszMD, GDAL_DMD_MIMETYPE));
    4151           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_HELPTOPIC))
    4152           3 :                 printf("  Help Topic: %s\n", /*ok*/
    4153             :                        CSLFetchNameValue(papszMD, GDAL_DMD_HELPTOPIC));
    4154             : 
    4155           4 :             if (CPLFetchBool(papszMD, GDAL_DMD_SUBDATASETS, false))
    4156           3 :                 printf("  Supports: Raster subdatasets\n"); /*ok*/
    4157           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_OPEN, false))
    4158           4 :                 printf("  Supports: Open() - Open existing dataset.\n"); /*ok*/
    4159           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_CREATE, false))
    4160           4 :                 printf(/*ok*/
    4161             :                        "  Supports: Create() - Create writable dataset.\n");
    4162           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_CREATE_MULTIDIMENSIONAL, false))
    4163           1 :                 printf(/*ok*/ "  Supports: CreateMultiDimensional() - Create "
    4164             :                               "multidimensional dataset.\n");
    4165           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_CREATECOPY, false))
    4166           3 :                 printf(/*ok*/ "  Supports: CreateCopy() - Create dataset by "
    4167             :                               "copying "
    4168             :                               "another.\n");
    4169           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_UPDATE, false))
    4170           3 :                 printf("  Supports: Update\n"); /*ok*/
    4171           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_VIRTUALIO, false))
    4172           3 :                 printf("  Supports: Virtual IO - eg. /vsimem/\n"); /*ok*/
    4173           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_CREATIONDATATYPES))
    4174           4 :                 printf("  Creation Datatypes: %s\n", /*ok*/
    4175             :                        CSLFetchNameValue(papszMD, GDAL_DMD_CREATIONDATATYPES));
    4176           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_CREATIONFIELDDATATYPES))
    4177           3 :                 printf("  Creation Field Datatypes: %s\n", /*ok*/
    4178             :                        CSLFetchNameValue(papszMD,
    4179             :                                          GDAL_DMD_CREATIONFIELDDATATYPES));
    4180           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_CREATIONFIELDDATASUBTYPES))
    4181           2 :                 printf("  Creation Field Data Sub-types: %s\n", /*ok*/
    4182             :                        CSLFetchNameValue(papszMD,
    4183             :                                          GDAL_DMD_CREATIONFIELDDATASUBTYPES));
    4184           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_NOTNULL_FIELDS, false))
    4185           2 :                 printf(/*ok*/ "  Supports: Creating fields with NOT NULL "
    4186             :                               "constraint.\n");
    4187           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_UNIQUE_FIELDS, false))
    4188           2 :                 printf(/*ok*/
    4189             :                        "  Supports: Creating fields with UNIQUE constraint.\n");
    4190           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_DEFAULT_FIELDS, false))
    4191           2 :                 printf(/*ok*/
    4192             :                        "  Supports: Creating fields with DEFAULT values.\n");
    4193           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_NOTNULL_GEOMFIELDS, false))
    4194           2 :                 /*ok*/ printf(
    4195             :                     "  Supports: Creating geometry fields with NOT NULL "
    4196             :                     "constraint.\n");
    4197           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION,
    4198             :                              false))
    4199           2 :                 /*ok*/ printf("  Supports: Writing geometries with given "
    4200             :                               "coordinate precision\n");
    4201           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_FEATURE_STYLES_READ, false))
    4202           0 :                 printf("  Supports: Reading feature styles.\n"); /*ok*/
    4203           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_FEATURE_STYLES_WRITE, false))
    4204           0 :                 printf("  Supports: Writing feature styles.\n"); /*ok*/
    4205           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_COORDINATE_EPOCH, false))
    4206           2 :                 printf("  Supports: Coordinate epoch.\n"); /*ok*/
    4207           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_MULTIPLE_VECTOR_LAYERS, false))
    4208           3 :                 printf("  Supports: Multiple vector layers.\n"); /*ok*/
    4209           4 :             if (CPLFetchBool(papszMD, GDAL_DCAP_FIELD_DOMAINS, false))
    4210           3 :                 printf("  Supports: Reading field domains.\n"); /*ok*/
    4211           4 :             if (CSLFetchNameValue(papszMD,
    4212           4 :                                   GDAL_DMD_CREATION_FIELD_DOMAIN_TYPES))
    4213           3 :                 printf("  Creation field domain types: %s\n", /*ok*/
    4214             :                        CSLFetchNameValue(papszMD,
    4215             :                                          GDAL_DMD_CREATION_FIELD_DOMAIN_TYPES));
    4216           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_SUPPORTED_SQL_DIALECTS))
    4217           3 :                 printf("  Supported SQL dialects: %s\n", /*ok*/
    4218             :                        CSLFetchNameValue(papszMD,
    4219             :                                          GDAL_DMD_SUPPORTED_SQL_DIALECTS));
    4220           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_UPDATE_ITEMS))
    4221           3 :                 printf("  Supported items for update: %s\n", /*ok*/
    4222             :                        CSLFetchNameValue(papszMD, GDAL_DMD_UPDATE_ITEMS));
    4223             : 
    4224          32 :             for (const char *key :
    4225             :                  {GDAL_DMD_CREATIONOPTIONLIST,
    4226             :                   GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST,
    4227             :                   GDAL_DMD_MULTIDIM_GROUP_CREATIONOPTIONLIST,
    4228             :                   GDAL_DMD_MULTIDIM_DIMENSION_CREATIONOPTIONLIST,
    4229             :                   GDAL_DMD_MULTIDIM_ARRAY_CREATIONOPTIONLIST,
    4230             :                   GDAL_DMD_MULTIDIM_ARRAY_OPENOPTIONLIST,
    4231             :                   GDAL_DMD_MULTIDIM_ATTRIBUTE_CREATIONOPTIONLIST,
    4232          36 :                   GDAL_DS_LAYER_CREATIONOPTIONLIST})
    4233             :             {
    4234          32 :                 if (CSLFetchNameValue(papszMD, key))
    4235             :                 {
    4236             :                     CPLXMLNode *psCOL =
    4237           7 :                         CPLParseXMLString(CSLFetchNameValue(papszMD, key));
    4238           7 :                     StripIrrelevantOptions(psCOL, nOptions);
    4239           7 :                     char *pszFormattedXML = CPLSerializeXMLTree(psCOL);
    4240             : 
    4241           7 :                     CPLDestroyXMLNode(psCOL);
    4242             : 
    4243           7 :                     printf("\n%s\n", pszFormattedXML); /*ok*/
    4244           7 :                     CPLFree(pszFormattedXML);
    4245             :                 }
    4246             :             }
    4247             : 
    4248           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_CONNECTION_PREFIX))
    4249           0 :                 printf("  Connection prefix: %s\n", /*ok*/
    4250             :                        CSLFetchNameValue(papszMD, GDAL_DMD_CONNECTION_PREFIX));
    4251             : 
    4252           4 :             if (CSLFetchNameValue(papszMD, GDAL_DMD_OPENOPTIONLIST))
    4253             :             {
    4254           3 :                 CPLXMLNode *psCOL = CPLParseXMLString(
    4255             :                     CSLFetchNameValue(papszMD, GDAL_DMD_OPENOPTIONLIST));
    4256           3 :                 StripIrrelevantOptions(psCOL, nOptions);
    4257           3 :                 char *pszFormattedXML = CPLSerializeXMLTree(psCOL);
    4258             : 
    4259           3 :                 CPLDestroyXMLNode(psCOL);
    4260             : 
    4261           3 :                 printf("%s\n", pszFormattedXML); /*ok*/
    4262           3 :                 CPLFree(pszFormattedXML);
    4263             :             }
    4264             : 
    4265           4 :             bool bFirstOtherOption = true;
    4266         149 :             for (char **papszIter = papszMD; papszIter && *papszIter;
    4267             :                  ++papszIter)
    4268             :             {
    4269         145 :                 if (!STARTS_WITH(*papszIter, "DCAP_") &&
    4270          62 :                     !STARTS_WITH(*papszIter, "DMD_") &&
    4271          16 :                     !STARTS_WITH(*papszIter, "DS_") &&
    4272          13 :                     !STARTS_WITH(*papszIter, "OGR_DRIVER="))
    4273             :                 {
    4274          13 :                     if (bFirstOtherOption)
    4275           4 :                         printf("  Other metadata items:\n"); /*ok*/
    4276          13 :                     bFirstOtherOption = false;
    4277          13 :                     printf("    %s\n", *papszIter); /*ok*/
    4278             :                 }
    4279             :             }
    4280             : 
    4281           4 :             return 0;
    4282             :         }
    4283             : 
    4284             :         /* --------------------------------------------------------------------
    4285             :          */
    4286             :         /*      --help-general */
    4287             :         /* --------------------------------------------------------------------
    4288             :          */
    4289        6555 :         else if (EQUAL(papszArgv[iArg], "--help-general"))
    4290             :         {
    4291           2 :             printf("Generic GDAL utility command options:\n");       /*ok*/
    4292           2 :             printf("  --version: report version of GDAL in use.\n"); /*ok*/
    4293           2 :             /*ok*/ printf(
    4294             :                 "  --build: report detailed information about GDAL in "
    4295             :                 "use.\n");
    4296           2 :             printf("  --license: report GDAL license info.\n"); /*ok*/
    4297           2 :             printf(                                             /*ok*/
    4298             :                    "  --formats: report all configured format drivers.\n"); /*ok*/
    4299           2 :             printf("  --format [<format>]: details of one format.\n"); /*ok*/
    4300           2 :             /*ok*/ printf(
    4301             :                 "  --optfile filename: expand an option file into the "
    4302             :                 "argument list.\n");
    4303           2 :             printf(/*ok*/
    4304             :                    "  --config <key> <value> or --config <key>=<value>: set "
    4305             :                    "system configuration option.\n");               /*ok*/
    4306           2 :             printf("  --debug [on/off/value]: set debug level.\n"); /*ok*/
    4307           2 :             /*ok*/ printf(                                          /*ok*/
    4308             :                           "  --pause: wait for user input, time to attach "
    4309             :                           "debugger\n");
    4310           2 :             printf("  --locale [<locale>]: install locale for debugging " /*ok*/
    4311             :                    "(i.e. en_US.UTF-8)\n");
    4312           2 :             printf("  --help-general: report detailed help on general " /*ok*/
    4313             :                    "options.\n");
    4314             : 
    4315           2 :             return 0;
    4316             :         }
    4317             : 
    4318             :         /* --------------------------------------------------------------------
    4319             :          */
    4320             :         /*      --locale */
    4321             :         /* --------------------------------------------------------------------
    4322             :          */
    4323        6553 :         else if (iArg < nArgc - 1 && EQUAL(papszArgv[iArg], "--locale"))
    4324             :         {
    4325           2 :             CPLsetlocale(LC_ALL, papszArgv[++iArg]);
    4326             :         }
    4327             : 
    4328             :         /* --------------------------------------------------------------------
    4329             :          */
    4330             :         /*      --pause */
    4331             :         /* --------------------------------------------------------------------
    4332             :          */
    4333        6551 :         else if (EQUAL(papszArgv[iArg], "--pause"))
    4334             :         {
    4335           0 :             std::cout << "Hit <ENTER> to Continue." << std::endl;
    4336           0 :             std::cin.clear();
    4337           0 :             std::cin.ignore(cpl::NumericLimits<std::streamsize>::max(), '\n');
    4338             :         }
    4339             : 
    4340             :         /* --------------------------------------------------------------------
    4341             :          */
    4342             :         /*      Carry through unrecognized options. */
    4343             :         /* --------------------------------------------------------------------
    4344             :          */
    4345             :         else
    4346             :         {
    4347        6551 :             aosReturn.AddString(papszArgv[iArg]);
    4348             :         }
    4349             :     }
    4350             : 
    4351        1222 :     const int nSize = aosReturn.size();
    4352        1222 :     *ppapszArgv = aosReturn.StealList();
    4353             : 
    4354        1222 :     return nSize;
    4355             : }
    4356             : 
    4357             : /************************************************************************/
    4358             : /*                          _FetchDblFromMD()                           */
    4359             : /************************************************************************/
    4360             : 
    4361        1680 : static bool _FetchDblFromMD(CSLConstList papszMD, const char *pszKey,
    4362             :                             double *padfTarget, int nCount, double dfDefault)
    4363             : 
    4364             : {
    4365             :     char szFullKey[200];
    4366             : 
    4367        1680 :     snprintf(szFullKey, sizeof(szFullKey), "%s", pszKey);
    4368             : 
    4369        1680 :     const char *pszValue = CSLFetchNameValue(papszMD, szFullKey);
    4370             : 
    4371        9744 :     for (int i = 0; i < nCount; i++)
    4372        8064 :         padfTarget[i] = dfDefault;
    4373             : 
    4374        1680 :     if (pszValue == nullptr)
    4375         414 :         return false;
    4376             : 
    4377        1266 :     if (nCount == 1)
    4378             :     {
    4379         930 :         *padfTarget = CPLAtofM(pszValue);
    4380         930 :         return true;
    4381             :     }
    4382             : 
    4383         336 :     char **papszTokens = CSLTokenizeStringComplex(pszValue, " ,", FALSE, FALSE);
    4384             : 
    4385         336 :     if (CSLCount(papszTokens) != nCount)
    4386             :     {
    4387           0 :         CSLDestroy(papszTokens);
    4388           0 :         return false;
    4389             :     }
    4390             : 
    4391        7056 :     for (int i = 0; i < nCount; i++)
    4392        6720 :         padfTarget[i] = CPLAtofM(papszTokens[i]);
    4393             : 
    4394         336 :     CSLDestroy(papszTokens);
    4395             : 
    4396         336 :     return true;
    4397             : }
    4398             : 
    4399             : /************************************************************************/
    4400             : /*                         GDALExtractRPCInfo()                         */
    4401             : /************************************************************************/
    4402             : 
    4403             : /** Extract RPC info from metadata, and apply to an RPCInfo structure.
    4404             :  *
    4405             :  * The inverse of this function is RPCInfoV1ToMD() in alg/gdal_rpc.cpp
    4406             :  *
    4407             :  * @param papszMD Dictionary of metadata representing RPC
    4408             :  * @param psRPC (output) Pointer to structure to hold the RPC values.
    4409             :  * @return TRUE in case of success. FALSE in case of failure.
    4410             :  */
    4411           0 : int CPL_STDCALL GDALExtractRPCInfoV1(CSLConstList papszMD, GDALRPCInfoV1 *psRPC)
    4412             : 
    4413             : {
    4414             :     GDALRPCInfoV2 sRPC;
    4415           0 :     if (!GDALExtractRPCInfoV2(papszMD, &sRPC))
    4416           0 :         return FALSE;
    4417           0 :     memcpy(psRPC, &sRPC, sizeof(GDALRPCInfoV1));
    4418           0 :     return TRUE;
    4419             : }
    4420             : 
    4421             : /** Extract RPC info from metadata, and apply to an RPCInfo structure.
    4422             :  *
    4423             :  * The inverse of this function is RPCInfoV2ToMD() in alg/gdal_rpc.cpp
    4424             :  *
    4425             :  * @param papszMD Dictionary of metadata representing RPC
    4426             :  * @param psRPC (output) Pointer to structure to hold the RPC values.
    4427             :  * @return TRUE in case of success. FALSE in case of failure.
    4428             :  */
    4429          84 : int CPL_STDCALL GDALExtractRPCInfoV2(CSLConstList papszMD, GDALRPCInfoV2 *psRPC)
    4430             : 
    4431             : {
    4432          84 :     if (CSLFetchNameValue(papszMD, RPC_LINE_NUM_COEFF) == nullptr)
    4433           0 :         return FALSE;
    4434             : 
    4435          84 :     if (CSLFetchNameValue(papszMD, RPC_LINE_NUM_COEFF) == nullptr ||
    4436          84 :         CSLFetchNameValue(papszMD, RPC_LINE_DEN_COEFF) == nullptr ||
    4437         252 :         CSLFetchNameValue(papszMD, RPC_SAMP_NUM_COEFF) == nullptr ||
    4438          84 :         CSLFetchNameValue(papszMD, RPC_SAMP_DEN_COEFF) == nullptr)
    4439             :     {
    4440           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    4441             :                  "Some required RPC metadata missing in GDALExtractRPCInfo()");
    4442           0 :         return FALSE;
    4443             :     }
    4444             : 
    4445          84 :     _FetchDblFromMD(papszMD, RPC_ERR_BIAS, &(psRPC->dfERR_BIAS), 1, -1.0);
    4446          84 :     _FetchDblFromMD(papszMD, RPC_ERR_RAND, &(psRPC->dfERR_RAND), 1, -1.0);
    4447          84 :     _FetchDblFromMD(papszMD, RPC_LINE_OFF, &(psRPC->dfLINE_OFF), 1, 0.0);
    4448          84 :     _FetchDblFromMD(papszMD, RPC_LINE_SCALE, &(psRPC->dfLINE_SCALE), 1, 1.0);
    4449          84 :     _FetchDblFromMD(papszMD, RPC_SAMP_OFF, &(psRPC->dfSAMP_OFF), 1, 0.0);
    4450          84 :     _FetchDblFromMD(papszMD, RPC_SAMP_SCALE, &(psRPC->dfSAMP_SCALE), 1, 1.0);
    4451          84 :     _FetchDblFromMD(papszMD, RPC_HEIGHT_OFF, &(psRPC->dfHEIGHT_OFF), 1, 0.0);
    4452          84 :     _FetchDblFromMD(papszMD, RPC_HEIGHT_SCALE, &(psRPC->dfHEIGHT_SCALE), 1,
    4453             :                     1.0);
    4454          84 :     _FetchDblFromMD(papszMD, RPC_LAT_OFF, &(psRPC->dfLAT_OFF), 1, 0.0);
    4455          84 :     _FetchDblFromMD(papszMD, RPC_LAT_SCALE, &(psRPC->dfLAT_SCALE), 1, 1.0);
    4456          84 :     _FetchDblFromMD(papszMD, RPC_LONG_OFF, &(psRPC->dfLONG_OFF), 1, 0.0);
    4457          84 :     _FetchDblFromMD(papszMD, RPC_LONG_SCALE, &(psRPC->dfLONG_SCALE), 1, 1.0);
    4458             : 
    4459          84 :     _FetchDblFromMD(papszMD, RPC_LINE_NUM_COEFF, psRPC->adfLINE_NUM_COEFF, 20,
    4460             :                     0.0);
    4461          84 :     _FetchDblFromMD(papszMD, RPC_LINE_DEN_COEFF, psRPC->adfLINE_DEN_COEFF, 20,
    4462             :                     0.0);
    4463          84 :     _FetchDblFromMD(papszMD, RPC_SAMP_NUM_COEFF, psRPC->adfSAMP_NUM_COEFF, 20,
    4464             :                     0.0);
    4465          84 :     _FetchDblFromMD(papszMD, RPC_SAMP_DEN_COEFF, psRPC->adfSAMP_DEN_COEFF, 20,
    4466             :                     0.0);
    4467             : 
    4468          84 :     _FetchDblFromMD(papszMD, RPC_MIN_LONG, &(psRPC->dfMIN_LONG), 1, -180.0);
    4469          84 :     _FetchDblFromMD(papszMD, RPC_MIN_LAT, &(psRPC->dfMIN_LAT), 1, -90.0);
    4470          84 :     _FetchDblFromMD(papszMD, RPC_MAX_LONG, &(psRPC->dfMAX_LONG), 1, 180.0);
    4471          84 :     _FetchDblFromMD(papszMD, RPC_MAX_LAT, &(psRPC->dfMAX_LAT), 1, 90.0);
    4472             : 
    4473          84 :     return TRUE;
    4474             : }
    4475             : 
    4476             : /************************************************************************/
    4477             : /*                     GDALFindAssociatedAuxFile()                      */
    4478             : /************************************************************************/
    4479             : 
    4480       10200 : GDALDataset *GDALFindAssociatedAuxFile(const char *pszBasename,
    4481             :                                        GDALAccess eAccess,
    4482             :                                        GDALDataset *poDependentDS)
    4483             : 
    4484             : {
    4485       10200 :     const char *pszAuxSuffixLC = "aux";
    4486       10200 :     const char *pszAuxSuffixUC = "AUX";
    4487             : 
    4488       10200 :     if (EQUAL(CPLGetExtensionSafe(pszBasename).c_str(), pszAuxSuffixLC))
    4489          32 :         return nullptr;
    4490             : 
    4491             :     /* -------------------------------------------------------------------- */
    4492             :     /*      Don't even try to look for an .aux file if we don't have a      */
    4493             :     /*      path of any kind.                                               */
    4494             :     /* -------------------------------------------------------------------- */
    4495       10168 :     if (strlen(pszBasename) == 0)
    4496          50 :         return nullptr;
    4497             : 
    4498             :     /* -------------------------------------------------------------------- */
    4499             :     /*      We didn't find that, so try and find a corresponding aux        */
    4500             :     /*      file.  Check that we are the dependent file of the aux          */
    4501             :     /*      file, or if we aren't verify that the dependent file does       */
    4502             :     /*      not exist, likely mean it is us but some sort of renaming       */
    4503             :     /*      has occurred.                                                   */
    4504             :     /* -------------------------------------------------------------------- */
    4505       20236 :     CPLString osJustFile = CPLGetFilename(pszBasename);  // without dir
    4506             :     CPLString osAuxFilename =
    4507       10118 :         CPLResetExtensionSafe(pszBasename, pszAuxSuffixLC);
    4508       10118 :     GDALDataset *poODS = nullptr;
    4509             :     GByte abyHeader[32];
    4510             : 
    4511       10118 :     VSILFILE *fp = VSIFOpenL(osAuxFilename, "rb");
    4512             : 
    4513       10118 :     if (fp == nullptr && VSIIsCaseSensitiveFS(osAuxFilename))
    4514             :     {
    4515             :         // Can't found file with lower case suffix. Try the upper case one.
    4516       10095 :         osAuxFilename = CPLResetExtensionSafe(pszBasename, pszAuxSuffixUC);
    4517       10095 :         fp = VSIFOpenL(osAuxFilename, "rb");
    4518             :     }
    4519             : 
    4520       10118 :     if (fp != nullptr)
    4521             :     {
    4522          46 :         if (VSIFReadL(abyHeader, 1, 32, fp) == 32 &&
    4523          23 :             STARTS_WITH_CI(reinterpret_cast<const char *>(abyHeader),
    4524             :                            "EHFA_HEADER_TAG"))
    4525             :         {
    4526             :             /* Avoid causing failure in opening of main file from SWIG bindings
    4527             :              */
    4528             :             /* when auxiliary file cannot be opened (#3269) */
    4529          36 :             CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
    4530          18 :             if (poDependentDS != nullptr && poDependentDS->GetShared())
    4531           0 :                 poODS = GDALDataset::FromHandle(
    4532             :                     GDALOpenShared(osAuxFilename, eAccess));
    4533             :             else
    4534             :                 poODS =
    4535          18 :                     GDALDataset::FromHandle(GDALOpen(osAuxFilename, eAccess));
    4536             :         }
    4537          23 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
    4538             :     }
    4539             : 
    4540             :     /* -------------------------------------------------------------------- */
    4541             :     /*      Try replacing extension with .aux                               */
    4542             :     /* -------------------------------------------------------------------- */
    4543       10118 :     if (poODS != nullptr)
    4544             :     {
    4545             :         const char *pszDep =
    4546          18 :             poODS->GetMetadataItem("HFA_DEPENDENT_FILE", "HFA");
    4547          18 :         if (pszDep == nullptr)
    4548             :         {
    4549           0 :             CPLDebug("AUX", "Found %s but it has no dependent file, ignoring.",
    4550             :                      osAuxFilename.c_str());
    4551           0 :             GDALClose(poODS);
    4552           0 :             poODS = nullptr;
    4553             :         }
    4554          18 :         else if (!EQUAL(pszDep, osJustFile))
    4555             :         {
    4556             :             VSIStatBufL sStatBuf;
    4557             : 
    4558           0 :             if (VSIStatExL(pszDep, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
    4559             :             {
    4560           0 :                 CPLDebug("AUX", "%s is for file %s, not %s, ignoring.",
    4561             :                          osAuxFilename.c_str(), pszDep, osJustFile.c_str());
    4562           0 :                 GDALClose(poODS);
    4563           0 :                 poODS = nullptr;
    4564             :             }
    4565             :             else
    4566             :             {
    4567           0 :                 CPLDebug("AUX",
    4568             :                          "%s is for file %s, not %s, but since\n"
    4569             :                          "%s does not exist, we will use .aux file as our own.",
    4570             :                          osAuxFilename.c_str(), pszDep, osJustFile.c_str(),
    4571             :                          pszDep);
    4572             :             }
    4573             :         }
    4574             : 
    4575             :         /* --------------------------------------------------------------------
    4576             :          */
    4577             :         /*      Confirm that the aux file matches the configuration of the */
    4578             :         /*      dependent dataset. */
    4579             :         /* --------------------------------------------------------------------
    4580             :          */
    4581          36 :         if (poODS != nullptr && poDependentDS != nullptr &&
    4582          18 :             (poODS->GetRasterCount() != poDependentDS->GetRasterCount() ||
    4583          18 :              poODS->GetRasterXSize() != poDependentDS->GetRasterXSize() ||
    4584          15 :              poODS->GetRasterYSize() != poDependentDS->GetRasterYSize()))
    4585             :         {
    4586           3 :             CPLDebug("AUX",
    4587             :                      "Ignoring aux file %s as its raster configuration\n"
    4588             :                      "(%dP x %dL x %dB) does not match master file (%dP x %dL "
    4589             :                      "x %dB)",
    4590             :                      osAuxFilename.c_str(), poODS->GetRasterXSize(),
    4591             :                      poODS->GetRasterYSize(), poODS->GetRasterCount(),
    4592             :                      poDependentDS->GetRasterXSize(),
    4593             :                      poDependentDS->GetRasterYSize(),
    4594             :                      poDependentDS->GetRasterCount());
    4595             : 
    4596           3 :             GDALClose(poODS);
    4597           3 :             poODS = nullptr;
    4598             :         }
    4599             :     }
    4600             : 
    4601             :     /* -------------------------------------------------------------------- */
    4602             :     /*      Try appending .aux to the end of the filename.                  */
    4603             :     /* -------------------------------------------------------------------- */
    4604       10118 :     if (poODS == nullptr)
    4605             :     {
    4606       10103 :         osAuxFilename = pszBasename;
    4607       10103 :         osAuxFilename += ".";
    4608       10103 :         osAuxFilename += pszAuxSuffixLC;
    4609       10103 :         fp = VSIFOpenL(osAuxFilename, "rb");
    4610       10103 :         if (fp == nullptr && VSIIsCaseSensitiveFS(osAuxFilename))
    4611             :         {
    4612             :             // Can't found file with lower case suffix. Try the upper case one.
    4613       10103 :             osAuxFilename = pszBasename;
    4614       10103 :             osAuxFilename += ".";
    4615       10103 :             osAuxFilename += pszAuxSuffixUC;
    4616       10103 :             fp = VSIFOpenL(osAuxFilename, "rb");
    4617             :         }
    4618             : 
    4619       10103 :         if (fp != nullptr)
    4620             :         {
    4621           0 :             if (VSIFReadL(abyHeader, 1, 32, fp) == 32 &&
    4622           0 :                 STARTS_WITH_CI(reinterpret_cast<const char *>(abyHeader),
    4623             :                                "EHFA_HEADER_TAG"))
    4624             :             {
    4625             :                 /* Avoid causing failure in opening of main file from SWIG
    4626             :                  * bindings */
    4627             :                 /* when auxiliary file cannot be opened (#3269) */
    4628           0 :                 CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
    4629           0 :                 if (poDependentDS != nullptr && poDependentDS->GetShared())
    4630           0 :                     poODS = GDALDataset::FromHandle(
    4631             :                         GDALOpenShared(osAuxFilename, eAccess));
    4632             :                 else
    4633           0 :                     poODS = GDALDataset::FromHandle(
    4634             :                         GDALOpen(osAuxFilename, eAccess));
    4635             :             }
    4636           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
    4637             :         }
    4638             : 
    4639       10103 :         if (poODS != nullptr)
    4640             :         {
    4641             :             const char *pszDep =
    4642           0 :                 poODS->GetMetadataItem("HFA_DEPENDENT_FILE", "HFA");
    4643           0 :             if (pszDep == nullptr)
    4644             :             {
    4645           0 :                 CPLDebug("AUX",
    4646             :                          "Found %s but it has no dependent file, ignoring.",
    4647             :                          osAuxFilename.c_str());
    4648           0 :                 GDALClose(poODS);
    4649           0 :                 poODS = nullptr;
    4650             :             }
    4651           0 :             else if (!EQUAL(pszDep, osJustFile))
    4652             :             {
    4653             :                 VSIStatBufL sStatBuf;
    4654             : 
    4655           0 :                 if (VSIStatExL(pszDep, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
    4656             :                 {
    4657           0 :                     CPLDebug("AUX", "%s is for file %s, not %s, ignoring.",
    4658             :                              osAuxFilename.c_str(), pszDep, osJustFile.c_str());
    4659           0 :                     GDALClose(poODS);
    4660           0 :                     poODS = nullptr;
    4661             :                 }
    4662             :                 else
    4663             :                 {
    4664           0 :                     CPLDebug(
    4665             :                         "AUX",
    4666             :                         "%s is for file %s, not %s, but since\n"
    4667             :                         "%s does not exist, we will use .aux file as our own.",
    4668             :                         osAuxFilename.c_str(), pszDep, osJustFile.c_str(),
    4669             :                         pszDep);
    4670             :                 }
    4671             :             }
    4672             :         }
    4673             :     }
    4674             : 
    4675             :     /* -------------------------------------------------------------------- */
    4676             :     /*      Confirm that the aux file matches the configuration of the      */
    4677             :     /*      dependent dataset.                                              */
    4678             :     /* -------------------------------------------------------------------- */
    4679       10133 :     if (poODS != nullptr && poDependentDS != nullptr &&
    4680          15 :         (poODS->GetRasterCount() != poDependentDS->GetRasterCount() ||
    4681          15 :          poODS->GetRasterXSize() != poDependentDS->GetRasterXSize() ||
    4682          15 :          poODS->GetRasterYSize() != poDependentDS->GetRasterYSize()))
    4683             :     {
    4684           0 :         CPLDebug(
    4685             :             "AUX",
    4686             :             "Ignoring aux file %s as its raster configuration\n"
    4687             :             "(%dP x %dL x %dB) does not match master file (%dP x %dL x %dB)",
    4688             :             osAuxFilename.c_str(), poODS->GetRasterXSize(),
    4689             :             poODS->GetRasterYSize(), poODS->GetRasterCount(),
    4690             :             poDependentDS->GetRasterXSize(), poDependentDS->GetRasterYSize(),
    4691             :             poDependentDS->GetRasterCount());
    4692             : 
    4693           0 :         GDALClose(poODS);
    4694           0 :         poODS = nullptr;
    4695             :     }
    4696             : 
    4697       10118 :     return poODS;
    4698             : }
    4699             : 
    4700             : /************************************************************************/
    4701             : /* Infrastructure to check that dataset characteristics are valid       */
    4702             : /************************************************************************/
    4703             : 
    4704             : CPL_C_START
    4705             : 
    4706             : /**
    4707             :  * \brief Return TRUE if the dataset dimensions are valid.
    4708             :  *
    4709             :  * @param nXSize raster width
    4710             :  * @param nYSize raster height
    4711             :  *
    4712             :  * @since GDAL 1.7.0
    4713             :  */
    4714        5399 : int GDALCheckDatasetDimensions(int nXSize, int nYSize)
    4715             : {
    4716        5399 :     if (nXSize <= 0 || nYSize <= 0)
    4717             :     {
    4718           8 :         CPLError(CE_Failure, CPLE_AppDefined,
    4719             :                  "Invalid dataset dimensions : %d x %d", nXSize, nYSize);
    4720           8 :         return FALSE;
    4721             :     }
    4722        5391 :     return TRUE;
    4723             : }
    4724             : 
    4725             : /**
    4726             :  * \brief Return TRUE if the band count is valid.
    4727             :  *
    4728             :  * If the configuration option GDAL_MAX_BAND_COUNT is defined,
    4729             :  * the band count will be compared to the maximum number of band allowed.
    4730             :  * If not defined, the maximum number allowed is 65536.
    4731             :  *
    4732             :  * @param nBands the band count
    4733             :  * @param bIsZeroAllowed TRUE if band count == 0 is allowed
    4734             :  *
    4735             :  * @since GDAL 1.7.0
    4736             :  */
    4737             : 
    4738        8775 : int GDALCheckBandCount(int nBands, int bIsZeroAllowed)
    4739             : {
    4740        8775 :     if (nBands < 0 || (!bIsZeroAllowed && nBands == 0))
    4741             :     {
    4742           6 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid band count : %d",
    4743             :                  nBands);
    4744           6 :         return FALSE;
    4745             :     }
    4746             :     const char *pszMaxBandCount =
    4747        8769 :         CPLGetConfigOption("GDAL_MAX_BAND_COUNT", "65536");
    4748             :     /* coverity[tainted_data] */
    4749        8769 :     int nMaxBands = atoi(pszMaxBandCount);
    4750        8769 :     if (nBands > nMaxBands)
    4751             :     {
    4752           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    4753             :                  "Invalid band count : %d. Maximum allowed currently is %d. "
    4754             :                  "Define GDAL_MAX_BAND_COUNT to a higher level if it is a "
    4755             :                  "legitimate number.",
    4756             :                  nBands, nMaxBands);
    4757           2 :         return FALSE;
    4758             :     }
    4759        8767 :     return TRUE;
    4760             : }
    4761             : 
    4762             : CPL_C_END
    4763             : 
    4764             : /************************************************************************/
    4765             : /*                     GDALSerializeGCPListToXML()                      */
    4766             : /************************************************************************/
    4767             : 
    4768          16 : void GDALSerializeGCPListToXML(CPLXMLNode *psParentNode,
    4769             :                                const std::vector<gdal::GCP> &asGCPs,
    4770             :                                const OGRSpatialReference *poGCP_SRS)
    4771             : {
    4772          32 :     CPLString oFmt;
    4773             : 
    4774             :     CPLXMLNode *psPamGCPList =
    4775          16 :         CPLCreateXMLNode(psParentNode, CXT_Element, "GCPList");
    4776             : 
    4777          16 :     CPLXMLNode *psLastChild = nullptr;
    4778             : 
    4779          16 :     if (poGCP_SRS != nullptr && !poGCP_SRS->IsEmpty())
    4780             :     {
    4781           9 :         char *pszWKT = nullptr;
    4782           9 :         poGCP_SRS->exportToWkt(&pszWKT);
    4783           9 :         CPLSetXMLValue(psPamGCPList, "#Projection", pszWKT);
    4784           9 :         CPLFree(pszWKT);
    4785           9 :         const auto &mapping = poGCP_SRS->GetDataAxisToSRSAxisMapping();
    4786           9 :         CPLString osMapping;
    4787          27 :         for (size_t i = 0; i < mapping.size(); ++i)
    4788             :         {
    4789          18 :             if (!osMapping.empty())
    4790           9 :                 osMapping += ",";
    4791          18 :             osMapping += CPLSPrintf("%d", mapping[i]);
    4792             :         }
    4793           9 :         CPLSetXMLValue(psPamGCPList, "#dataAxisToSRSAxisMapping",
    4794             :                        osMapping.c_str());
    4795             : 
    4796           9 :         psLastChild = psPamGCPList->psChild->psNext;
    4797             :     }
    4798             : 
    4799       21896 :     for (const gdal::GCP &gcp : asGCPs)
    4800             :     {
    4801       21880 :         CPLXMLNode *psXMLGCP = CPLCreateXMLNode(nullptr, CXT_Element, "GCP");
    4802             : 
    4803       21880 :         if (psLastChild == nullptr)
    4804           7 :             psPamGCPList->psChild = psXMLGCP;
    4805             :         else
    4806       21873 :             psLastChild->psNext = psXMLGCP;
    4807       21880 :         psLastChild = psXMLGCP;
    4808             : 
    4809       21880 :         CPLSetXMLValue(psXMLGCP, "#Id", gcp.Id());
    4810             : 
    4811       21880 :         if (gcp.Info() != nullptr && strlen(gcp.Info()) > 0)
    4812           0 :             CPLSetXMLValue(psXMLGCP, "Info", gcp.Info());
    4813             : 
    4814       21880 :         CPLSetXMLValue(psXMLGCP, "#Pixel", oFmt.Printf("%.4f", gcp.Pixel()));
    4815             : 
    4816       21880 :         CPLSetXMLValue(psXMLGCP, "#Line", oFmt.Printf("%.4f", gcp.Line()));
    4817             : 
    4818       21880 :         CPLSetXMLValue(psXMLGCP, "#X", oFmt.Printf("%.12E", gcp.X()));
    4819             : 
    4820       21880 :         CPLSetXMLValue(psXMLGCP, "#Y", oFmt.Printf("%.12E", gcp.Y()));
    4821             : 
    4822             :         /* Note: GDAL 1.10.1 and older generated #GCPZ, but could not read it
    4823             :          * back */
    4824       21880 :         if (gcp.Z() != 0.0)
    4825       21860 :             CPLSetXMLValue(psXMLGCP, "#Z", oFmt.Printf("%.12E", gcp.Z()));
    4826             :     }
    4827          16 : }
    4828             : 
    4829             : /************************************************************************/
    4830             : /*                     GDALDeserializeGCPListFromXML()                  */
    4831             : /************************************************************************/
    4832             : 
    4833          84 : void GDALDeserializeGCPListFromXML(const CPLXMLNode *psGCPList,
    4834             :                                    std::vector<gdal::GCP> &asGCPs,
    4835             :                                    OGRSpatialReference **ppoGCP_SRS)
    4836             : {
    4837          84 :     if (ppoGCP_SRS)
    4838             :     {
    4839             :         const char *pszRawProj =
    4840          76 :             CPLGetXMLValue(psGCPList, "Projection", nullptr);
    4841             : 
    4842          76 :         *ppoGCP_SRS = nullptr;
    4843          76 :         if (pszRawProj && pszRawProj[0])
    4844             :         {
    4845          60 :             *ppoGCP_SRS = new OGRSpatialReference();
    4846             :             (*ppoGCP_SRS)
    4847          60 :                 ->SetFromUserInput(
    4848             :                     pszRawProj,
    4849             :                     OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS);
    4850             : 
    4851             :             const char *pszMapping =
    4852          60 :                 CPLGetXMLValue(psGCPList, "dataAxisToSRSAxisMapping", nullptr);
    4853          60 :             if (pszMapping)
    4854             :             {
    4855             :                 char **papszTokens =
    4856          13 :                     CSLTokenizeStringComplex(pszMapping, ",", FALSE, FALSE);
    4857          26 :                 std::vector<int> anMapping;
    4858          39 :                 for (int i = 0; papszTokens && papszTokens[i]; i++)
    4859             :                 {
    4860          26 :                     anMapping.push_back(atoi(papszTokens[i]));
    4861             :                 }
    4862          13 :                 CSLDestroy(papszTokens);
    4863          13 :                 (*ppoGCP_SRS)->SetDataAxisToSRSAxisMapping(anMapping);
    4864             :             }
    4865             :             else
    4866             :             {
    4867             :                 (*ppoGCP_SRS)
    4868          47 :                     ->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    4869             :             }
    4870             :         }
    4871             :     }
    4872             : 
    4873          84 :     asGCPs.clear();
    4874       24612 :     for (const CPLXMLNode *psXMLGCP = psGCPList->psChild; psXMLGCP;
    4875       24528 :          psXMLGCP = psXMLGCP->psNext)
    4876             :     {
    4877       24528 :         if (!EQUAL(psXMLGCP->pszValue, "GCP") || psXMLGCP->eType != CXT_Element)
    4878          81 :             continue;
    4879             : 
    4880       48894 :         gdal::GCP gcp;
    4881       24447 :         gcp.SetId(CPLGetXMLValue(psXMLGCP, "Id", ""));
    4882       24447 :         gcp.SetInfo(CPLGetXMLValue(psXMLGCP, "Info", ""));
    4883             : 
    4884             :         const auto ParseDoubleValue =
    4885       97788 :             [psXMLGCP](const char *pszParameter, double &dfVal)
    4886             :         {
    4887             :             const char *pszVal =
    4888       97788 :                 CPLGetXMLValue(psXMLGCP, pszParameter, nullptr);
    4889       97788 :             if (!pszVal)
    4890             :             {
    4891           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "GCP#%s is missing",
    4892             :                          pszParameter);
    4893           0 :                 return false;
    4894             :             }
    4895       97788 :             char *endptr = nullptr;
    4896       97788 :             dfVal = CPLStrtod(pszVal, &endptr);
    4897       97788 :             if (endptr == pszVal)
    4898             :             {
    4899           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4900             :                          "GCP#%s=%s is an invalid value", pszParameter, pszVal);
    4901           0 :                 return false;
    4902             :             }
    4903       97788 :             return true;
    4904       24447 :         };
    4905             : 
    4906       24447 :         bool bOK = true;
    4907       24447 :         if (!ParseDoubleValue("Pixel", gcp.Pixel()))
    4908           0 :             bOK = false;
    4909       24447 :         if (!ParseDoubleValue("Line", gcp.Line()))
    4910           0 :             bOK = false;
    4911       24447 :         if (!ParseDoubleValue("X", gcp.X()))
    4912           0 :             bOK = false;
    4913       24447 :         if (!ParseDoubleValue("Y", gcp.Y()))
    4914           0 :             bOK = false;
    4915       24447 :         const char *pszZ = CPLGetXMLValue(psXMLGCP, "Z", nullptr);
    4916       24447 :         if (pszZ == nullptr)
    4917             :         {
    4918             :             // Note: GDAL 1.10.1 and older generated #GCPZ,
    4919             :             // but could not read it back.
    4920        2379 :             pszZ = CPLGetXMLValue(psXMLGCP, "GCPZ", "0.0");
    4921             :         }
    4922       24447 :         char *endptr = nullptr;
    4923       24447 :         gcp.Z() = CPLStrtod(pszZ, &endptr);
    4924       24447 :         if (endptr == pszZ)
    4925             :         {
    4926           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4927             :                      "GCP#Z=%s is an invalid value", pszZ);
    4928           0 :             bOK = false;
    4929             :         }
    4930             : 
    4931       24447 :         if (bOK)
    4932             :         {
    4933       24447 :             asGCPs.emplace_back(std::move(gcp));
    4934             :         }
    4935             :     }
    4936          84 : }
    4937             : 
    4938             : /************************************************************************/
    4939             : /*                   GDALSerializeOpenOptionsToXML()                    */
    4940             : /************************************************************************/
    4941             : 
    4942        2669 : void GDALSerializeOpenOptionsToXML(CPLXMLNode *psParentNode,
    4943             :                                    CSLConstList papszOpenOptions)
    4944             : {
    4945        2669 :     if (papszOpenOptions != nullptr)
    4946             :     {
    4947             :         CPLXMLNode *psOpenOptions =
    4948           5 :             CPLCreateXMLNode(psParentNode, CXT_Element, "OpenOptions");
    4949           5 :         CPLXMLNode *psLastChild = nullptr;
    4950             : 
    4951          10 :         for (CSLConstList papszIter = papszOpenOptions; *papszIter != nullptr;
    4952             :              papszIter++)
    4953             :         {
    4954             :             const char *pszRawValue;
    4955           5 :             char *pszKey = nullptr;
    4956             :             CPLXMLNode *psOOI;
    4957             : 
    4958           5 :             pszRawValue = CPLParseNameValue(*papszIter, &pszKey);
    4959             : 
    4960           5 :             psOOI = CPLCreateXMLNode(nullptr, CXT_Element, "OOI");
    4961           5 :             if (psLastChild == nullptr)
    4962           5 :                 psOpenOptions->psChild = psOOI;
    4963             :             else
    4964           0 :                 psLastChild->psNext = psOOI;
    4965           5 :             psLastChild = psOOI;
    4966             : 
    4967           5 :             CPLSetXMLValue(psOOI, "#key", pszKey);
    4968           5 :             CPLCreateXMLNode(psOOI, CXT_Text, pszRawValue);
    4969             : 
    4970           5 :             CPLFree(pszKey);
    4971             :         }
    4972             :     }
    4973        2669 : }
    4974             : 
    4975             : /************************************************************************/
    4976             : /*                  GDALDeserializeOpenOptionsFromXML()                 */
    4977             : /************************************************************************/
    4978             : 
    4979        6057 : char **GDALDeserializeOpenOptionsFromXML(const CPLXMLNode *psParentNode)
    4980             : {
    4981        6057 :     char **papszOpenOptions = nullptr;
    4982             :     const CPLXMLNode *psOpenOptions =
    4983        6057 :         CPLGetXMLNode(psParentNode, "OpenOptions");
    4984        6057 :     if (psOpenOptions != nullptr)
    4985             :     {
    4986             :         const CPLXMLNode *psOOI;
    4987          34 :         for (psOOI = psOpenOptions->psChild; psOOI != nullptr;
    4988          17 :              psOOI = psOOI->psNext)
    4989             :         {
    4990          17 :             if (!EQUAL(psOOI->pszValue, "OOI") || psOOI->eType != CXT_Element ||
    4991          17 :                 psOOI->psChild == nullptr ||
    4992          17 :                 psOOI->psChild->psNext == nullptr ||
    4993          17 :                 psOOI->psChild->eType != CXT_Attribute ||
    4994          17 :                 psOOI->psChild->psChild == nullptr)
    4995           0 :                 continue;
    4996             : 
    4997          17 :             char *pszName = psOOI->psChild->psChild->pszValue;
    4998          17 :             char *pszValue = psOOI->psChild->psNext->pszValue;
    4999          17 :             if (pszName != nullptr && pszValue != nullptr)
    5000             :                 papszOpenOptions =
    5001          17 :                     CSLSetNameValue(papszOpenOptions, pszName, pszValue);
    5002             :         }
    5003             :     }
    5004        6057 :     return papszOpenOptions;
    5005             : }
    5006             : 
    5007             : /************************************************************************/
    5008             : /*                    GDALRasterIOGetResampleAlg()                      */
    5009             : /************************************************************************/
    5010             : 
    5011      203661 : GDALRIOResampleAlg GDALRasterIOGetResampleAlg(const char *pszResampling)
    5012             : {
    5013      203661 :     GDALRIOResampleAlg eResampleAlg = GRIORA_NearestNeighbour;
    5014      203661 :     if (STARTS_WITH_CI(pszResampling, "NEAR"))
    5015      200939 :         eResampleAlg = GRIORA_NearestNeighbour;
    5016        2722 :     else if (EQUAL(pszResampling, "BILINEAR"))
    5017        2082 :         eResampleAlg = GRIORA_Bilinear;
    5018         640 :     else if (EQUAL(pszResampling, "CUBIC"))
    5019         575 :         eResampleAlg = GRIORA_Cubic;
    5020          65 :     else if (EQUAL(pszResampling, "CUBICSPLINE"))
    5021           4 :         eResampleAlg = GRIORA_CubicSpline;
    5022          61 :     else if (EQUAL(pszResampling, "LANCZOS"))
    5023           1 :         eResampleAlg = GRIORA_Lanczos;
    5024          60 :     else if (EQUAL(pszResampling, "AVERAGE"))
    5025          53 :         eResampleAlg = GRIORA_Average;
    5026           7 :     else if (EQUAL(pszResampling, "RMS"))
    5027           1 :         eResampleAlg = GRIORA_RMS;
    5028           6 :     else if (EQUAL(pszResampling, "MODE"))
    5029           5 :         eResampleAlg = GRIORA_Mode;
    5030           1 :     else if (EQUAL(pszResampling, "GAUSS"))
    5031           1 :         eResampleAlg = GRIORA_Gauss;
    5032             :     else
    5033           0 :         CPLError(CE_Warning, CPLE_NotSupported,
    5034             :                  "GDAL_RASTERIO_RESAMPLING = %s not supported", pszResampling);
    5035      203661 :     return eResampleAlg;
    5036             : }
    5037             : 
    5038             : /************************************************************************/
    5039             : /*                    GDALRasterIOGetResampleAlgStr()                   */
    5040             : /************************************************************************/
    5041             : 
    5042           7 : const char *GDALRasterIOGetResampleAlg(GDALRIOResampleAlg eResampleAlg)
    5043             : {
    5044           7 :     switch (eResampleAlg)
    5045             :     {
    5046           0 :         case GRIORA_NearestNeighbour:
    5047           0 :             return "NearestNeighbour";
    5048           0 :         case GRIORA_Bilinear:
    5049           0 :             return "Bilinear";
    5050           7 :         case GRIORA_Cubic:
    5051           7 :             return "Cubic";
    5052           0 :         case GRIORA_CubicSpline:
    5053           0 :             return "CubicSpline";
    5054           0 :         case GRIORA_Lanczos:
    5055           0 :             return "Lanczos";
    5056           0 :         case GRIORA_Average:
    5057           0 :             return "Average";
    5058           0 :         case GRIORA_RMS:
    5059           0 :             return "RMS";
    5060           0 :         case GRIORA_Mode:
    5061           0 :             return "Mode";
    5062           0 :         case GRIORA_Gauss:
    5063           0 :             return "Gauss";
    5064           0 :         default:
    5065           0 :             CPLAssert(false);
    5066             :             return "Unknown";
    5067             :     }
    5068             : }
    5069             : 
    5070             : /************************************************************************/
    5071             : /*                   GDALRasterIOExtraArgSetResampleAlg()               */
    5072             : /************************************************************************/
    5073             : 
    5074     5095550 : void GDALRasterIOExtraArgSetResampleAlg(GDALRasterIOExtraArg *psExtraArg,
    5075             :                                         int nXSize, int nYSize, int nBufXSize,
    5076             :                                         int nBufYSize)
    5077             : {
    5078     5095550 :     if ((nBufXSize != nXSize || nBufYSize != nYSize) &&
    5079      572304 :         psExtraArg->eResampleAlg == GRIORA_NearestNeighbour)
    5080             :     {
    5081             :         const char *pszResampling =
    5082      569010 :             CPLGetConfigOption("GDAL_RASTERIO_RESAMPLING", nullptr);
    5083      569010 :         if (pszResampling != nullptr)
    5084             :         {
    5085           1 :             psExtraArg->eResampleAlg =
    5086           1 :                 GDALRasterIOGetResampleAlg(pszResampling);
    5087             :         }
    5088             :     }
    5089     5095550 : }
    5090             : 
    5091             : /************************************************************************/
    5092             : /*                     GDALCanFileAcceptSidecarFile()                   */
    5093             : /************************************************************************/
    5094             : 
    5095      124657 : int GDALCanFileAcceptSidecarFile(const char *pszFilename)
    5096             : {
    5097      124657 :     if (strstr(pszFilename, "/vsicurl/") && strchr(pszFilename, '?'))
    5098           0 :         return FALSE;
    5099             :     // Do no attempt reading side-car files on /vsisubfile/ (#6241)
    5100      124657 :     if (strncmp(pszFilename, "/vsisubfile/", strlen("/vsisubfile/")) == 0)
    5101         402 :         return FALSE;
    5102      124255 :     return TRUE;
    5103             : }
    5104             : 
    5105             : /************************************************************************/
    5106             : /*                   GDALCanReliablyUseSiblingFileList()                */
    5107             : /************************************************************************/
    5108             : 
    5109             : /* Try to address https://github.com/OSGeo/gdal/issues/2903 */
    5110             : /* - On Apple HFS+ filesystem, filenames are stored in a variant of UTF-8 NFD */
    5111             : /*   (normalization form decomposed). The filesystem takes care of converting */
    5112             : /*   precomposed form as often coming from user interface to this NFD variant */
    5113             : /*   See
    5114             :  * https://stackoverflow.com/questions/6153345/different-utf8-encoding-in-filenames-os-x
    5115             :  */
    5116             : /*   And readdir() will return such NFD variant encoding. Consequently comparing
    5117             :  */
    5118             : /*   the user filename with ones with readdir() is not reliable */
    5119             : /* - APFS preserves both case and normalization of the filename on disk in all
    5120             :  */
    5121             : /*   variants. In macOS High Sierra, APFS is normalization-insensitive in both
    5122             :  */
    5123             : /*   the case-insensitive and case-sensitive variants, using a hash-based native
    5124             :  */
    5125             : /*   normalization scheme. APFS preserves the normalization of the filename and
    5126             :  */
    5127             : /*   uses hashes of the normalized form of the filename to provide normalization
    5128             :  */
    5129             : /*   insensitivity. */
    5130             : /*   From
    5131             :  * https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/APFS_Guide/FAQ/FAQ.html
    5132             :  */
    5133             : /*   Issues might still arise if the file has been created using one of the
    5134             :  * UTF-8 */
    5135             : /*   encoding (likely the decomposed one if using MacOS specific API), but the
    5136             :  */
    5137             : /*   string passed to GDAL for opening would be with another one (likely the
    5138             :  * precomposed one) */
    5139      138802 : bool GDALCanReliablyUseSiblingFileList(const char *pszFilename)
    5140             : {
    5141             : #ifdef __APPLE__
    5142             :     for (int i = 0; pszFilename[i] != 0; ++i)
    5143             :     {
    5144             :         if (reinterpret_cast<const unsigned char *>(pszFilename)[i] > 127)
    5145             :         {
    5146             :             // non-ASCII character found
    5147             : 
    5148             :             // if this is a network storage, assume no issue
    5149             :             if (!VSIIsLocal(pszFilename))
    5150             :             {
    5151             :                 return true;
    5152             :             }
    5153             :             return false;
    5154             :         }
    5155             :     }
    5156             :     return true;
    5157             : #else
    5158             :     (void)pszFilename;
    5159      138802 :     return true;
    5160             : #endif
    5161             : }
    5162             : 
    5163             : /************************************************************************/
    5164             : /*                    GDALAdjustNoDataCloseToFloatMax()                 */
    5165             : /************************************************************************/
    5166             : 
    5167        1345 : double GDALAdjustNoDataCloseToFloatMax(double dfVal)
    5168             : {
    5169        1345 :     const auto kMaxFloat = cpl::NumericLimits<float>::max();
    5170        1345 :     if (std::fabs(dfVal - -kMaxFloat) < 1e-10 * kMaxFloat)
    5171          33 :         return -kMaxFloat;
    5172        1312 :     if (std::fabs(dfVal - kMaxFloat) < 1e-10 * kMaxFloat)
    5173           8 :         return kMaxFloat;
    5174        1304 :     return dfVal;
    5175             : }
    5176             : 
    5177             : /************************************************************************/
    5178             : /*                        GDALCopyNoDataValue()                         */
    5179             : /************************************************************************/
    5180             : 
    5181             : /** Copy the nodata value from the source band to the target band if
    5182             :  * it can be exactly represented in the output data type.
    5183             :  *
    5184             :  * @param poDstBand Destination band.
    5185             :  * @param poSrcBand Source band band.
    5186             :  * @param[out] pbCannotBeExactlyRepresented Pointer to a boolean, or nullptr.
    5187             :  *             If the value cannot be exactly represented on the output data
    5188             :  *             type, *pbCannotBeExactlyRepresented will be set to true.
    5189             :  *
    5190             :  * @return true if the nodata value was successfully set.
    5191             :  */
    5192      134158 : bool GDALCopyNoDataValue(GDALRasterBand *poDstBand, GDALRasterBand *poSrcBand,
    5193             :                          bool *pbCannotBeExactlyRepresented)
    5194             : {
    5195      134158 :     if (pbCannotBeExactlyRepresented)
    5196          99 :         *pbCannotBeExactlyRepresented = false;
    5197             :     int bSuccess;
    5198      134158 :     const auto eSrcDataType = poSrcBand->GetRasterDataType();
    5199      134158 :     const auto eDstDataType = poDstBand->GetRasterDataType();
    5200      134158 :     if (eSrcDataType == GDT_Int64)
    5201             :     {
    5202           8 :         const auto nNoData = poSrcBand->GetNoDataValueAsInt64(&bSuccess);
    5203           8 :         if (bSuccess)
    5204             :         {
    5205           3 :             if (eDstDataType == GDT_Int64)
    5206             :             {
    5207           3 :                 return poDstBand->SetNoDataValueAsInt64(nNoData) == CE_None;
    5208             :             }
    5209           0 :             else if (eDstDataType == GDT_UInt64)
    5210             :             {
    5211           0 :                 if (nNoData >= 0)
    5212             :                 {
    5213           0 :                     return poDstBand->SetNoDataValueAsUInt64(
    5214           0 :                                static_cast<uint64_t>(nNoData)) == CE_None;
    5215             :                 }
    5216             :             }
    5217           0 :             else if (nNoData ==
    5218           0 :                      static_cast<int64_t>(static_cast<double>(nNoData)))
    5219             :             {
    5220           0 :                 const double dfValue = static_cast<double>(nNoData);
    5221           0 :                 if (GDALIsValueExactAs(dfValue, eDstDataType))
    5222           0 :                     return poDstBand->SetNoDataValue(dfValue) == CE_None;
    5223             :             }
    5224             :         }
    5225             :     }
    5226      134150 :     else if (eSrcDataType == GDT_UInt64)
    5227             :     {
    5228           4 :         const auto nNoData = poSrcBand->GetNoDataValueAsUInt64(&bSuccess);
    5229           4 :         if (bSuccess)
    5230             :         {
    5231           3 :             if (eDstDataType == GDT_UInt64)
    5232             :             {
    5233           3 :                 return poDstBand->SetNoDataValueAsUInt64(nNoData) == CE_None;
    5234             :             }
    5235           0 :             else if (eDstDataType == GDT_Int64)
    5236             :             {
    5237           0 :                 if (nNoData <
    5238           0 :                     static_cast<uint64_t>(cpl::NumericLimits<int64_t>::max()))
    5239             :                 {
    5240           0 :                     return poDstBand->SetNoDataValueAsInt64(
    5241           0 :                                static_cast<int64_t>(nNoData)) == CE_None;
    5242             :                 }
    5243             :             }
    5244           0 :             else if (nNoData ==
    5245           0 :                      static_cast<uint64_t>(static_cast<double>(nNoData)))
    5246             :             {
    5247           0 :                 const double dfValue = static_cast<double>(nNoData);
    5248           0 :                 if (GDALIsValueExactAs(dfValue, eDstDataType))
    5249           0 :                     return poDstBand->SetNoDataValue(dfValue) == CE_None;
    5250             :             }
    5251             :         }
    5252             :     }
    5253             :     else
    5254             :     {
    5255      134146 :         const auto dfNoData = poSrcBand->GetNoDataValue(&bSuccess);
    5256      134146 :         if (bSuccess)
    5257             :         {
    5258         374 :             if (eDstDataType == GDT_Int64)
    5259             :             {
    5260           0 :                 if (dfNoData >= static_cast<double>(
    5261           0 :                                     cpl::NumericLimits<int64_t>::lowest()) &&
    5262           0 :                     dfNoData <= static_cast<double>(
    5263           0 :                                     cpl::NumericLimits<int64_t>::max()) &&
    5264             :                     dfNoData ==
    5265           0 :                         static_cast<double>(static_cast<int64_t>(dfNoData)))
    5266             :                 {
    5267           0 :                     return poDstBand->SetNoDataValueAsInt64(
    5268           0 :                                static_cast<int64_t>(dfNoData)) == CE_None;
    5269             :                 }
    5270             :             }
    5271         374 :             else if (eDstDataType == GDT_UInt64)
    5272             :             {
    5273           0 :                 if (dfNoData >= static_cast<double>(
    5274           0 :                                     cpl::NumericLimits<uint64_t>::lowest()) &&
    5275           0 :                     dfNoData <= static_cast<double>(
    5276           0 :                                     cpl::NumericLimits<uint64_t>::max()) &&
    5277             :                     dfNoData ==
    5278           0 :                         static_cast<double>(static_cast<uint64_t>(dfNoData)))
    5279             :                 {
    5280           0 :                     return poDstBand->SetNoDataValueAsInt64(
    5281           0 :                                static_cast<uint64_t>(dfNoData)) == CE_None;
    5282             :                 }
    5283             :             }
    5284             :             else
    5285             :             {
    5286         374 :                 return poDstBand->SetNoDataValue(dfNoData) == CE_None;
    5287             :             }
    5288             :         }
    5289             :     }
    5290      133778 :     if (pbCannotBeExactlyRepresented)
    5291           0 :         *pbCannotBeExactlyRepresented = true;
    5292      133778 :     return false;
    5293             : }
    5294             : 
    5295             : /************************************************************************/
    5296             : /*                     GDALGetNoDataValueCastToDouble()                 */
    5297             : /************************************************************************/
    5298             : 
    5299           2 : double GDALGetNoDataValueCastToDouble(int64_t nVal)
    5300             : {
    5301           2 :     const double dfVal = static_cast<double>(nVal);
    5302           2 :     if (static_cast<int64_t>(dfVal) != nVal)
    5303             :     {
    5304           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    5305             :                  "GetNoDataValue() returns an approximate value of the "
    5306             :                  "true nodata value = " CPL_FRMT_GIB ". Use "
    5307             :                  "GetNoDataValueAsInt64() instead",
    5308             :                  static_cast<GIntBig>(nVal));
    5309             :     }
    5310           2 :     return dfVal;
    5311             : }
    5312             : 
    5313           2 : double GDALGetNoDataValueCastToDouble(uint64_t nVal)
    5314             : {
    5315           2 :     const double dfVal = static_cast<double>(nVal);
    5316           2 :     if (static_cast<uint64_t>(dfVal) != nVal)
    5317             :     {
    5318           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    5319             :                  "GetNoDataValue() returns an approximate value of the "
    5320             :                  "true nodata value = " CPL_FRMT_GUIB ". Use "
    5321             :                  "GetNoDataValueAsUInt64() instead",
    5322             :                  static_cast<GUIntBig>(nVal));
    5323             :     }
    5324           2 :     return dfVal;
    5325             : }
    5326             : 
    5327             : /************************************************************************/
    5328             : /*                GDALGetCompressionFormatForJPEG()                     */
    5329             : /************************************************************************/
    5330             : 
    5331             : //! @cond Doxygen_Suppress
    5332          23 : std::string GDALGetCompressionFormatForJPEG(VSILFILE *fp)
    5333             : {
    5334          23 :     std::string osRet;
    5335          23 :     const auto nSavedPos = VSIFTellL(fp);
    5336             :     GByte abyMarkerHeader[4];
    5337          23 :     if (VSIFSeekL(fp, 0, SEEK_SET) == 0 &&
    5338          23 :         VSIFReadL(abyMarkerHeader, 2, 1, fp) == 1 &&
    5339          46 :         abyMarkerHeader[0] == 0xFF && abyMarkerHeader[1] == 0xD8)
    5340             :     {
    5341          23 :         osRet = "JPEG";
    5342          23 :         bool bHasAPP14Adobe = false;
    5343          23 :         GByte abyAPP14AdobeMarkerData[14 - 2] = {0};
    5344          23 :         int nNumComponents = 0;
    5345             :         while (true)
    5346             :         {
    5347         171 :             const auto nCurPos = VSIFTellL(fp);
    5348         171 :             if (VSIFReadL(abyMarkerHeader, 4, 1, fp) != 1)
    5349           0 :                 break;
    5350         171 :             if (abyMarkerHeader[0] != 0xFF)
    5351           0 :                 break;
    5352         171 :             const GByte markerType = abyMarkerHeader[1];
    5353         171 :             const size_t nMarkerSize =
    5354         171 :                 abyMarkerHeader[2] * 256 + abyMarkerHeader[3];
    5355         171 :             if (nMarkerSize < 2)
    5356           0 :                 break;
    5357         171 :             if (markerType >= 0xC0 && markerType <= 0xCF &&
    5358          23 :                 markerType != 0xC4 && markerType != 0xC8 && markerType != 0xCC)
    5359             :             {
    5360          23 :                 switch (markerType)
    5361             :                 {
    5362          21 :                     case 0xC0:
    5363          21 :                         osRet += ";frame_type=SOF0_baseline";
    5364          21 :                         break;
    5365           2 :                     case 0xC1:
    5366           2 :                         osRet += ";frame_type=SOF1_extended_sequential";
    5367           2 :                         break;
    5368           0 :                     case 0xC2:
    5369           0 :                         osRet += ";frame_type=SOF2_progressive_huffman";
    5370           0 :                         break;
    5371           0 :                     case 0xC3:
    5372             :                         osRet += ";frame_type=SOF3_lossless_huffman;libjpeg_"
    5373           0 :                                  "supported=no";
    5374           0 :                         break;
    5375           0 :                     case 0xC5:
    5376             :                         osRet += ";frame_type="
    5377             :                                  "SOF5_differential_sequential_huffman;"
    5378           0 :                                  "libjpeg_supported=no";
    5379           0 :                         break;
    5380           0 :                     case 0xC6:
    5381             :                         osRet += ";frame_type=SOF6_differential_progressive_"
    5382           0 :                                  "huffman;libjpeg_supported=no";
    5383           0 :                         break;
    5384           0 :                     case 0xC7:
    5385             :                         osRet += ";frame_type="
    5386             :                                  "SOF7_differential_lossless_huffman;"
    5387           0 :                                  "libjpeg_supported=no";
    5388           0 :                         break;
    5389           0 :                     case 0xC9:
    5390             :                         osRet += ";frame_type="
    5391           0 :                                  "SOF9_extended_sequential_arithmetic";
    5392           0 :                         break;
    5393           0 :                     case 0xCA:
    5394           0 :                         osRet += ";frame_type=SOF10_progressive_arithmetic";
    5395           0 :                         break;
    5396           0 :                     case 0xCB:
    5397             :                         osRet += ";frame_type="
    5398             :                                  "SOF11_lossless_arithmetic;libjpeg_"
    5399           0 :                                  "supported=no";
    5400           0 :                         break;
    5401           0 :                     case 0xCD:
    5402             :                         osRet += ";frame_type=SOF13_differential_sequential_"
    5403           0 :                                  "arithmetic;libjpeg_supported=no";
    5404           0 :                         break;
    5405           0 :                     case 0xCE:
    5406             :                         osRet += ";frame_type=SOF14_differential_progressive_"
    5407           0 :                                  "arithmetic;libjpeg_supported=no";
    5408           0 :                         break;
    5409           0 :                     case 0xCF:
    5410             :                         osRet += ";frame_type=SOF15_differential_lossless_"
    5411           0 :                                  "arithmetic;libjpeg_supported=no";
    5412           0 :                         break;
    5413           0 :                     default:
    5414           0 :                         break;
    5415             :                 }
    5416             :                 GByte abySegmentBegin[6];
    5417          23 :                 if (VSIFReadL(abySegmentBegin, sizeof(abySegmentBegin), 1,
    5418          23 :                               fp) != 1)
    5419           0 :                     break;
    5420          23 :                 osRet += ";bit_depth=";
    5421          23 :                 osRet += CPLSPrintf("%d", abySegmentBegin[0]);
    5422          23 :                 nNumComponents = abySegmentBegin[5];
    5423          23 :                 osRet += ";num_components=";
    5424          23 :                 osRet += CPLSPrintf("%d", nNumComponents);
    5425          23 :                 if (nNumComponents == 3)
    5426             :                 {
    5427             :                     GByte abySegmentNext[3 * 3];
    5428          13 :                     if (VSIFReadL(abySegmentNext, sizeof(abySegmentNext), 1,
    5429          13 :                                   fp) != 1)
    5430           0 :                         break;
    5431          13 :                     if (abySegmentNext[0] == 1 && abySegmentNext[1] == 0x11 &&
    5432           0 :                         abySegmentNext[3] == 2 && abySegmentNext[4] == 0x11 &&
    5433           0 :                         abySegmentNext[6] == 3 && abySegmentNext[7] == 0x11)
    5434             :                     {
    5435             :                         // no subsampling
    5436           0 :                         osRet += ";subsampling=4:4:4";
    5437             :                     }
    5438          13 :                     else if (abySegmentNext[0] == 1 &&
    5439          11 :                              abySegmentNext[1] == 0x22 &&
    5440          11 :                              abySegmentNext[3] == 2 &&
    5441          11 :                              abySegmentNext[4] == 0x11 &&
    5442          11 :                              abySegmentNext[6] == 3 &&
    5443          11 :                              abySegmentNext[7] == 0x11)
    5444             :                     {
    5445             :                         // classic subsampling
    5446          11 :                         osRet += ";subsampling=4:2:0";
    5447             :                     }
    5448           2 :                     else if (abySegmentNext[0] == 1 &&
    5449           0 :                              abySegmentNext[1] == 0x21 &&
    5450           0 :                              abySegmentNext[3] == 2 &&
    5451           0 :                              abySegmentNext[4] == 0x11 &&
    5452           0 :                              abySegmentNext[6] == 3 &&
    5453           0 :                              abySegmentNext[7] == 0x11)
    5454             :                     {
    5455           0 :                         osRet += ";subsampling=4:2:2";
    5456             :                     }
    5457          23 :                 }
    5458             :             }
    5459         148 :             else if (markerType == 0xEE && nMarkerSize == 14)
    5460             :             {
    5461           1 :                 if (VSIFReadL(abyAPP14AdobeMarkerData,
    5462           2 :                               sizeof(abyAPP14AdobeMarkerData), 1, fp) == 1 &&
    5463           1 :                     memcmp(abyAPP14AdobeMarkerData, "Adobe", strlen("Adobe")) ==
    5464             :                         0)
    5465             :                 {
    5466           1 :                     bHasAPP14Adobe = true;
    5467             :                 }
    5468             :             }
    5469         147 :             else if (markerType == 0xDA)
    5470             :             {
    5471             :                 // Start of scan
    5472          23 :                 break;
    5473             :             }
    5474         148 :             VSIFSeekL(fp, nCurPos + nMarkerSize + 2, SEEK_SET);
    5475         148 :         }
    5476          46 :         std::string osColorspace;
    5477          23 :         if (bHasAPP14Adobe)
    5478             :         {
    5479           1 :             if (abyAPP14AdobeMarkerData[11] == 0)
    5480             :             {
    5481           1 :                 if (nNumComponents == 3)
    5482           0 :                     osColorspace = "RGB";
    5483           1 :                 else if (nNumComponents == 4)
    5484           1 :                     osColorspace = "CMYK";
    5485             :             }
    5486           0 :             else if (abyAPP14AdobeMarkerData[11] == 1)
    5487             :             {
    5488           0 :                 osColorspace = "YCbCr";
    5489             :             }
    5490           0 :             else if (abyAPP14AdobeMarkerData[11] == 2)
    5491             :             {
    5492           0 :                 osColorspace = "YCCK";
    5493             :             }
    5494             :         }
    5495             :         else
    5496             :         {
    5497          22 :             if (nNumComponents == 3)
    5498          13 :                 osColorspace = "YCbCr";
    5499           9 :             else if (nNumComponents == 4)
    5500           1 :                 osColorspace = "CMYK";
    5501             :         }
    5502          23 :         osRet += ";colorspace=";
    5503          23 :         if (!osColorspace.empty())
    5504          15 :             osRet += osColorspace;
    5505             :         else
    5506           8 :             osRet += "unknown";
    5507             :     }
    5508          23 :     if (VSIFSeekL(fp, nSavedPos, SEEK_SET) != 0)
    5509             :     {
    5510           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5511             :                  "VSIFSeekL(fp, nSavedPos, SEEK_SET) failed");
    5512             :     }
    5513          46 :     return osRet;
    5514             : }
    5515             : 
    5516          16 : std::string GDALGetCompressionFormatForJPEG(const void *pBuffer,
    5517             :                                             size_t nBufferSize)
    5518             : {
    5519          16 :     VSILFILE *fp = VSIFileFromMemBuffer(
    5520             :         nullptr, static_cast<GByte *>(const_cast<void *>(pBuffer)), nBufferSize,
    5521             :         false);
    5522          16 :     std::string osRet = GDALGetCompressionFormatForJPEG(fp);
    5523          16 :     VSIFCloseL(fp);
    5524          16 :     return osRet;
    5525             : }
    5526             : 
    5527             : //! @endcond
    5528             : 
    5529             : /************************************************************************/
    5530             : /*                      GDALGetNoDataReplacementValue()                 */
    5531             : /************************************************************************/
    5532             : 
    5533             : /**
    5534             :  * \brief Returns a replacement value for a nodata value or 0 if dfNoDataValue
    5535             :  *        is out of range for the specified data type (dt).
    5536             :  *        For UInt64 and Int64 data type this function cannot reliably trusted
    5537             :  *        because their nodata values might not always be representable exactly
    5538             :  *        as a double, in particular the maximum absolute value for those types
    5539             :  *        is 2^53.
    5540             :  *
    5541             :  * The replacement value is a value that can be used in a computation
    5542             :  * whose result would match by accident the nodata value, whereas it is
    5543             :  * meant to be valid. For example, for a dataset with a nodata value of 0,
    5544             :  * when averaging -1 and 1, one would get normally a value of 0. The
    5545             :  * replacement nodata value can then be substituted to that 0 value to still
    5546             :  * get a valid value, as close as practical to the true value, while being
    5547             :  * different from the nodata value.
    5548             :  *
    5549             :  * @param dt Data type
    5550             :  * @param dfNoDataValue The no data value
    5551             : 
    5552             :  * @since GDAL 3.9
    5553             :  */
    5554         269 : double GDALGetNoDataReplacementValue(GDALDataType dt, double dfNoDataValue)
    5555             : {
    5556             : 
    5557             :     // The logic here is to check if the value is out of range for the
    5558             :     // specified data type and return a replacement value if it is, return
    5559             :     // 0 otherwise.
    5560         269 :     double dfReplacementVal = dfNoDataValue;
    5561         269 :     if (dt == GDT_Byte)
    5562             :     {
    5563          83 :         if (GDALClampDoubleValue(dfNoDataValue,
    5564          83 :                                  cpl::NumericLimits<uint8_t>::lowest(),
    5565          83 :                                  cpl::NumericLimits<uint8_t>::max()))
    5566             :         {
    5567           2 :             return 0;
    5568             :         }
    5569          81 :         if (dfNoDataValue == cpl::NumericLimits<unsigned char>::max())
    5570           3 :             dfReplacementVal = cpl::NumericLimits<unsigned char>::max() - 1;
    5571             :         else
    5572          78 :             dfReplacementVal = dfNoDataValue + 1;
    5573             :     }
    5574         186 :     else if (dt == GDT_Int8)
    5575             :     {
    5576           5 :         if (GDALClampDoubleValue(dfNoDataValue,
    5577           5 :                                  cpl::NumericLimits<int8_t>::lowest(),
    5578           5 :                                  cpl::NumericLimits<int8_t>::max()))
    5579             :         {
    5580           2 :             return 0;
    5581             :         }
    5582           3 :         if (dfNoDataValue == cpl::NumericLimits<GInt8>::max())
    5583           1 :             dfReplacementVal = cpl::NumericLimits<GInt8>::max() - 1;
    5584             :         else
    5585           2 :             dfReplacementVal = dfNoDataValue + 1;
    5586             :     }
    5587         181 :     else if (dt == GDT_UInt16)
    5588             :     {
    5589           6 :         if (GDALClampDoubleValue(dfNoDataValue,
    5590           6 :                                  cpl::NumericLimits<uint16_t>::lowest(),
    5591           6 :                                  cpl::NumericLimits<uint16_t>::max()))
    5592             :         {
    5593           2 :             return 0;
    5594             :         }
    5595           4 :         if (dfNoDataValue == cpl::NumericLimits<GUInt16>::max())
    5596           1 :             dfReplacementVal = cpl::NumericLimits<GUInt16>::max() - 1;
    5597             :         else
    5598           3 :             dfReplacementVal = dfNoDataValue + 1;
    5599             :     }
    5600         175 :     else if (dt == GDT_Int16)
    5601             :     {
    5602          19 :         if (GDALClampDoubleValue(dfNoDataValue,
    5603          19 :                                  cpl::NumericLimits<int16_t>::lowest(),
    5604          19 :                                  cpl::NumericLimits<int16_t>::max()))
    5605             :         {
    5606           2 :             return 0;
    5607             :         }
    5608          17 :         if (dfNoDataValue == cpl::NumericLimits<GInt16>::max())
    5609           1 :             dfReplacementVal = cpl::NumericLimits<GInt16>::max() - 1;
    5610             :         else
    5611          16 :             dfReplacementVal = dfNoDataValue + 1;
    5612             :     }
    5613         156 :     else if (dt == GDT_UInt32)
    5614             :     {
    5615           5 :         if (GDALClampDoubleValue(dfNoDataValue,
    5616             :                                  cpl::NumericLimits<uint32_t>::lowest(),
    5617             :                                  cpl::NumericLimits<uint32_t>::max()))
    5618             :         {
    5619           2 :             return 0;
    5620             :         }
    5621           3 :         if (dfNoDataValue == cpl::NumericLimits<GUInt32>::max())
    5622           1 :             dfReplacementVal = cpl::NumericLimits<GUInt32>::max() - 1;
    5623             :         else
    5624           2 :             dfReplacementVal = dfNoDataValue + 1;
    5625             :     }
    5626         151 :     else if (dt == GDT_Int32)
    5627             :     {
    5628           7 :         if (GDALClampDoubleValue(dfNoDataValue,
    5629             :                                  cpl::NumericLimits<int32_t>::lowest(),
    5630             :                                  cpl::NumericLimits<int32_t>::max()))
    5631             :         {
    5632           2 :             return 0;
    5633             :         }
    5634           5 :         if (dfNoDataValue == cpl::NumericLimits<int32_t>::max())
    5635           1 :             dfReplacementVal = cpl::NumericLimits<int32_t>::max() - 1;
    5636             :         else
    5637           4 :             dfReplacementVal = dfNoDataValue + 1;
    5638             :     }
    5639         144 :     else if (dt == GDT_UInt64)
    5640             :     {
    5641             :         // Implicit conversion from 'unsigned long' to 'double' changes value from 18446744073709551615 to 18446744073709551616
    5642             :         // so we take the next lower value representable as a double 18446744073709549567
    5643             :         static const double dfMaxUInt64Value{
    5644             :             std::nextafter(
    5645             :                 static_cast<double>(cpl::NumericLimits<uint64_t>::max()), 0) -
    5646             :             1};
    5647             : 
    5648           5 :         if (GDALClampDoubleValue(dfNoDataValue,
    5649             :                                  cpl::NumericLimits<uint64_t>::lowest(),
    5650             :                                  cpl::NumericLimits<uint64_t>::max()))
    5651             :         {
    5652           2 :             return 0;
    5653             :         }
    5654             : 
    5655           3 :         if (dfNoDataValue >=
    5656           3 :             static_cast<double>(cpl::NumericLimits<uint64_t>::max()))
    5657           1 :             dfReplacementVal = dfMaxUInt64Value;
    5658             :         else
    5659           2 :             dfReplacementVal = dfNoDataValue + 1;
    5660             :     }
    5661         139 :     else if (dt == GDT_Int64)
    5662             :     {
    5663             :         // Implicit conversion from 'long' to 'double' changes value from 9223372036854775807 to 9223372036854775808
    5664             :         // so we take the next lower value representable as a double 9223372036854774784
    5665             :         static const double dfMaxInt64Value{
    5666             :             std::nextafter(
    5667             :                 static_cast<double>(cpl::NumericLimits<int64_t>::max()), 0) -
    5668             :             1};
    5669             : 
    5670           5 :         if (GDALClampDoubleValue(dfNoDataValue,
    5671             :                                  cpl::NumericLimits<int64_t>::lowest(),
    5672             :                                  cpl::NumericLimits<int64_t>::max()))
    5673             :         {
    5674           2 :             return 0;
    5675             :         }
    5676             : 
    5677           3 :         if (dfNoDataValue >=
    5678           3 :             static_cast<double>(cpl::NumericLimits<int64_t>::max()))
    5679           1 :             dfReplacementVal = dfMaxInt64Value;
    5680             :         else
    5681           2 :             dfReplacementVal = dfNoDataValue + 1;
    5682             :     }
    5683         134 :     else if (dt == GDT_Float16)
    5684             :     {
    5685             : 
    5686           8 :         if (GDALClampDoubleValue(dfNoDataValue,
    5687             :                                  cpl::NumericLimits<GFloat16>::lowest(),
    5688             :                                  cpl::NumericLimits<GFloat16>::max()))
    5689             :         {
    5690           4 :             return 0;
    5691             :         }
    5692             : 
    5693           4 :         if (dfNoDataValue == cpl::NumericLimits<GFloat16>::max())
    5694             :         {
    5695             :             using std::nextafter;
    5696             :             dfReplacementVal =
    5697           1 :                 nextafter(static_cast<GFloat16>(dfNoDataValue), GFloat16(0.0f));
    5698             :         }
    5699             :         else
    5700             :         {
    5701             :             using std::nextafter;
    5702           0 :             dfReplacementVal = nextafter(static_cast<GFloat16>(dfNoDataValue),
    5703           3 :                                          cpl::NumericLimits<GFloat16>::max());
    5704             :         }
    5705             :     }
    5706         126 :     else if (dt == GDT_Float32)
    5707             :     {
    5708             : 
    5709          33 :         if (GDALClampDoubleValue(dfNoDataValue,
    5710             :                                  cpl::NumericLimits<float>::lowest(),
    5711             :                                  cpl::NumericLimits<float>::max()))
    5712             :         {
    5713           4 :             return 0;
    5714             :         }
    5715             : 
    5716          29 :         if (dfNoDataValue == cpl::NumericLimits<float>::max())
    5717             :         {
    5718           1 :             dfReplacementVal =
    5719           1 :                 std::nextafter(static_cast<float>(dfNoDataValue), 0.0f);
    5720             :         }
    5721             :         else
    5722             :         {
    5723          28 :             dfReplacementVal = std::nextafter(static_cast<float>(dfNoDataValue),
    5724             :                                               cpl::NumericLimits<float>::max());
    5725             :         }
    5726             :     }
    5727          93 :     else if (dt == GDT_Float64)
    5728             :     {
    5729          93 :         if (GDALClampDoubleValue(dfNoDataValue,
    5730             :                                  cpl::NumericLimits<double>::lowest(),
    5731             :                                  cpl::NumericLimits<double>::max()))
    5732             :         {
    5733           2 :             return 0;
    5734             :         }
    5735             : 
    5736          91 :         if (dfNoDataValue == cpl::NumericLimits<double>::max())
    5737             :         {
    5738           2 :             dfReplacementVal = std::nextafter(dfNoDataValue, 0.0);
    5739             :         }
    5740             :         else
    5741             :         {
    5742          89 :             dfReplacementVal = std::nextafter(
    5743             :                 dfNoDataValue, cpl::NumericLimits<double>::max());
    5744             :         }
    5745             :     }
    5746             : 
    5747         243 :     return dfReplacementVal;
    5748             : }
    5749             : 
    5750             : /************************************************************************/
    5751             : /*                        GDALGetCacheDirectory()                       */
    5752             : /************************************************************************/
    5753             : 
    5754             : /** Return the root path of the GDAL cache.
    5755             :  *
    5756             :  * If the GDAL_CACHE_DIRECTORY configuration option is set, its value will
    5757             :  * be returned.
    5758             :  * Otherwise if the XDG_CACHE_HOME environment variable is set,
    5759             :  * ${XDG_CACHE_HOME}/.gdal will be returned.
    5760             :  * Otherwise ${HOME}/.gdal on Unix or$ ${USERPROFILE}/.gdal on Windows will
    5761             :  * be returned.
    5762             :  * Otherwise ${CPL_TMPDIR|TMPDIR|TEMP}/.gdal_${USERNAME|USER} will be returned.
    5763             :  * Otherwise empty string will be returned.
    5764             :  *
    5765             :  * @since GDAL 3.11
    5766             :  */
    5767         315 : std::string GDALGetCacheDirectory()
    5768             : {
    5769         315 :     if (const char *pszGDAL_CACHE_DIRECTORY =
    5770         315 :             CPLGetConfigOption("GDAL_CACHE_DIRECTORY", nullptr))
    5771             :     {
    5772           0 :         return pszGDAL_CACHE_DIRECTORY;
    5773             :     }
    5774             : 
    5775         315 :     if (const char *pszXDG_CACHE_HOME =
    5776         315 :             CPLGetConfigOption("XDG_CACHE_HOME", nullptr))
    5777             :     {
    5778           0 :         return CPLFormFilenameSafe(pszXDG_CACHE_HOME, "gdal", nullptr);
    5779             :     }
    5780             : 
    5781             : #ifdef _WIN32
    5782             :     const char *pszHome = CPLGetConfigOption("USERPROFILE", nullptr);
    5783             : #else
    5784         315 :     const char *pszHome = CPLGetConfigOption("HOME", nullptr);
    5785             : #endif
    5786         315 :     if (pszHome != nullptr)
    5787             :     {
    5788         315 :         return CPLFormFilenameSafe(pszHome, ".gdal", nullptr);
    5789             :     }
    5790             :     else
    5791             :     {
    5792           0 :         const char *pszDir = CPLGetConfigOption("CPL_TMPDIR", nullptr);
    5793             : 
    5794           0 :         if (pszDir == nullptr)
    5795           0 :             pszDir = CPLGetConfigOption("TMPDIR", nullptr);
    5796             : 
    5797           0 :         if (pszDir == nullptr)
    5798           0 :             pszDir = CPLGetConfigOption("TEMP", nullptr);
    5799             : 
    5800           0 :         const char *pszUsername = CPLGetConfigOption("USERNAME", nullptr);
    5801           0 :         if (pszUsername == nullptr)
    5802           0 :             pszUsername = CPLGetConfigOption("USER", nullptr);
    5803             : 
    5804           0 :         if (pszDir != nullptr && pszUsername != nullptr)
    5805             :         {
    5806             :             return CPLFormFilenameSafe(
    5807           0 :                 pszDir, CPLSPrintf(".gdal_%s", pszUsername), nullptr);
    5808             :         }
    5809             :     }
    5810           0 :     return std::string();
    5811             : }
    5812             : 
    5813             : /************************************************************************/
    5814             : /*                      GDALDoesFileOrDatasetExist()                    */
    5815             : /************************************************************************/
    5816             : 
    5817             : /** Return whether a file already exists.
    5818             :  */
    5819         670 : bool GDALDoesFileOrDatasetExist(const char *pszName, const char **ppszType,
    5820             :                                 GDALDriver **ppDriver)
    5821             : {
    5822             :     {
    5823         670 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
    5824         670 :         GDALDriverH hDriver = GDALIdentifyDriver(pszName, nullptr);
    5825         670 :         if (hDriver)
    5826             :         {
    5827          58 :             if (ppszType)
    5828          58 :                 *ppszType = "Dataset";
    5829          58 :             if (ppDriver)
    5830          57 :                 *ppDriver = GDALDriver::FromHandle(hDriver);
    5831          58 :             return true;
    5832             :         }
    5833             :     }
    5834             : 
    5835             :     VSIStatBufL sStat;
    5836         612 :     if (VSIStatL(pszName, &sStat) == 0)
    5837             :     {
    5838           4 :         if (ppszType)
    5839           4 :             *ppszType = VSI_ISDIR(sStat.st_mode) ? "Directory" : "File";
    5840           4 :         return true;
    5841             :     }
    5842             : 
    5843         608 :     return false;
    5844             : }
    5845             : 
    5846             : /************************************************************************/
    5847             : /*                        GDALRescaleGeoTransform()                     */
    5848             : /************************************************************************/
    5849             : 
    5850             : /** Rescale a geotransform by multiplying its scale and rotation terms by
    5851             :  * the provided ratios.
    5852             :  *
    5853             :  * This is typically used to compute the geotransform matrix of an overview
    5854             :  * dataset from the full resolution dataset, where the ratios are the size
    5855             :  * of the full resolution dataset divided by the size of the overview.
    5856             :  */
    5857        1745 : void GDALRescaleGeoTransform(double adfGeoTransform[6], double dfXRatio,
    5858             :                              double dfYRatio)
    5859             : {
    5860        1745 :     adfGeoTransform[1] *= dfXRatio;
    5861        1745 :     adfGeoTransform[2] *= dfYRatio;
    5862        1745 :     adfGeoTransform[4] *= dfXRatio;
    5863        1745 :     adfGeoTransform[5] *= dfYRatio;
    5864        1745 : }

Generated by: LCOV version 1.14