LCOV - code coverage report
Current view: top level - frmts/nitf - nitfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2431 3012 80.7 %
Date: 2024-11-21 22:18:42 Functions: 55 56 98.2 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  NITF Read/Write Translator
       4             :  * Purpose:  NITFDataset and driver related implementations.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2002, Frank Warmerdam
       9             :  * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * Portions Copyright (c) Her majesty the Queen in right of Canada as
      12             :  * represented by the Minister of National Defence, 2006, 2020
      13             :  *
      14             :  * SPDX-License-Identifier: MIT
      15             :  ****************************************************************************/
      16             : 
      17             : #include "cpl_port.h"
      18             : #include "nitfdataset.h"
      19             : #include "nitfdrivercore.h"
      20             : 
      21             : #include "gdal_mdreader.h"
      22             : 
      23             : #include <cmath>
      24             : #include <cstdio>
      25             : #include <cstdlib>
      26             : #include <cstring>
      27             : #if HAVE_FCNTL_H
      28             : #include <fcntl.h>
      29             : #endif
      30             : #include <algorithm>
      31             : #include <memory>
      32             : #include <string>
      33             : #include <vector>
      34             : 
      35             : #include "cpl_conv.h"
      36             : #include "cpl_csv.h"
      37             : #include "cpl_error.h"
      38             : #include "cpl_minixml.h"
      39             : #include "cpl_progress.h"
      40             : #include "cpl_string.h"
      41             : #include "cpl_vsi.h"
      42             : #include "gdal.h"
      43             : #include "gdal_frmts.h"
      44             : #include "gdal_priv.h"
      45             : #include "ogr_api.h"
      46             : #include "ogr_core.h"
      47             : #include "ogr_srs_api.h"
      48             : 
      49             : #ifdef EMBED_RESOURCE_FILES
      50             : #include "embedded_resources.h"
      51             : #endif
      52             : 
      53             : static bool NITFPatchImageLength(const char *pszFilename, int nIMIndex,
      54             :                                  GUIntBig nImageOffset, GIntBig nPixelCount,
      55             :                                  const char *pszIC, vsi_l_offset nICOffset,
      56             :                                  CSLConstList papszCreationOptions);
      57             : static bool NITFWriteExtraSegments(const char *pszFilename,
      58             :                                    CSLConstList papszCgmMD,
      59             :                                    CSLConstList papszTextMD,
      60             :                                    CSLConstList papszOptions);
      61             : 
      62             : #ifdef JPEG_SUPPORTED
      63             : static bool NITFWriteJPEGImage(GDALDataset *, VSILFILE *, vsi_l_offset, char **,
      64             :                                GDALProgressFunc pfnProgress,
      65             :                                void *pProgressData);
      66             : #endif
      67             : 
      68             : static void SetBandMetadata(NITFImage *psImage, GDALRasterBand *poBand,
      69             :                             int nBand, bool bReportISUBCAT);
      70             : 
      71             : /************************************************************************/
      72             : /* ==================================================================== */
      73             : /*                             NITFDataset                              */
      74             : /* ==================================================================== */
      75             : /************************************************************************/
      76             : 
      77             : /************************************************************************/
      78             : /*                            NITFDataset()                             */
      79             : /************************************************************************/
      80             : 
      81         755 : NITFDataset::NITFDataset()
      82             :     : psFile(nullptr), psImage(nullptr), poJ2KDataset(nullptr),
      83             :       bJP2Writing(FALSE), poJPEGDataset(nullptr), bGotGeoTransform(FALSE),
      84             :       nGCPCount(0), pasGCPList(nullptr), panJPEGBlockOffset(nullptr),
      85             :       pabyJPEGBlock(nullptr), nQLevel(0), nIMIndex(0),
      86             :       papszTextMDToWrite(nullptr), papszCgmMDToWrite(nullptr),
      87         755 :       bInLoadXML(FALSE), bExposeUnderlyingJPEGDatasetOverviews(FALSE)
      88             : {
      89         755 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
      90         755 :     m_oGCPSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
      91             : 
      92         755 :     adfGeoTransform[0] = 0.0;
      93         755 :     adfGeoTransform[1] = 1.0;
      94         755 :     adfGeoTransform[2] = 0.0;
      95         755 :     adfGeoTransform[3] = 0.0;
      96         755 :     adfGeoTransform[4] = 0.0;
      97         755 :     adfGeoTransform[5] = 1.0;
      98             : 
      99         755 :     poDriver = reinterpret_cast<GDALDriver *>(GDALGetDriverByName("NITF"));
     100         755 : }
     101             : 
     102             : /************************************************************************/
     103             : /*                            ~NITFDataset()                            */
     104             : /************************************************************************/
     105             : 
     106        1510 : NITFDataset::~NITFDataset()
     107             : 
     108             : {
     109         755 :     NITFDataset::CloseDependentDatasets();
     110             : 
     111             :     /* -------------------------------------------------------------------- */
     112             :     /*      Free datastructures.                                            */
     113             :     /* -------------------------------------------------------------------- */
     114             : 
     115         755 :     GDALDeinitGCPs(nGCPCount, pasGCPList);
     116         755 :     CPLFree(pasGCPList);
     117             : 
     118         755 :     CPLFree(panJPEGBlockOffset);
     119         755 :     CPLFree(pabyJPEGBlock);
     120        1510 : }
     121             : 
     122             : /************************************************************************/
     123             : /*                        CloseDependentDatasets()                      */
     124             : /************************************************************************/
     125             : 
     126         755 : int NITFDataset::CloseDependentDatasets()
     127             : {
     128         755 :     NITFDataset::FlushCache(true);
     129             : 
     130         755 :     int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();
     131             : 
     132             :     /* -------------------------------------------------------------------- */
     133             :     /*      If we have been writing to a JPEG2000 file, check if the        */
     134             :     /*      color interpretations were set.  If so, apply the settings      */
     135             :     /*      to the NITF file.                                               */
     136             :     /* -------------------------------------------------------------------- */
     137         755 :     if (poJ2KDataset != nullptr && bJP2Writing)
     138             :     {
     139           4 :         for (int i = 0; i < nBands && papoBands != nullptr; i++)
     140             :         {
     141           3 :             if (papoBands[i]->GetColorInterpretation() != GCI_Undefined)
     142           3 :                 NITFSetColorInterpretation(
     143           3 :                     psImage, i + 1, papoBands[i]->GetColorInterpretation());
     144             :         }
     145             :     }
     146             : 
     147             :     /* -------------------------------------------------------------------- */
     148             :     /*      Close the underlying NITF file.                                 */
     149             :     /* -------------------------------------------------------------------- */
     150         755 :     if (psFile != nullptr)
     151             :     {
     152         750 :         NITFClose(psFile);
     153         750 :         psFile = nullptr;
     154             :     }
     155             : 
     156             :     /* -------------------------------------------------------------------- */
     157             :     /*      If we have a jpeg2000 output file, make sure it gets closed     */
     158             :     /*      and flushed out.                                                */
     159             :     /* -------------------------------------------------------------------- */
     160         755 :     if (poJ2KDataset != nullptr)
     161             :     {
     162          37 :         GDALClose((GDALDatasetH)poJ2KDataset);
     163          37 :         poJ2KDataset = nullptr;
     164          37 :         bHasDroppedRef = TRUE;
     165             :     }
     166             : 
     167             :     /* -------------------------------------------------------------------- */
     168             :     /*      Update file length, and COMRAT for JPEG2000 files we are        */
     169             :     /*      writing to.                                                     */
     170             :     /* -------------------------------------------------------------------- */
     171         755 :     if (bJP2Writing)
     172             :     {
     173           1 :         GIntBig nPixelCount = nRasterXSize * ((GIntBig)nRasterYSize) * nBands;
     174             : 
     175           1 :         CPL_IGNORE_RET_VAL(NITFPatchImageLength(GetDescription(), m_nIMIndex,
     176             :                                                 m_nImageOffset, nPixelCount,
     177             :                                                 "C8", m_nICOffset, nullptr));
     178             :     }
     179             : 
     180         755 :     bJP2Writing = FALSE;
     181             : 
     182             :     /* -------------------------------------------------------------------- */
     183             :     /*      If we have a jpeg output file, make sure it gets closed         */
     184             :     /*      and flushed out.                                                */
     185             :     /* -------------------------------------------------------------------- */
     186         755 :     if (poJPEGDataset != nullptr)
     187             :     {
     188          22 :         GDALClose((GDALDatasetH)poJPEGDataset);
     189          22 :         poJPEGDataset = nullptr;
     190          22 :         bHasDroppedRef = TRUE;
     191             :     }
     192             : 
     193             :     /* -------------------------------------------------------------------- */
     194             :     /*      If the dataset was opened by Create(), we may need to write     */
     195             :     /*      the CGM and TEXT segments                                       */
     196             :     /* -------------------------------------------------------------------- */
     197         755 :     if (m_nIMIndex + 1 == m_nImageCount)
     198             :     {
     199         158 :         CPL_IGNORE_RET_VAL(NITFWriteExtraSegments(
     200         158 :             GetDescription(), papszCgmMDToWrite, papszTextMDToWrite,
     201         158 :             aosCreationOptions.List()));
     202             :     }
     203             : 
     204         755 :     CSLDestroy(papszTextMDToWrite);
     205         755 :     papszTextMDToWrite = nullptr;
     206         755 :     CSLDestroy(papszCgmMDToWrite);
     207         755 :     papszCgmMDToWrite = nullptr;
     208             : 
     209             :     /* -------------------------------------------------------------------- */
     210             :     /*      Destroy the raster bands if they exist.                         */
     211             :     /* We must do it now since the rasterbands can be NITFWrapperRasterBand */
     212             :     /* that derive from the GDALProxyRasterBand object, which keeps         */
     213             :     /* a reference on the JPEG/JP2K dataset, so any later call to           */
     214             :     /* FlushCache() would result in FlushCache() being called on a          */
     215             :     /* already destroyed object                                             */
     216             :     /* -------------------------------------------------------------------- */
     217      211802 :     for (int iBand = 0; iBand < nBands; iBand++)
     218             :     {
     219      211047 :         delete papoBands[iBand];
     220             :     }
     221         755 :     nBands = 0;
     222             : 
     223         755 :     return bHasDroppedRef;
     224             : }
     225             : 
     226             : /************************************************************************/
     227             : /*                             FlushCache()                             */
     228             : /************************************************************************/
     229             : 
     230         766 : CPLErr NITFDataset::FlushCache(bool bAtClosing)
     231             : 
     232             : {
     233             :     // If the JPEG/JP2K dataset has dirty pam info, then we should consider
     234             :     // ourselves to as well.
     235        1554 :     if (poJPEGDataset != nullptr &&
     236         788 :         (poJPEGDataset->GetMOFlags() & GMO_PAM_CLASS) &&
     237          22 :         (reinterpret_cast<GDALPamDataset *>(poJPEGDataset)->GetPamFlags() &
     238             :          GPF_DIRTY))
     239           3 :         MarkPamDirty();
     240             : 
     241        1570 :     if (poJ2KDataset != nullptr &&
     242         802 :         (poJ2KDataset->GetMOFlags() & GMO_PAM_CLASS) &&
     243          36 :         (reinterpret_cast<GDALPamDataset *>(poJ2KDataset)->GetPamFlags() &
     244             :          GPF_DIRTY))
     245           2 :         MarkPamDirty();
     246             : 
     247         766 :     CPLErr eErr = CE_None;
     248         766 :     if (poJ2KDataset != nullptr && bJP2Writing)
     249           2 :         eErr = poJ2KDataset->FlushCache(bAtClosing);
     250             : 
     251         766 :     if (GDALPamDataset::FlushCache(bAtClosing) != CE_None)
     252           0 :         eErr = CE_Failure;
     253         766 :     return eErr;
     254             : }
     255             : 
     256             : #ifdef ESRI_BUILD
     257             : 
     258             : /************************************************************************/
     259             : /*                           ExtractEsriMD()                            */
     260             : /*                                                                      */
     261             : /*      Extracts ESRI-specific required meta data from metadata         */
     262             : /*      string list papszStrList.                                       */
     263             : /************************************************************************/
     264             : 
     265             : static char **ExtractEsriMD(char **papszMD)
     266             : {
     267             :     char **papszEsriMD = NULL;
     268             : 
     269             :     if (papszMD)
     270             :     {
     271             :         // These are the current generic ESRI metadata.
     272             :         const char *const pEsriMDAcquisitionDate = "ESRI_MD_ACQUISITION_DATE";
     273             :         const char *const pEsriMDAngleToNorth = "ESRI_MD_ANGLE_TO_NORTH";
     274             :         const char *const pEsriMDCircularError = "ESRI_MD_CE";
     275             :         const char *const pEsriMDDataType = "ESRI_MD_DATA_TYPE";
     276             :         const char *const pEsriMDIsCloudCover = "ESRI_MD_ISCLOUDCOVER";
     277             :         const char *const pEsriMDLinearError = "ESRI_MD_LE";
     278             :         const char *const pEsriMDOffNaDir = "ESRI_MD_OFF_NADIR";
     279             :         const char *const pEsriMDPercentCloudCover =
     280             :             "ESRI_MD_PERCENT_CLOUD_COVER";
     281             :         const char *const pEsriMDProductName = "ESRI_MD_PRODUCT_NAME";
     282             :         const char *const pEsriMDSensorAzimuth = "ESRI_MD_SENSOR_AZIMUTH";
     283             :         const char *const pEsriMDSensorElevation = "ESRI_MD_SENSOR_ELEVATION";
     284             :         const char *const pEsriMDSensorName = "ESRI_MD_SENSOR_NAME";
     285             :         const char *const pEsriMDSunAzimuth = "ESRI_MD_SUN_AZIMUTH";
     286             :         const char *const pEsriMDSunElevation = "ESRI_MD_SUN_ELEVATION";
     287             : 
     288             :         const char *pCCImageSegment = CSLFetchNameValue(papszMD, "NITF_IID1");
     289             :         std::string ccSegment("false");
     290             : 
     291             :         if ((pCCImageSegment != NULL) && (strlen(pCCImageSegment) <= 10))
     292             :         {
     293             :             char szField[11] = {0};
     294             :             strncpy(szField, pCCImageSegment, strlen(pCCImageSegment));
     295             :             szField[strlen(pCCImageSegment)] = '\0';
     296             : 
     297             :             // Trim white off tag.
     298             :             while ((strlen(szField) > 0) &&
     299             :                    (szField[strlen(szField) - 1] == ' '))
     300             :                 szField[strlen(szField) - 1] = '\0';
     301             : 
     302             :             if ((strlen(szField) == 2) && (STARTS_WITH_CI(szField, "CC")))
     303             :                 ccSegment.assign("true");
     304             :         }
     305             : 
     306             :         const char *pAcquisitionDate = CSLFetchNameValue(papszMD, "NITF_FDT");
     307             :         const char *pAngleToNorth =
     308             :             CSLFetchNameValue(papszMD, "NITF_CSEXRA_ANGLE_TO_NORTH");
     309             :         const char *pCircularError = CSLFetchNameValue(
     310             :             papszMD, "NITF_CSEXRA_CIRCL_ERR");  // Unit in feet.
     311             :         const char *pLinearError = CSLFetchNameValue(
     312             :             papszMD, "NITF_CSEXRA_LINEAR_ERR");  // Unit in feet.
     313             :         const char *pPercentCloudCover =
     314             :             CSLFetchNameValue(papszMD, "NITF_PIAIMC_CLOUDCVR");
     315             :         const char *pProductName =
     316             :             CSLFetchNameValue(papszMD, "NITF_CSDIDA_PRODUCT_ID");
     317             :         const char *pSensorName =
     318             :             CSLFetchNameValue(papszMD, "NITF_PIAIMC_SENSNAME");
     319             :         const char *pSunAzimuth =
     320             :             CSLFetchNameValue(papszMD, "NITF_CSEXRA_SUN_AZIMUTH");
     321             :         const char *pSunElevation =
     322             :             CSLFetchNameValue(papszMD, "NITF_CSEXRA_SUN_ELEVATION");
     323             : 
     324             :         // Get ESRI_MD_DATA_TYPE.
     325             :         const char *pImgSegFieldICAT = CSLFetchNameValue(papszMD, "NITF_ICAT");
     326             : 
     327             :         const char *pDataType = NULL;
     328             :         if ((pImgSegFieldICAT != NULL) &&
     329             :             (STARTS_WITH_CI(pImgSegFieldICAT, "DTEM")))
     330             :             pDataType = "Elevation";
     331             :         else
     332             :             pDataType = "Generic";
     333             : 
     334             :         if (pAngleToNorth == NULL)
     335             :             pAngleToNorth =
     336             :                 CSLFetchNameValue(papszMD, "NITF_USE00A_ANGLE_TO_NORTH");
     337             : 
     338             :         // Percent cloud cover == 999 means that the information is not
     339             :         // available.
     340             :         if ((pPercentCloudCover != NULL) &&
     341             :             (STARTS_WITH_CI(pPercentCloudCover, "999")))
     342             :             pPercentCloudCover = NULL;
     343             : 
     344             :         pAngleToNorth =
     345             :             CSLFetchNameValue(papszMD, "NITF_USE00A_ANGLE_TO_NORTH");
     346             : 
     347             :         if (pSunAzimuth == NULL)
     348             :             pSunAzimuth = CSLFetchNameValue(papszMD, "NITF_USE00A_SUN_AZ");
     349             : 
     350             :         if (pSunElevation == NULL)
     351             :             pSunElevation = CSLFetchNameValue(papszMD, "NITF_USE00A_SUN_EL");
     352             : 
     353             :         // CSLAddNameValue will not add the key/value pair if the value is NULL.
     354             :         papszEsriMD = CSLAddNameValue(papszEsriMD, pEsriMDAcquisitionDate,
     355             :                                       pAcquisitionDate);
     356             :         papszEsriMD =
     357             :             CSLAddNameValue(papszEsriMD, pEsriMDAngleToNorth, pAngleToNorth);
     358             :         papszEsriMD =
     359             :             CSLAddNameValue(papszEsriMD, pEsriMDCircularError, pCircularError);
     360             :         papszEsriMD = CSLAddNameValue(papszEsriMD, pEsriMDDataType, pDataType);
     361             :         papszEsriMD = CSLAddNameValue(papszEsriMD, pEsriMDIsCloudCover,
     362             :                                       ccSegment.c_str());
     363             :         papszEsriMD =
     364             :             CSLAddNameValue(papszEsriMD, pEsriMDLinearError, pLinearError);
     365             :         papszEsriMD =
     366             :             CSLAddNameValue(papszEsriMD, pEsriMDProductName, pProductName);
     367             :         papszEsriMD = CSLAddNameValue(papszEsriMD, pEsriMDPercentCloudCover,
     368             :                                       pPercentCloudCover);
     369             :         papszEsriMD =
     370             :             CSLAddNameValue(papszEsriMD, pEsriMDSensorName, pSensorName);
     371             :         papszEsriMD =
     372             :             CSLAddNameValue(papszEsriMD, pEsriMDSunAzimuth, pSunAzimuth);
     373             :         papszEsriMD =
     374             :             CSLAddNameValue(papszEsriMD, pEsriMDSunElevation, pSunElevation);
     375             :     }
     376             : 
     377             :     return papszEsriMD;
     378             : }
     379             : 
     380             : #endif /* def ESRI_BUILD */
     381             : 
     382             : /************************************************************************/
     383             : /*                          SetBandMetadata()                           */
     384             : /************************************************************************/
     385             : 
     386      211037 : static void SetBandMetadata(NITFImage *psImage, GDALRasterBand *poBand,
     387             :                             int nBand, bool bReportISUBCAT)
     388             : {
     389      211037 :     const NITFBandInfo *psBandInfo = psImage->pasBandInfo + nBand - 1;
     390             : 
     391             :     /* The ISUBCAT is particularly valuable for interpreting SAR bands */
     392      211037 :     if (bReportISUBCAT && strlen(psBandInfo->szISUBCAT) > 0)
     393             :     {
     394           4 :         poBand->SetMetadataItem("NITF_ISUBCAT", psBandInfo->szISUBCAT);
     395             :     }
     396      211037 : }
     397             : 
     398             : /************************************************************************/
     399             : /*                                Open()                                */
     400             : /************************************************************************/
     401             : 
     402         501 : GDALDataset *NITFDataset::Open(GDALOpenInfo *poOpenInfo)
     403             : {
     404         501 :     return OpenInternal(poOpenInfo, nullptr, false, -1);
     405             : }
     406             : 
     407         752 : NITFDataset *NITFDataset::OpenInternal(GDALOpenInfo *poOpenInfo,
     408             :                                        GDALDataset *poWritableJ2KDataset,
     409             :                                        bool bOpenForCreate, int nIMIndex)
     410             : 
     411             : {
     412         752 :     if (!NITFDriverIdentify(poOpenInfo))
     413           0 :         return nullptr;
     414             : 
     415         752 :     const char *pszFilename = poOpenInfo->pszFilename;
     416             : 
     417             :     /* -------------------------------------------------------------------- */
     418             :     /*      Select a specific subdataset.                                   */
     419             :     /* -------------------------------------------------------------------- */
     420         752 :     if (STARTS_WITH_CI(pszFilename, "NITF_IM:"))
     421             :     {
     422          20 :         pszFilename += 8;
     423          20 :         nIMIndex = atoi(pszFilename);
     424             : 
     425          54 :         while (*pszFilename != '\0' && *pszFilename != ':')
     426          34 :             pszFilename++;
     427             : 
     428          20 :         if (*pszFilename == ':')
     429          20 :             pszFilename++;
     430             :     }
     431             : 
     432             :     /* -------------------------------------------------------------------- */
     433             :     /*      Open the file with library.                                     */
     434             :     /* -------------------------------------------------------------------- */
     435         752 :     NITFFile *psFile = nullptr;
     436             : 
     437         752 :     if (poOpenInfo->fpL)
     438             :     {
     439         732 :         VSILFILE *fpL = poOpenInfo->fpL;
     440         732 :         poOpenInfo->fpL = nullptr;
     441         732 :         psFile = NITFOpenEx(fpL, pszFilename);
     442             :     }
     443             :     else
     444          20 :         psFile = NITFOpen(pszFilename, poOpenInfo->eAccess == GA_Update);
     445         752 :     if (psFile == nullptr)
     446             :     {
     447           2 :         return nullptr;
     448             :     }
     449             : 
     450         750 :     if (!bOpenForCreate)
     451             :     {
     452         499 :         NITFCollectAttachments(psFile);
     453         499 :         NITFReconcileAttachments(psFile);
     454             :     }
     455             : 
     456             :     /* -------------------------------------------------------------------- */
     457             :     /*      Is there an image to operate on?                                */
     458             :     /* -------------------------------------------------------------------- */
     459         750 :     int nThisIM = 0;
     460         750 :     NITFImage *psImage = nullptr;
     461             : 
     462         750 :     int iSegment = 0;  // Used after for loop.
     463        7754 :     for (; iSegment < psFile->nSegmentCount; iSegment++)
     464             :     {
     465       15496 :         if (EQUAL(psFile->pasSegmentInfo[iSegment].szSegmentType, "IM") &&
     466        7747 :             (nThisIM++ == nIMIndex || nIMIndex == -1))
     467             :         {
     468         745 :             psImage = NITFImageAccess(psFile, iSegment);
     469         745 :             if (psImage == nullptr)
     470             :             {
     471           0 :                 NITFClose(psFile);
     472           0 :                 return nullptr;
     473             :             }
     474         745 :             break;
     475             :         }
     476             :     }
     477             : 
     478             :     /* -------------------------------------------------------------------- */
     479             :     /*      If no image segments found report this to the user.             */
     480             :     /* -------------------------------------------------------------------- */
     481         750 :     if (psImage == nullptr)
     482             :     {
     483           5 :         CPLError(CE_Warning, CPLE_AppDefined,
     484             :                  "The file %s appears to be an NITF file, but no image "
     485             :                  "blocks were found on it.",
     486             :                  poOpenInfo->pszFilename);
     487             :     }
     488         745 :     else if (psImage->nBitsPerSample > 16 &&
     489          44 :              (EQUAL(psImage->szIC, "C3") || EQUAL(psImage->szIC, "M3")))
     490             :     {
     491             :         // Early rejection of JPEG compressed images with invalid bit depth
     492             :         // Otherwise this will cause potentially heap buffer overflows
     493             :         // as ReadJPEGBlock() assumes that the data type size is no larger
     494             :         // than 2 bytes.
     495           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     496           0 :                  "IC=%s and ABPP=%d are not supported", psImage->szIC,
     497             :                  psImage->nBitsPerSample);
     498           0 :         NITFClose(psFile);
     499           0 :         return nullptr;
     500             :     }
     501             : 
     502             :     /* -------------------------------------------------------------------- */
     503             :     /*      Create a corresponding GDALDataset.                             */
     504             :     /* -------------------------------------------------------------------- */
     505         750 :     NITFDataset *poDS = new NITFDataset();
     506             : 
     507         750 :     poDS->psFile = psFile;
     508         750 :     poDS->psImage = psImage;
     509         750 :     poDS->eAccess = poOpenInfo->eAccess;
     510         750 :     poDS->osNITFFilename = pszFilename;
     511         750 :     poDS->nIMIndex = nIMIndex;
     512             : 
     513         750 :     if (psImage)
     514             :     {
     515         745 :         if (psImage->nCols <= 0 || psImage->nRows <= 0 ||
     516         745 :             psImage->nBlockWidth <= 0 || psImage->nBlockHeight <= 0)
     517             :         {
     518           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     519             :                      "Bad values in NITF image : nCols=%d, nRows=%d, "
     520             :                      "nBlockWidth=%d, nBlockHeight=%d",
     521             :                      psImage->nCols, psImage->nRows, psImage->nBlockWidth,
     522             :                      psImage->nBlockHeight);
     523           0 :             delete poDS;
     524           0 :             return nullptr;
     525             :         }
     526             : 
     527         745 :         poDS->nRasterXSize = psImage->nCols;
     528         745 :         poDS->nRasterYSize = psImage->nRows;
     529             :     }
     530             :     else
     531             :     {
     532           5 :         poDS->nRasterXSize = 1;
     533           5 :         poDS->nRasterYSize = 1;
     534             :     }
     535             : 
     536             :     /* Can be set to NO to avoid opening the underlying JPEG2000/JPEG */
     537             :     /* stream. Might speed up operations when just metadata is needed */
     538             :     bool bOpenUnderlyingDS =
     539         750 :         CPLTestBool(CPLGetConfigOption("NITF_OPEN_UNDERLYING_DS", "YES"));
     540             : 
     541             :     /* -------------------------------------------------------------------- */
     542             :     /*      If the image is JPEG2000 (C8) compressed, we will need to       */
     543             :     /*      open the image data as a JPEG2000 dataset.                      */
     544             :     /* -------------------------------------------------------------------- */
     545         750 :     int nUsableBands = 0;
     546         750 :     bool bSetColorInterpretation = true;
     547         750 :     bool bSetColorTable = false;
     548             : 
     549         750 :     if (psImage)
     550         745 :         nUsableBands = psImage->nBands;
     551             : 
     552         750 :     if (bOpenUnderlyingDS && psImage != nullptr && EQUAL(psImage->szIC, "C8"))
     553             :     {
     554          37 :         CPLString osDSName;
     555             : 
     556             :         osDSName.Printf("/vsisubfile/" CPL_FRMT_GUIB "_" CPL_FRMT_GUIB ",%s",
     557          37 :                         psFile->pasSegmentInfo[iSegment].nSegmentStart,
     558          37 :                         psFile->pasSegmentInfo[iSegment].nSegmentSize,
     559          37 :                         pszFilename);
     560             : 
     561          37 :         if (poWritableJ2KDataset != nullptr)
     562             :         {
     563           1 :             poDS->poJ2KDataset = poWritableJ2KDataset;
     564           1 :             poDS->bJP2Writing = TRUE;
     565           1 :             poWritableJ2KDataset = nullptr;
     566             :         }
     567             :         else
     568             :         {
     569             :             // We explicitly list the allowed drivers to avoid hostile content
     570             :             // to be opened by a random driver.
     571             :             static const char *const apszDrivers[] = {
     572             :                 "JP2KAK", "JP2ECW", "JP2MRSID", "JP2OPENJPEG", nullptr};
     573          36 :             poDS->poJ2KDataset = GDALDataset::FromHandle(GDALOpenEx(
     574             :                 osDSName, GDAL_OF_RASTER, apszDrivers, nullptr, nullptr));
     575             : 
     576          36 :             if (poDS->poJ2KDataset == nullptr)
     577             :             {
     578           0 :                 bool bFoundJPEG2000Driver = false;
     579           0 :                 for (int iDriver = 0; apszDrivers[iDriver] != nullptr;
     580             :                      iDriver++)
     581             :                 {
     582           0 :                     if (GDALGetDriverByName(apszDrivers[iDriver]) != nullptr)
     583           0 :                         bFoundJPEG2000Driver = true;
     584             :                 }
     585             : 
     586           0 :                 CPLError(
     587             :                     CE_Failure, CPLE_AppDefined,
     588             :                     "Unable to open JPEG2000 image within NITF file.\n%s\n%s",
     589             :                     !bFoundJPEG2000Driver
     590             :                         ? "No JPEG2000 capable driver (JP2KAK, JP2ECW, "
     591             :                           "JP2MRSID, "
     592             :                           "JP2OPENJPEG, etc...) is available."
     593             :                         : "One or several JPEG2000 capable drivers are "
     594             :                           "available but "
     595             :                           "the datastream could not be opened successfully.",
     596             :                     "You can define the NITF_OPEN_UNDERLYING_DS configuration "
     597             :                     "option to NO, in order to just get the metadata.");
     598           0 :                 delete poDS;
     599           0 :                 return nullptr;
     600             :             }
     601             : 
     602          36 :             if (poDS->poJ2KDataset->GetMOFlags() & GMO_PAM_CLASS)
     603             :             {
     604          36 :                 reinterpret_cast<GDALPamDataset *>(poDS->poJ2KDataset)
     605          36 :                     ->SetPamFlags(
     606          36 :                         reinterpret_cast<GDALPamDataset *>(poDS->poJ2KDataset)
     607          36 :                             ->GetPamFlags() |
     608             :                         GPF_NOSAVE);
     609             :             }
     610             :         }
     611             : 
     612          74 :         if (poDS->GetRasterXSize() != poDS->poJ2KDataset->GetRasterXSize() ||
     613          37 :             poDS->GetRasterYSize() != poDS->poJ2KDataset->GetRasterYSize())
     614             :         {
     615           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     616             :                      "JPEG2000 data stream has not the same dimensions as "
     617             :                      "the NITF file.");
     618           0 :             delete poDS;
     619           0 :             return nullptr;
     620             :         }
     621             : 
     622          37 :         if (nUsableBands == 1)
     623             :         {
     624             :             const char *pszIREP =
     625          22 :                 CSLFetchNameValue(psImage->papszMetadata, "NITF_IREP");
     626          22 :             if (pszIREP != nullptr && EQUAL(pszIREP, "RGB/LUT"))
     627             :             {
     628           0 :                 if (poDS->poJ2KDataset->GetRasterCount() == 3)
     629             :                 {
     630             :                     // Test case:
     631             :                     // http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9_jp2_2places.ntf
     632             :                     /* 256-entry palette/LUT in both JP2 Header and image
     633             :                      * Subheader */
     634             :                     /* In this case, the JPEG2000 driver will probably do the
     635             :                      * RGB expansion. */
     636           0 :                     nUsableBands = 3;
     637           0 :                     bSetColorInterpretation = false;
     638             :                 }
     639           0 :                 else if (poDS->poJ2KDataset->GetRasterCount() == 1 &&
     640           0 :                          psImage->pasBandInfo[0].nSignificantLUTEntries > 0)
     641             :                 {
     642             :                     // Test case:
     643             :                     // http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9_j2c.ntf
     644             : 
     645             :                     // 256-entry/LUT in Image Subheader, JP2 header completely
     646             :                     // removed. The JPEG2000 driver will decode it as a grey
     647             :                     // band So we must set the color table on the wrapper band
     648             :                     // or for file9_jp2_2places.ntf as well if the J2K driver
     649             :                     // does do RGB expansion
     650           0 :                     bSetColorTable = true;
     651             :                 }
     652             :             }
     653             :         }
     654             : 
     655          37 :         if (poDS->poJ2KDataset->GetRasterCount() < nUsableBands)
     656             :         {
     657           0 :             CPLError(CE_Warning, CPLE_AppDefined,
     658             :                      "JPEG2000 data stream has less useful bands than "
     659             :                      "expected, likely because some channels have "
     660             :                      "differing resolutions.");
     661             : 
     662           0 :             nUsableBands = poDS->poJ2KDataset->GetRasterCount();
     663          37 :         }
     664             :     }
     665             : 
     666             :     /* -------------------------------------------------------------------- */
     667             :     /*      If the image is JPEG (C3) compressed, we will need to open      */
     668             :     /*      the image data as a JPEG dataset.                               */
     669             :     /* -------------------------------------------------------------------- */
     670         713 :     else if (bOpenUnderlyingDS && psImage != nullptr &&
     671         708 :              EQUAL(psImage->szIC, "C3") && psImage->nBlocksPerRow == 1 &&
     672          22 :              psImage->nBlocksPerColumn == 1)
     673             :     {
     674          22 :         GUIntBig nJPEGStart = psFile->pasSegmentInfo[iSegment].nSegmentStart;
     675             : 
     676          22 :         bool bError = false;
     677          22 :         poDS->nQLevel = poDS->ScanJPEGQLevel(&nJPEGStart, &bError);
     678             : 
     679          22 :         CPLString osDSName;
     680             : 
     681          22 :         if (psFile->pasSegmentInfo[iSegment].nSegmentSize <
     682          22 :             nJPEGStart - psFile->pasSegmentInfo[iSegment].nSegmentStart)
     683             :         {
     684           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Corrupted segment size");
     685           0 :             delete poDS;
     686           0 :             return nullptr;
     687             :         }
     688             : 
     689          22 :         osDSName.Printf(
     690             :             "JPEG_SUBFILE:Q%d," CPL_FRMT_GUIB "," CPL_FRMT_GUIB ",%s",
     691             :             poDS->nQLevel, nJPEGStart,
     692          22 :             psFile->pasSegmentInfo[iSegment].nSegmentSize -
     693          22 :                 (nJPEGStart - psFile->pasSegmentInfo[iSegment].nSegmentStart),
     694          22 :             pszFilename);
     695             : 
     696          22 :         CPLDebug("GDAL", "NITFDataset::Open() as IC=C3 (JPEG compressed)\n");
     697             : 
     698          22 :         poDS->poJPEGDataset =
     699          22 :             GDALDataset::FromHandle(GDALOpen(osDSName, GA_ReadOnly));
     700          22 :         if (poDS->poJPEGDataset == nullptr)
     701             :         {
     702           0 :             int bFoundJPEGDriver = GDALGetDriverByName("JPEG") != nullptr;
     703           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     704             :                      "Unable to open JPEG image within NITF file.\n%s\n%s",
     705             :                      (!bFoundJPEGDriver)
     706             :                          ? "The JPEG driver is not available."
     707             :                          : "The JPEG driver is available but the datastream "
     708             :                            "could not be opened successfully.",
     709             :                      "You can define the NITF_OPEN_UNDERLYING_DS configuration "
     710             :                      "option to NO, in order to just get the metadata.");
     711           0 :             delete poDS;
     712           0 :             return nullptr;
     713             :         }
     714             : 
     715             :         /* In some circumstances, the JPEG image can be larger than the NITF */
     716             :         /* (NCOLS, NROWS) dimensions (#5001), so accept it as a valid case */
     717             :         /* But reject when it is smaller than the NITF dimensions. */
     718          44 :         if (poDS->GetRasterXSize() > poDS->poJPEGDataset->GetRasterXSize() ||
     719          22 :             poDS->GetRasterYSize() > poDS->poJPEGDataset->GetRasterYSize())
     720             :         {
     721           0 :             CPLError(
     722             :                 CE_Failure, CPLE_AppDefined,
     723             :                 "JPEG data stream has smaller dimensions than the NITF file.");
     724           0 :             delete poDS;
     725           0 :             return nullptr;
     726             :         }
     727             : 
     728          22 :         if (poDS->poJPEGDataset->GetMOFlags() & GMO_PAM_CLASS)
     729             :         {
     730          22 :             (reinterpret_cast<GDALPamDataset *>(poDS->poJPEGDataset))
     731          22 :                 ->SetPamFlags(
     732          22 :                     (reinterpret_cast<GDALPamDataset *>(poDS->poJPEGDataset))
     733          22 :                         ->GetPamFlags() |
     734             :                     GPF_NOSAVE);
     735             :         }
     736             : 
     737          22 :         if (poDS->poJPEGDataset->GetRasterCount() < nUsableBands)
     738             :         {
     739           0 :             CPLError(
     740             :                 CE_Warning, CPLE_AppDefined,
     741             :                 "JPEG data stream has less useful bands than expected, likely\n"
     742             :                 "because some channels have differing resolutions.");
     743             : 
     744           0 :             nUsableBands = poDS->poJPEGDataset->GetRasterCount();
     745             :         }
     746             :     }
     747             : 
     748             :     /* -------------------------------------------------------------------- */
     749             :     /*      Create band information objects.                                */
     750             :     /* -------------------------------------------------------------------- */
     751             : 
     752             :     /* Keep temporary non-based dataset bands */
     753         750 :     bool bIsTempBandUsed = false;
     754         750 :     GDALDataType dtFirstBand = GDT_Unknown;
     755         750 :     GDALDataType dtSecondBand = GDT_Unknown;
     756        1500 :     std::vector<GDALRasterBand *> apoNewBands(nUsableBands);
     757             : 
     758         750 :     GDALDataset *poBaseDS = nullptr;
     759         750 :     if (poDS->poJ2KDataset != nullptr)
     760          37 :         poBaseDS = poDS->poJ2KDataset;
     761         713 :     else if (poDS->poJPEGDataset != nullptr)
     762          22 :         poBaseDS = poDS->poJPEGDataset;
     763             : 
     764      211792 :     for (int iBand = 0; iBand < nUsableBands; iBand++)
     765             :     {
     766      211042 :         if (poBaseDS != nullptr)
     767             :         {
     768         107 :             GDALRasterBand *poBaseBand = poBaseDS->GetRasterBand(iBand + 1);
     769             : 
     770         107 :             SetBandMetadata(psImage, poBaseBand, iBand + 1, true);
     771             : 
     772             :             NITFWrapperRasterBand *poBand =
     773         107 :                 new NITFWrapperRasterBand(poDS, poBaseBand, iBand + 1);
     774             : 
     775         107 :             NITFBandInfo *psBandInfo = psImage->pasBandInfo + iBand;
     776         107 :             if (bSetColorInterpretation)
     777             :             {
     778             :                 /* FIXME? Does it make sense if the JPEG/JPEG2000 driver decodes
     779             :                  */
     780             :                 /* YCbCr data as RGB. We probably don't want to set */
     781             :                 /* the color interpretation as Y, Cb, Cr */
     782         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "R"))
     783          12 :                     poBand->SetColorInterpretation(GCI_RedBand);
     784         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "G"))
     785          12 :                     poBand->SetColorInterpretation(GCI_GreenBand);
     786         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "B"))
     787          12 :                     poBand->SetColorInterpretation(GCI_BlueBand);
     788         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "M"))
     789          39 :                     poBand->SetColorInterpretation(GCI_GrayIndex);
     790         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "Y"))
     791          10 :                     poBand->SetColorInterpretation(GCI_YCbCr_YBand);
     792         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "Cb"))
     793          10 :                     poBand->SetColorInterpretation(GCI_YCbCr_CbBand);
     794         107 :                 if (EQUAL(psBandInfo->szIREPBAND, "Cr"))
     795          10 :                     poBand->SetColorInterpretation(GCI_YCbCr_CrBand);
     796             :             }
     797         107 :             if (bSetColorTable)
     798             :             {
     799           0 :                 poBand->SetColorTableFromNITFBandInfo();
     800           0 :                 poBand->SetColorInterpretation(GCI_PaletteIndex);
     801             :             }
     802             : 
     803         107 :             poDS->SetBand(iBand + 1, poBand);
     804             : 
     805         107 :             if (iBand == 0)
     806          59 :                 dtFirstBand = poBand->GetRasterDataType();
     807          48 :             else if (iBand == 1)
     808          25 :                 dtSecondBand = poBand->GetRasterDataType();
     809             :         }
     810             :         else
     811             :         {
     812      210935 :             bIsTempBandUsed = true;
     813             : 
     814      210935 :             NITFRasterBand *poBand = new NITFRasterBand(poDS, iBand + 1);
     815      210935 :             if (poBand->GetRasterDataType() == GDT_Unknown)
     816             :             {
     817           0 :                 for (auto *poOtherBand : apoNewBands)
     818           0 :                     delete poOtherBand;
     819           0 :                 delete poBand;
     820           0 :                 delete poDS;
     821           0 :                 return nullptr;
     822             :             }
     823             : 
     824      210935 :             apoNewBands[iBand] = poBand;
     825             : 
     826      210935 :             if (iBand == 0)
     827         686 :                 dtFirstBand = poBand->GetRasterDataType();
     828      210935 :             if (iBand == 1)
     829         127 :                 dtSecondBand = poBand->GetRasterDataType();
     830             :         }
     831             :     }
     832             : 
     833             :     /* -------------------------------------------------------------------- */
     834             :     /*      SAR images may store complex data in 2 bands (I and Q)          */
     835             :     /*      Map onto a GDAL complex raster band                             */
     836             :     /* -------------------------------------------------------------------- */
     837         750 :     bool bIsTempBandSet = false;
     838         499 :     if (!bOpenForCreate && psImage &&
     839         495 :         EQUAL(psImage->szICAT, "SAR")  //SAR image...
     840           6 :         && bIsTempBandUsed &&
     841           6 :         nUsableBands == psImage->nBands
     842             :         //...with 2 bands ... (modified to allow an even number - spec seems to indicate only 2 bands allowed?)
     843           6 :         && (nUsableBands % 2) == 0 &&
     844             :         dtFirstBand == dtSecondBand  //...that have the same datatype...
     845           6 :         && !GDALDataTypeIsComplex(dtFirstBand)  //...and are not complex...
     846             :         //..and can be mapped directly to a complex type
     847           6 :         && (dtFirstBand == GDT_Int16 || dtFirstBand == GDT_Int32 ||
     848        1249 :             dtFirstBand == GDT_Float32 || dtFirstBand == GDT_Float64) &&
     849           6 :         CPLTestBool(CPLGetConfigOption("NITF_SAR_AS_COMPLEX_TYPE", "YES")))
     850             :     {
     851           5 :         bool allBandsIQ = true;
     852          10 :         for (int i = 0; i < nUsableBands; i += 2)
     853             :         {
     854           5 :             const NITFBandInfo *psBandInfo1 = psImage->pasBandInfo + i;
     855           5 :             const NITFBandInfo *psBandInfo2 = psImage->pasBandInfo + i + 1;
     856             : 
     857             :             //check that the ISUBCAT is labelled "I" and "Q" on the 2 bands
     858           5 :             if (!EQUAL(psBandInfo1->szISUBCAT, "I") ||
     859           5 :                 !EQUAL(psBandInfo2->szISUBCAT, "Q"))
     860             :             {
     861           0 :                 allBandsIQ = false;
     862           0 :                 break;
     863             :             }
     864             :         }
     865             : 
     866           5 :         if (allBandsIQ)
     867             :         {
     868           5 :             poDS->m_bHasComplexRasterBand = true;
     869          10 :             for (int i = 0; i < (nUsableBands / 2); i++)
     870             :             {
     871             :                 //wrap the I and Q bands into a single complex band
     872           5 :                 const int iBandIndex = 2 * i;
     873           5 :                 const int qBandIndex = 2 * i + 1;
     874             :                 NITFComplexRasterBand *poBand = new NITFComplexRasterBand(
     875           5 :                     poDS, apoNewBands[iBandIndex], apoNewBands[qBandIndex],
     876           5 :                     iBandIndex + 1, qBandIndex + 1);
     877           5 :                 SetBandMetadata(psImage, poBand, i + 1, false);
     878           5 :                 poDS->SetBand(i + 1, poBand);
     879           5 :                 bIsTempBandSet = true;
     880             :             }
     881             :         }
     882             :     }
     883             : 
     884         750 :     if (bIsTempBandUsed && !bIsTempBandSet)
     885             :     {
     886             :         // Reset properly bands that are not complex
     887      211606 :         for (int iBand = 0; iBand < nUsableBands; iBand++)
     888             :         {
     889      210925 :             GDALRasterBand *poBand = apoNewBands[iBand];
     890      210925 :             SetBandMetadata(psImage, poBand, iBand + 1, true);
     891      210925 :             poDS->SetBand(iBand + 1, poBand);
     892             :         }
     893             :     }
     894             : 
     895             :     /* -------------------------------------------------------------------- */
     896             :     /*      Report problems with odd bit sizes.                             */
     897             :     /* -------------------------------------------------------------------- */
     898         750 :     if (poOpenInfo->eAccess == GA_Update && psImage != nullptr &&
     899         256 :         (psImage->nBitsPerSample % 8 != 0) && poDS->poJPEGDataset == nullptr &&
     900           0 :         poDS->poJ2KDataset == nullptr)
     901             :     {
     902           0 :         CPLError(
     903             :             CE_Warning, CPLE_AppDefined,
     904             :             "Image with %d bits per sample cannot be opened in update mode.",
     905             :             psImage->nBitsPerSample);
     906           0 :         delete poDS;
     907           0 :         return nullptr;
     908             :     }
     909             : 
     910             :     /* -------------------------------------------------------------------- */
     911             :     /*      Process the projection from the ICORDS.                         */
     912             :     /* -------------------------------------------------------------------- */
     913         750 :     if (psImage == nullptr)
     914             :     {
     915             :         /* nothing */
     916             :     }
     917         745 :     else if (psImage->chICORDS == 'G' || psImage->chICORDS == 'D')
     918             :     {
     919         196 :         poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
     920             :     }
     921         549 :     else if (psImage->chICORDS == 'C')
     922             :     {
     923           0 :         poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
     924             : 
     925             :         /* convert latitudes from geocentric to geodetic form. */
     926             : 
     927           0 :         psImage->dfULY =
     928           0 :             NITF_WGS84_Geocentric_Latitude_To_Geodetic_Latitude(psImage->dfULY);
     929           0 :         psImage->dfLLY =
     930           0 :             NITF_WGS84_Geocentric_Latitude_To_Geodetic_Latitude(psImage->dfLLY);
     931           0 :         psImage->dfURY =
     932           0 :             NITF_WGS84_Geocentric_Latitude_To_Geodetic_Latitude(psImage->dfURY);
     933           0 :         psImage->dfLRY =
     934           0 :             NITF_WGS84_Geocentric_Latitude_To_Geodetic_Latitude(psImage->dfLRY);
     935             :     }
     936         549 :     else if (psImage->chICORDS == 'S' || psImage->chICORDS == 'N')
     937             :     {
     938             :         // in open-for-create mode, we don't have a valid UTM zone, which
     939             :         // would make PROJ unhappy
     940          62 :         if (!bOpenForCreate)
     941             :         {
     942          41 :             poDS->m_oSRS.SetUTM(psImage->nZone, psImage->chICORDS == 'N');
     943          41 :             poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
     944             :         }
     945             :     }
     946         487 :     else if (psImage->chICORDS == 'U' && psImage->nZone != 0)
     947             :     {
     948           2 :         poDS->m_oSRS.SetUTM(std::abs(psImage->nZone), psImage->nZone > 0);
     949           2 :         poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
     950             :     }
     951             : 
     952             :     /* -------------------------------------------------------------------- */
     953             :     /*      Try looking for a .nfw file.                                    */
     954             :     /* -------------------------------------------------------------------- */
     955        1495 :     if (psImage && GDALReadWorldFile2(pszFilename, "nfw", poDS->adfGeoTransform,
     956         745 :                                       poOpenInfo->GetSiblingFiles(), nullptr))
     957             :     {
     958             :         int isNorth;
     959             :         int zone;
     960             : 
     961           3 :         poDS->bGotGeoTransform = TRUE;
     962             : 
     963             :         /* If nfw found, try looking for a header with projection info */
     964             :         /* in space imaging style format                               */
     965           3 :         const char *pszHDR = CPLResetExtension(pszFilename, "hdr");
     966             : 
     967           3 :         VSILFILE *fpHDR = VSIFOpenL(pszHDR, "rt");
     968             : 
     969           3 :         if (fpHDR == nullptr && VSIIsCaseSensitiveFS(pszHDR))
     970             :         {
     971           1 :             pszHDR = CPLResetExtension(pszFilename, "HDR");
     972           1 :             fpHDR = VSIFOpenL(pszHDR, "rt");
     973             :         }
     974             : 
     975           3 :         if (fpHDR != nullptr)
     976             :         {
     977           2 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fpHDR));
     978           2 :             char **papszLines = CSLLoad2(pszHDR, 16, 200, nullptr);
     979           2 :             if (CSLCount(papszLines) == 16)
     980             :             {
     981             : 
     982           2 :                 if (psImage->chICORDS == 'N')
     983           2 :                     isNorth = 1;
     984           0 :                 else if (psImage->chICORDS == 'S')
     985           0 :                     isNorth = 0;
     986           0 :                 else if (psImage->chICORDS == 'G' || psImage->chICORDS == 'D' ||
     987           0 :                          psImage->chICORDS == 'C')
     988             :                 {
     989           0 :                     if (psImage->dfLLY + psImage->dfLRY + psImage->dfULY +
     990           0 :                             psImage->dfURY <
     991             :                         0)
     992           0 :                         isNorth = 0;
     993             :                     else
     994           0 :                         isNorth = 1;
     995             :                 }
     996           0 :                 else if (psImage->chICORDS == 'U')
     997             :                 {
     998           0 :                     isNorth = psImage->nZone >= 0;
     999             :                 }
    1000             :                 else
    1001             :                 {
    1002             :                     // Arbitrarily suppose we are in northern hemisphere.
    1003           0 :                     isNorth = 1;
    1004             : 
    1005             :                     /* unless we have other information to determine the
    1006             :                      * hemisphere */
    1007           0 :                     char **papszUSE00A_MD = NITFReadSTDIDC(psImage);
    1008           0 :                     if (papszUSE00A_MD != nullptr)
    1009             :                     {
    1010           0 :                         const char *pszLocation = CSLFetchNameValue(
    1011             :                             papszUSE00A_MD, "NITF_STDIDC_LOCATION");
    1012           0 :                         if (pszLocation && strlen(pszLocation) == 11)
    1013             :                         {
    1014           0 :                             isNorth = (pszLocation[4] == 'N');
    1015             :                         }
    1016           0 :                         CSLDestroy(papszUSE00A_MD);
    1017             :                     }
    1018             :                     else
    1019             :                     {
    1020             :                         NITFRPC00BInfo sRPCInfo;
    1021           0 :                         if (NITFReadRPC00B(psImage, &sRPCInfo) &&
    1022           0 :                             sRPCInfo.SUCCESS)
    1023             :                         {
    1024           0 :                             isNorth = (sRPCInfo.LAT_OFF >= 0);
    1025             :                         }
    1026             :                     }
    1027             :                 }
    1028             : 
    1029           2 :                 if ((STARTS_WITH_CI(papszLines[7],
    1030             :                                     "Selected Projection: Universal Transverse "
    1031           2 :                                     "Mercator")) &&
    1032           2 :                     (STARTS_WITH_CI(papszLines[8], "Zone: ")) &&
    1033           2 :                     (strlen(papszLines[8]) >= 7))
    1034             :                 {
    1035           2 :                     zone = atoi(&(papszLines[8][6]));
    1036           2 :                     poDS->m_oSRS.Clear();
    1037           2 :                     poDS->m_oSRS.SetUTM(zone, isNorth);
    1038           2 :                     poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
    1039             :                 }
    1040             :                 else
    1041             :                 {
    1042             :                     /* Couldn't find associated projection info.
    1043             :                        Go back to original file for geotransform.
    1044             :                     */
    1045           0 :                     poDS->bGotGeoTransform = FALSE;
    1046             :                 }
    1047             :             }
    1048             :             else
    1049           0 :                 poDS->bGotGeoTransform = FALSE;
    1050           2 :             CSLDestroy(papszLines);
    1051             :         }
    1052             :         else
    1053           1 :             poDS->bGotGeoTransform = FALSE;
    1054             :     }
    1055             : 
    1056             :     /* -------------------------------------------------------------------- */
    1057             :     /*      Does this look like a CADRG polar tile ? (#2940)                */
    1058             :     /* -------------------------------------------------------------------- */
    1059             :     const char *pszIID1 =
    1060         750 :         (psImage) ? CSLFetchNameValue(psImage->papszMetadata, "NITF_IID1")
    1061         750 :                   : nullptr;
    1062             :     const char *pszITITLE =
    1063         750 :         (psImage) ? CSLFetchNameValue(psImage->papszMetadata, "NITF_ITITLE")
    1064         750 :                   : nullptr;
    1065         750 :     if (psImage != nullptr && !poDS->bGotGeoTransform &&
    1066         743 :         (psImage->chICORDS == 'G' || psImage->chICORDS == 'D') &&
    1067         196 :         pszIID1 != nullptr && EQUAL(pszIID1, "CADRG") && pszITITLE != nullptr &&
    1068          24 :         strlen(pszITITLE) >= 12 &&
    1069          24 :         (pszITITLE[strlen(pszITITLE) - 1] == '9' ||
    1070          23 :          pszITITLE[strlen(pszITITLE) - 1] == 'J'))
    1071             :     {
    1072             :         /* To get a perfect rectangle in Azimuthal Equidistant projection, we
    1073             :          * must use */
    1074             :         /* the sphere and not WGS84 ellipsoid. That's a bit strange... */
    1075           1 :         const char *pszNorthPolarProjection =
    1076             :             "PROJCS[\"ARC_System_Zone_09\",GEOGCS[\"GCS_Sphere\","
    1077             :             "DATUM[\"D_Sphere\",SPHEROID[\"Sphere\",6378137.0,0.0]],"
    1078             :             "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],"
    1079             :             "PROJECTION[\"Azimuthal_Equidistant\"],"
    1080             :             "PARAMETER[\"latitude_of_center\",90],"
    1081             :             "PARAMETER[\"longitude_of_center\",0],"
    1082             :             "PARAMETER[\"false_easting\",0],"
    1083             :             "PARAMETER[\"false_northing\",0],"
    1084             :             "UNIT[\"metre\",1]]";
    1085             : 
    1086           1 :         const char *pszSouthPolarProjection =
    1087             :             "PROJCS[\"ARC_System_Zone_18\",GEOGCS[\"GCS_Sphere\","
    1088             :             "DATUM[\"D_Sphere\",SPHEROID[\"Sphere\",6378137.0,0.0]],"
    1089             :             "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],"
    1090             :             "PROJECTION[\"Azimuthal_Equidistant\"],"
    1091             :             "PARAMETER[\"latitude_of_center\",-90],"
    1092             :             "PARAMETER[\"longitude_of_center\",0],"
    1093             :             "PARAMETER[\"false_easting\",0],"
    1094             :             "PARAMETER[\"false_northing\",0],"
    1095             :             "UNIT[\"metre\",1]]";
    1096             : 
    1097           2 :         OGRSpatialReference oSRS_AEQD, oSRS_WGS84;
    1098             : 
    1099           2 :         const char *pszPolarProjection = (psImage->dfULY > 0)
    1100           1 :                                              ? pszNorthPolarProjection
    1101             :                                              : pszSouthPolarProjection;
    1102             : 
    1103           1 :         oSRS_AEQD.importFromWkt(pszPolarProjection);
    1104             : 
    1105           1 :         oSRS_WGS84.SetWellKnownGeogCS("WGS84");
    1106           1 :         oSRS_WGS84.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1107             : 
    1108           1 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    1109             :         OGRCoordinateTransformationH hCT =
    1110           1 :             (OGRCoordinateTransformationH)OGRCreateCoordinateTransformation(
    1111             :                 &oSRS_WGS84, &oSRS_AEQD);
    1112           1 :         CPLPopErrorHandler();
    1113           1 :         if (hCT)
    1114             :         {
    1115           1 :             double dfULX_AEQD = psImage->dfULX;
    1116           1 :             double dfULY_AEQD = psImage->dfULY;
    1117           1 :             double dfURX_AEQD = psImage->dfURX;
    1118           1 :             double dfURY_AEQD = psImage->dfURY;
    1119           1 :             double dfLLX_AEQD = psImage->dfLLX;
    1120           1 :             double dfLLY_AEQD = psImage->dfLLY;
    1121           1 :             double dfLRX_AEQD = psImage->dfLRX;
    1122           1 :             double dfLRY_AEQD = psImage->dfLRY;
    1123           1 :             double z = 0;
    1124           1 :             int bSuccess = TRUE;
    1125           1 :             bSuccess &= OCTTransform(hCT, 1, &dfULX_AEQD, &dfULY_AEQD, &z);
    1126           1 :             bSuccess &= OCTTransform(hCT, 1, &dfURX_AEQD, &dfURY_AEQD, &z);
    1127           1 :             bSuccess &= OCTTransform(hCT, 1, &dfLLX_AEQD, &dfLLY_AEQD, &z);
    1128           1 :             bSuccess &= OCTTransform(hCT, 1, &dfLRX_AEQD, &dfLRY_AEQD, &z);
    1129           1 :             if (bSuccess)
    1130             :             {
    1131             :                 /* Check that the coordinates of the 4 corners in Azimuthal
    1132             :                  * Equidistant projection */
    1133             :                 /* are a rectangle */
    1134           1 :                 if (fabs(dfULX_AEQD - dfLLX_AEQD) < 1e-6 * fabs(dfLLX_AEQD) &&
    1135           1 :                     fabs(dfURX_AEQD - dfLRX_AEQD) < 1e-6 * fabs(dfLRX_AEQD) &&
    1136           1 :                     fabs(dfULY_AEQD - dfURY_AEQD) < 1e-6 * fabs(dfURY_AEQD) &&
    1137           1 :                     fabs(dfLLY_AEQD - dfLRY_AEQD) < 1e-6 * fabs(dfLRY_AEQD))
    1138             :                 {
    1139           1 :                     poDS->m_oSRS = std::move(oSRS_AEQD);
    1140             : 
    1141           1 :                     poDS->bGotGeoTransform = TRUE;
    1142           1 :                     poDS->adfGeoTransform[0] = dfULX_AEQD;
    1143           1 :                     poDS->adfGeoTransform[1] =
    1144           1 :                         (dfURX_AEQD - dfULX_AEQD) / poDS->nRasterXSize;
    1145           1 :                     poDS->adfGeoTransform[2] = 0;
    1146           1 :                     poDS->adfGeoTransform[3] = dfULY_AEQD;
    1147           1 :                     poDS->adfGeoTransform[4] = 0;
    1148           1 :                     poDS->adfGeoTransform[5] =
    1149           1 :                         (dfLLY_AEQD - dfULY_AEQD) / poDS->nRasterYSize;
    1150             :                 }
    1151             :             }
    1152           1 :             OCTDestroyCoordinateTransformation(hCT);
    1153             :         }
    1154             :         else
    1155             :         {
    1156             :             // if we cannot instantiate the transformer, then we
    1157             :             // will at least attempt to record what we believe the
    1158             :             // natural coordinate system of the image is.  This is
    1159             :             // primarily used by ArcGIS (#3337)
    1160             : 
    1161           0 :             CPLErrorReset();
    1162             : 
    1163           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1164             :                      "Failed to instantiate coordinate system transformer, "
    1165             :                      "likely PROJ.DLL/libproj.so is not available.  Returning "
    1166             :                      "image corners as lat/long GCPs as a fallback.");
    1167             : 
    1168           0 :             char *pszAEQD = nullptr;
    1169           0 :             oSRS_AEQD.exportToWkt(&(pszAEQD));
    1170           0 :             poDS->SetMetadataItem("GCPPROJECTIONX", pszAEQD, "IMAGE_STRUCTURE");
    1171           0 :             CPLFree(pszAEQD);
    1172             :         }
    1173             :     }
    1174             : 
    1175             :     /* -------------------------------------------------------------------- */
    1176             :     /*      Do we have RPCs?                                                */
    1177             :     /* -------------------------------------------------------------------- */
    1178         750 :     bool bHasRPC00 = false;
    1179             :     NITFRPC00BInfo sRPCInfo;
    1180         750 :     memset(&sRPCInfo, 0,
    1181             :            sizeof(sRPCInfo)); /* To avoid warnings from not clever compilers */
    1182             : 
    1183         750 :     if (psImage && NITFReadRPC00B(psImage, &sRPCInfo) && sRPCInfo.SUCCESS)
    1184          55 :         bHasRPC00 = true;
    1185             : 
    1186             :     /* -------------------------------------------------------------------- */
    1187             :     /*      Do we have IGEOLO data that can be treated as a                 */
    1188             :     /*      geotransform?  Our approach should support images in an         */
    1189             :     /*      affine rotated frame of reference.                              */
    1190             :     /* -------------------------------------------------------------------- */
    1191         750 :     int nGCPCount = 0;
    1192         750 :     GDAL_GCP *psGCPs = nullptr;
    1193             : 
    1194         750 :     if (psImage && !poDS->bGotGeoTransform && psImage->chICORDS != ' ')
    1195             :     {
    1196         257 :         nGCPCount = 4;
    1197             : 
    1198             :         psGCPs = reinterpret_cast<GDAL_GCP *>(
    1199         257 :             CPLMalloc(sizeof(GDAL_GCP) * nGCPCount));
    1200         257 :         GDALInitGCPs(nGCPCount, psGCPs);
    1201             : 
    1202         257 :         if (psImage->bIsBoxCenterOfPixel)
    1203             :         {
    1204         213 :             psGCPs[0].dfGCPPixel = 0.5;
    1205         213 :             psGCPs[0].dfGCPLine = 0.5;
    1206         213 :             psGCPs[1].dfGCPPixel = poDS->nRasterXSize - 0.5;
    1207         213 :             psGCPs[1].dfGCPLine = 0.5;
    1208         213 :             psGCPs[2].dfGCPPixel = poDS->nRasterXSize - 0.5;
    1209         213 :             psGCPs[2].dfGCPLine = poDS->nRasterYSize - 0.5;
    1210         213 :             psGCPs[3].dfGCPPixel = 0.5;
    1211         213 :             psGCPs[3].dfGCPLine = poDS->nRasterYSize - 0.5;
    1212             :         }
    1213             :         else
    1214             :         {
    1215          44 :             psGCPs[0].dfGCPPixel = 0.0;
    1216          44 :             psGCPs[0].dfGCPLine = 0.0;
    1217          44 :             psGCPs[1].dfGCPPixel = poDS->nRasterXSize;
    1218          44 :             psGCPs[1].dfGCPLine = 0.0;
    1219          44 :             psGCPs[2].dfGCPPixel = poDS->nRasterXSize;
    1220          44 :             psGCPs[2].dfGCPLine = poDS->nRasterYSize;
    1221          44 :             psGCPs[3].dfGCPPixel = 0.0;
    1222          44 :             psGCPs[3].dfGCPLine = poDS->nRasterYSize;
    1223             :         }
    1224             : 
    1225         257 :         psGCPs[0].dfGCPX = psImage->dfULX;
    1226         257 :         psGCPs[0].dfGCPY = psImage->dfULY;
    1227             : 
    1228         257 :         psGCPs[1].dfGCPX = psImage->dfURX;
    1229         257 :         psGCPs[1].dfGCPY = psImage->dfURY;
    1230             : 
    1231         257 :         psGCPs[2].dfGCPX = psImage->dfLRX;
    1232         257 :         psGCPs[2].dfGCPY = psImage->dfLRY;
    1233             : 
    1234         257 :         psGCPs[3].dfGCPX = psImage->dfLLX;
    1235         257 :         psGCPs[3].dfGCPY = psImage->dfLLY;
    1236             : 
    1237             : /* -------------------------------------------------------------------- */
    1238             : /*      ESRI desires to use the RPCs to produce a denser and more       */
    1239             : /*      accurate set of GCPs in this case.  Details are unclear at      */
    1240             : /*      this time.                                                      */
    1241             : /* -------------------------------------------------------------------- */
    1242             : #ifdef ESRI_BUILD
    1243             :         if (bHasRPC00 &&
    1244             :             ((psImage->chICORDS == 'G') || (psImage->chICORDS == 'C')))
    1245             :         {
    1246             :             if (nGCPCount == 4)
    1247             :                 NITFDensifyGCPs(&psGCPs, &nGCPCount);
    1248             : 
    1249             :             NITFUpdateGCPsWithRPC(&sRPCInfo, psGCPs, &nGCPCount);
    1250             :         }
    1251             : #endif /* def ESRI_BUILD */
    1252             :     }
    1253             : 
    1254             :     /* -------------------------------------------------------------------- */
    1255             :     /*      Convert the GCPs into a geotransform definition, if possible.   */
    1256             :     /* -------------------------------------------------------------------- */
    1257         750 :     if (!psImage)
    1258             :     {
    1259             :         /* nothing */
    1260             :     }
    1261        1002 :     else if (poDS->bGotGeoTransform == FALSE && nGCPCount > 0 &&
    1262         257 :              GDALGCPsToGeoTransform(nGCPCount, psGCPs, poDS->adfGeoTransform,
    1263             :                                     FALSE))
    1264             :     {
    1265         178 :         poDS->bGotGeoTransform = TRUE;
    1266             :     }
    1267             : 
    1268             :     /* -------------------------------------------------------------------- */
    1269             :     /*      If we have IGEOLO that isn't north up, return it as GCPs.       */
    1270             :     /* -------------------------------------------------------------------- */
    1271         567 :     else if ((psImage->dfULX != 0 || psImage->dfURX != 0 ||
    1272         562 :               psImage->dfLRX != 0 || psImage->dfLLX != 0) &&
    1273           5 :              psImage->chICORDS != ' ' && (poDS->bGotGeoTransform == FALSE) &&
    1274             :              nGCPCount >= 4)
    1275             :     {
    1276           4 :         CPLDebug("GDAL",
    1277             :                  "NITFDataset::Open() was not able to derive a first order\n"
    1278             :                  "geotransform.  It will be returned as GCPs.");
    1279             : 
    1280           4 :         poDS->nGCPCount = nGCPCount;
    1281           4 :         poDS->pasGCPList = psGCPs;
    1282             : 
    1283           4 :         psGCPs = nullptr;
    1284           4 :         nGCPCount = 0;
    1285             : 
    1286           4 :         CPLFree(poDS->pasGCPList[0].pszId);
    1287           4 :         poDS->pasGCPList[0].pszId = CPLStrdup("UpperLeft");
    1288             : 
    1289           4 :         CPLFree(poDS->pasGCPList[1].pszId);
    1290           4 :         poDS->pasGCPList[1].pszId = CPLStrdup("UpperRight");
    1291             : 
    1292           4 :         CPLFree(poDS->pasGCPList[2].pszId);
    1293           4 :         poDS->pasGCPList[2].pszId = CPLStrdup("LowerRight");
    1294             : 
    1295           4 :         CPLFree(poDS->pasGCPList[3].pszId);
    1296           4 :         poDS->pasGCPList[3].pszId = CPLStrdup("LowerLeft");
    1297             : 
    1298           4 :         poDS->m_oGCPSRS = poDS->m_oSRS;
    1299             :     }
    1300             : 
    1301             :     // This cleans up the original copy of the GCPs used to test if
    1302             :     // this IGEOLO could be used for a geotransform if we did not
    1303             :     // steal the to use as primary gcps.
    1304         750 :     if (nGCPCount > 0)
    1305             :     {
    1306         253 :         GDALDeinitGCPs(nGCPCount, psGCPs);
    1307         253 :         CPLFree(psGCPs);
    1308             :     }
    1309             : 
    1310             :     /* -------------------------------------------------------------------- */
    1311             :     /*      Do we have PRJPSB and MAPLOB TREs to get better                 */
    1312             :     /*      georeferencing from?                                            */
    1313             :     /* -------------------------------------------------------------------- */
    1314         750 :     if (psImage)
    1315         745 :         poDS->CheckGeoSDEInfo();
    1316             : 
    1317             :     /* -------------------------------------------------------------------- */
    1318             :     /*      Do we have metadata.                                            */
    1319             :     /* -------------------------------------------------------------------- */
    1320             : 
    1321             :     // File and Image level metadata.
    1322         750 :     char **papszMergedMD = CSLDuplicate(poDS->psFile->papszMetadata);
    1323             : 
    1324         750 :     if (psImage)
    1325             :     {
    1326         745 :         papszMergedMD = CSLInsertStrings(papszMergedMD, CSLCount(papszMergedMD),
    1327         745 :                                          psImage->papszMetadata);
    1328             : 
    1329             :         // Comments.
    1330         745 :         if (psImage->pszComments != nullptr &&
    1331         745 :             strlen(psImage->pszComments) != 0)
    1332           8 :             papszMergedMD = CSLSetNameValue(
    1333           8 :                 papszMergedMD, "NITF_IMAGE_COMMENTS", psImage->pszComments);
    1334             : 
    1335             :         // Compression code.
    1336             :         papszMergedMD =
    1337         745 :             CSLSetNameValue(papszMergedMD, "NITF_IC", psImage->szIC);
    1338             : 
    1339             :         // IMODE
    1340             :         char szIMODE[2];
    1341         745 :         szIMODE[0] = psImage->chIMODE;
    1342         745 :         szIMODE[1] = '\0';
    1343         745 :         papszMergedMD = CSLSetNameValue(papszMergedMD, "NITF_IMODE", szIMODE);
    1344             : 
    1345             :         // ILOC/Attachment info
    1346         745 :         if (psImage->nIDLVL != 0)
    1347             :         {
    1348         745 :             NITFSegmentInfo *psSegInfo =
    1349         745 :                 psFile->pasSegmentInfo + psImage->iSegment;
    1350             : 
    1351             :             papszMergedMD =
    1352         745 :                 CSLSetNameValue(papszMergedMD, "NITF_IDLVL",
    1353        1490 :                                 CPLString().Printf("%d", psImage->nIDLVL));
    1354             :             papszMergedMD =
    1355         745 :                 CSLSetNameValue(papszMergedMD, "NITF_IALVL",
    1356        1490 :                                 CPLString().Printf("%d", psImage->nIALVL));
    1357             :             papszMergedMD =
    1358         745 :                 CSLSetNameValue(papszMergedMD, "NITF_ILOC_ROW",
    1359        1490 :                                 CPLString().Printf("%d", psImage->nILOCRow));
    1360             :             papszMergedMD =
    1361         745 :                 CSLSetNameValue(papszMergedMD, "NITF_ILOC_COLUMN",
    1362        1490 :                                 CPLString().Printf("%d", psImage->nILOCColumn));
    1363             :             papszMergedMD =
    1364         745 :                 CSLSetNameValue(papszMergedMD, "NITF_CCS_ROW",
    1365        1490 :                                 CPLString().Printf("%d", psSegInfo->nCCS_R));
    1366             :             papszMergedMD =
    1367         745 :                 CSLSetNameValue(papszMergedMD, "NITF_CCS_COLUMN",
    1368        1490 :                                 CPLString().Printf("%d", psSegInfo->nCCS_C));
    1369             :             papszMergedMD =
    1370         745 :                 CSLSetNameValue(papszMergedMD, "NITF_IMAG", psImage->szIMAG);
    1371             :         }
    1372             : 
    1373             :         papszMergedMD =
    1374         745 :             NITFGenericMetadataRead(papszMergedMD, psFile, psImage, nullptr);
    1375             : 
    1376             :         // BLOCKA
    1377         745 :         char **papszTRE_MD = NITFReadBLOCKA(psImage);
    1378         745 :         if (papszTRE_MD != nullptr)
    1379             :         {
    1380          22 :             papszMergedMD = CSLInsertStrings(
    1381             :                 papszMergedMD, CSLCount(papszTRE_MD), papszTRE_MD);
    1382          22 :             CSLDestroy(papszTRE_MD);
    1383             :         }
    1384             :     }
    1385             : 
    1386             : #ifdef ESRI_BUILD
    1387             :     // Extract ESRI generic metadata.
    1388             :     char **papszESRI_MD = ExtractEsriMD(papszMergedMD);
    1389             :     if (papszESRI_MD != NULL)
    1390             :     {
    1391             :         papszMergedMD = CSLInsertStrings(papszMergedMD, CSLCount(papszESRI_MD),
    1392             :                                          papszESRI_MD);
    1393             :         CSLDestroy(papszESRI_MD);
    1394             :     }
    1395             : #endif
    1396             : 
    1397         750 :     poDS->SetMetadata(papszMergedMD);
    1398         750 :     CSLDestroy(papszMergedMD);
    1399             : 
    1400             :     /* -------------------------------------------------------------------- */
    1401             :     /*      Image structure metadata.                                       */
    1402             :     /* -------------------------------------------------------------------- */
    1403         750 :     if (psImage == nullptr)
    1404             :         /* do nothing */;
    1405         745 :     else if (psImage->szIC[1] == '1')
    1406           2 :         poDS->SetMetadataItem("COMPRESSION", "BILEVEL", "IMAGE_STRUCTURE");
    1407         743 :     else if (psImage->szIC[1] == '2')
    1408           0 :         poDS->SetMetadataItem("COMPRESSION", "ARIDPCM", "IMAGE_STRUCTURE");
    1409         743 :     else if (psImage->szIC[1] == '3')
    1410          31 :         poDS->SetMetadataItem("COMPRESSION", "JPEG", "IMAGE_STRUCTURE");
    1411         712 :     else if (psImage->szIC[1] == '4')
    1412          24 :         poDS->SetMetadataItem("COMPRESSION", "VECTOR QUANTIZATION",
    1413          24 :                               "IMAGE_STRUCTURE");
    1414         688 :     else if (psImage->szIC[1] == '5')
    1415           0 :         poDS->SetMetadataItem("COMPRESSION", "LOSSLESS JPEG",
    1416           0 :                               "IMAGE_STRUCTURE");
    1417         688 :     else if (psImage->szIC[1] == '8')
    1418          37 :         poDS->SetMetadataItem("COMPRESSION", "JPEG2000", "IMAGE_STRUCTURE");
    1419             : 
    1420             :     /* -------------------------------------------------------------------- */
    1421             :     /*      Do we have RPC info.                                            */
    1422             :     /* -------------------------------------------------------------------- */
    1423             : 
    1424             :     // get _rpc.txt file
    1425         750 :     const char *pszDirName = CPLGetDirname(pszFilename);
    1426         750 :     const char *pszBaseName = CPLGetBasename(pszFilename);
    1427             :     const char *pszRPCTXTFilename =
    1428         750 :         CPLFormFilename(pszDirName, CPLSPrintf("%s_rpc", pszBaseName), "txt");
    1429         750 :     if (CPLCheckForFile((char *)pszRPCTXTFilename,
    1430         750 :                         poOpenInfo->GetSiblingFiles()))
    1431             :     {
    1432           4 :         poDS->m_osRPCTXTFilename = pszRPCTXTFilename;
    1433             :     }
    1434             :     else
    1435             :     {
    1436         746 :         pszRPCTXTFilename = CPLFormFilename(
    1437             :             pszDirName, CPLSPrintf("%s_RPC", pszBaseName), "TXT");
    1438         746 :         if (CPLCheckForFile((char *)pszRPCTXTFilename,
    1439         746 :                             poOpenInfo->GetSiblingFiles()))
    1440             :         {
    1441           0 :             poDS->m_osRPCTXTFilename = pszRPCTXTFilename;
    1442             :         }
    1443             :     }
    1444         750 :     bool bHasLoadedRPCTXT = false;
    1445         750 :     if (!poDS->m_osRPCTXTFilename.empty())
    1446             :     {
    1447           4 :         char **papszMD = GDALLoadRPCFile(poDS->m_osRPCTXTFilename);
    1448           4 :         if (papszMD != nullptr)
    1449             :         {
    1450           4 :             bHasLoadedRPCTXT = true;
    1451           4 :             poDS->SetMetadata(papszMD, "RPC");
    1452           4 :             CSLDestroy(papszMD);
    1453             :         }
    1454             :         else
    1455             :         {
    1456           0 :             poDS->m_osRPCTXTFilename.clear();
    1457             :         }
    1458             :     }
    1459             : 
    1460         750 :     if (psImage && bHasRPC00 && !bHasLoadedRPCTXT)
    1461             :     {
    1462             :         char szValue[1280];
    1463             : 
    1464          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.ERR_BIAS);
    1465          51 :         poDS->SetMetadataItem("ERR_BIAS", szValue, "RPC");
    1466             : 
    1467          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.ERR_RAND);
    1468          51 :         poDS->SetMetadataItem("ERR_RAND", szValue, "RPC");
    1469             : 
    1470          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LINE_OFF);
    1471          51 :         poDS->SetMetadataItem("LINE_OFF", szValue, "RPC");
    1472             : 
    1473          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LINE_SCALE);
    1474          51 :         poDS->SetMetadataItem("LINE_SCALE", szValue, "RPC");
    1475             : 
    1476          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.SAMP_OFF);
    1477          51 :         poDS->SetMetadataItem("SAMP_OFF", szValue, "RPC");
    1478             : 
    1479          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.SAMP_SCALE);
    1480          51 :         poDS->SetMetadataItem("SAMP_SCALE", szValue, "RPC");
    1481             : 
    1482          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LONG_OFF);
    1483          51 :         poDS->SetMetadataItem("LONG_OFF", szValue, "RPC");
    1484             : 
    1485          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LONG_SCALE);
    1486          51 :         poDS->SetMetadataItem("LONG_SCALE", szValue, "RPC");
    1487             : 
    1488          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LAT_OFF);
    1489          51 :         poDS->SetMetadataItem("LAT_OFF", szValue, "RPC");
    1490             : 
    1491          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.LAT_SCALE);
    1492          51 :         poDS->SetMetadataItem("LAT_SCALE", szValue, "RPC");
    1493             : 
    1494          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.HEIGHT_OFF);
    1495          51 :         poDS->SetMetadataItem("HEIGHT_OFF", szValue, "RPC");
    1496             : 
    1497          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sRPCInfo.HEIGHT_SCALE);
    1498          51 :         poDS->SetMetadataItem("HEIGHT_SCALE", szValue, "RPC");
    1499             : 
    1500          51 :         szValue[0] = '\0';
    1501        1071 :         for (int i = 0; i < 20; i++)
    1502        1020 :             CPLsnprintf(szValue + strlen(szValue),
    1503        1020 :                         sizeof(szValue) - strlen(szValue), "%.16g ",
    1504             :                         sRPCInfo.LINE_NUM_COEFF[i]);
    1505          51 :         poDS->SetMetadataItem("LINE_NUM_COEFF", szValue, "RPC");
    1506             : 
    1507          51 :         szValue[0] = '\0';
    1508        1071 :         for (int i = 0; i < 20; i++)
    1509        1020 :             CPLsnprintf(szValue + strlen(szValue),
    1510        1020 :                         sizeof(szValue) - strlen(szValue), "%.16g ",
    1511             :                         sRPCInfo.LINE_DEN_COEFF[i]);
    1512          51 :         poDS->SetMetadataItem("LINE_DEN_COEFF", szValue, "RPC");
    1513             : 
    1514          51 :         szValue[0] = '\0';
    1515        1071 :         for (int i = 0; i < 20; i++)
    1516        1020 :             CPLsnprintf(szValue + strlen(szValue),
    1517        1020 :                         sizeof(szValue) - strlen(szValue), "%.16g ",
    1518             :                         sRPCInfo.SAMP_NUM_COEFF[i]);
    1519          51 :         poDS->SetMetadataItem("SAMP_NUM_COEFF", szValue, "RPC");
    1520             : 
    1521          51 :         szValue[0] = '\0';
    1522        1071 :         for (int i = 0; i < 20; i++)
    1523        1020 :             CPLsnprintf(szValue + strlen(szValue),
    1524        1020 :                         sizeof(szValue) - strlen(szValue), "%.16g ",
    1525             :                         sRPCInfo.SAMP_DEN_COEFF[i]);
    1526          51 :         poDS->SetMetadataItem("SAMP_DEN_COEFF", szValue, "RPC");
    1527             : 
    1528          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g",
    1529          51 :                     sRPCInfo.LONG_OFF - sRPCInfo.LONG_SCALE);
    1530          51 :         poDS->SetMetadataItem("MIN_LONG", szValue, "RPC");
    1531             : 
    1532          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g",
    1533          51 :                     sRPCInfo.LONG_OFF + sRPCInfo.LONG_SCALE);
    1534          51 :         poDS->SetMetadataItem("MAX_LONG", szValue, "RPC");
    1535             : 
    1536          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g",
    1537          51 :                     sRPCInfo.LAT_OFF - sRPCInfo.LAT_SCALE);
    1538          51 :         poDS->SetMetadataItem("MIN_LAT", szValue, "RPC");
    1539             : 
    1540          51 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g",
    1541          51 :                     sRPCInfo.LAT_OFF + sRPCInfo.LAT_SCALE);
    1542          51 :         poDS->SetMetadataItem("MAX_LAT", szValue, "RPC");
    1543             :     }
    1544             : 
    1545             :     /* -------------------------------------------------------------------- */
    1546             :     /*      Do we have Chip info?                                            */
    1547             :     /* -------------------------------------------------------------------- */
    1548             :     NITFICHIPBInfo sChipInfo;
    1549             : 
    1550         753 :     if (psImage && NITFReadICHIPB(psImage, &sChipInfo) &&
    1551           3 :         sChipInfo.XFRM_FLAG == 0)
    1552             :     {
    1553             :         char szValue[1280];
    1554             : 
    1555           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.SCALE_FACTOR);
    1556           3 :         poDS->SetMetadataItem("ICHIP_SCALE_FACTOR", szValue);
    1557             : 
    1558             :         // TODO: Why do these two not use CPLsnprintf?
    1559           3 :         snprintf(szValue, sizeof(szValue), "%d", sChipInfo.ANAMORPH_CORR);
    1560           3 :         poDS->SetMetadataItem("ICHIP_ANAMORPH_CORR", szValue);
    1561             : 
    1562           3 :         snprintf(szValue, sizeof(szValue), "%d", sChipInfo.SCANBLK_NUM);
    1563           3 :         poDS->SetMetadataItem("ICHIP_SCANBLK_NUM", szValue);
    1564             : 
    1565           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_ROW_11);
    1566           3 :         poDS->SetMetadataItem("ICHIP_OP_ROW_11", szValue);
    1567             : 
    1568           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_COL_11);
    1569           3 :         poDS->SetMetadataItem("ICHIP_OP_COL_11", szValue);
    1570             : 
    1571           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_ROW_12);
    1572           3 :         poDS->SetMetadataItem("ICHIP_OP_ROW_12", szValue);
    1573             : 
    1574           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_COL_12);
    1575           3 :         poDS->SetMetadataItem("ICHIP_OP_COL_12", szValue);
    1576             : 
    1577           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_ROW_21);
    1578           3 :         poDS->SetMetadataItem("ICHIP_OP_ROW_21", szValue);
    1579             : 
    1580           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_COL_21);
    1581           3 :         poDS->SetMetadataItem("ICHIP_OP_COL_21", szValue);
    1582             : 
    1583           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_ROW_22);
    1584           3 :         poDS->SetMetadataItem("ICHIP_OP_ROW_22", szValue);
    1585             : 
    1586           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.OP_COL_22);
    1587           3 :         poDS->SetMetadataItem("ICHIP_OP_COL_22", szValue);
    1588             : 
    1589           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_ROW_11);
    1590           3 :         poDS->SetMetadataItem("ICHIP_FI_ROW_11", szValue);
    1591             : 
    1592           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_COL_11);
    1593           3 :         poDS->SetMetadataItem("ICHIP_FI_COL_11", szValue);
    1594             : 
    1595           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_ROW_12);
    1596           3 :         poDS->SetMetadataItem("ICHIP_FI_ROW_12", szValue);
    1597             : 
    1598           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_COL_12);
    1599           3 :         poDS->SetMetadataItem("ICHIP_FI_COL_12", szValue);
    1600             : 
    1601           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_ROW_21);
    1602           3 :         poDS->SetMetadataItem("ICHIP_FI_ROW_21", szValue);
    1603             : 
    1604           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_COL_21);
    1605           3 :         poDS->SetMetadataItem("ICHIP_FI_COL_21", szValue);
    1606             : 
    1607           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_ROW_22);
    1608           3 :         poDS->SetMetadataItem("ICHIP_FI_ROW_22", szValue);
    1609             : 
    1610           3 :         CPLsnprintf(szValue, sizeof(szValue), "%.16g", sChipInfo.FI_COL_22);
    1611           3 :         poDS->SetMetadataItem("ICHIP_FI_COL_22", szValue);
    1612             : 
    1613             :         // Why not CPLsnprintf?
    1614           3 :         snprintf(szValue, sizeof(szValue), "%d", sChipInfo.FI_ROW);
    1615           3 :         poDS->SetMetadataItem("ICHIP_FI_ROW", szValue);
    1616             : 
    1617           3 :         snprintf(szValue, sizeof(szValue), "%d", sChipInfo.FI_COL);
    1618           3 :         poDS->SetMetadataItem("ICHIP_FI_COL", szValue);
    1619             :     }
    1620             : 
    1621         750 :     const NITFSeries *series = NITFGetSeriesInfo(pszFilename);
    1622         750 :     if (series)
    1623             :     {
    1624          40 :         poDS->SetMetadataItem("NITF_SERIES_ABBREVIATION",
    1625          40 :                               (series->abbreviation) ? series->abbreviation
    1626          40 :                                                      : "Unknown");
    1627          40 :         poDS->SetMetadataItem("NITF_SERIES_NAME",
    1628          40 :                               (series->name) ? series->name : "Unknown");
    1629             :     }
    1630             : 
    1631             :     /* -------------------------------------------------------------------- */
    1632             :     /*      If there are multiple image segments, and no specific one is    */
    1633             :     /*      asker for, then setup the subdataset metadata.                  */
    1634             :     /* -------------------------------------------------------------------- */
    1635         750 :     int nSubDSCount = 0;
    1636             : 
    1637             :     {
    1638         750 :         char **papszSubdatasets = nullptr;
    1639             : 
    1640       11572 :         for (iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++)
    1641             :         {
    1642       10822 :             if (EQUAL(psFile->pasSegmentInfo[iSegment].szSegmentType, "IM"))
    1643             :             {
    1644       21520 :                 CPLString oName;
    1645       10760 :                 CPLString oValue;
    1646             : 
    1647       10760 :                 if (nIMIndex == -1)
    1648             :                 {
    1649        1566 :                     oName.Printf("SUBDATASET_%d_NAME", nSubDSCount + 1);
    1650        1566 :                     oValue.Printf("NITF_IM:%d:%s", nSubDSCount, pszFilename);
    1651             :                     papszSubdatasets =
    1652        1566 :                         CSLSetNameValue(papszSubdatasets, oName, oValue);
    1653             : 
    1654        1566 :                     oName.Printf("SUBDATASET_%d_DESC", nSubDSCount + 1);
    1655             :                     oValue.Printf("Image %d of %s", nSubDSCount + 1,
    1656        1566 :                                   pszFilename);
    1657             :                     papszSubdatasets =
    1658        1566 :                         CSLSetNameValue(papszSubdatasets, oName, oValue);
    1659             :                 }
    1660             : 
    1661       10760 :                 nSubDSCount++;
    1662             :             }
    1663             :         }
    1664             : 
    1665         750 :         if (nIMIndex == -1 && nSubDSCount > 1)
    1666             :         {
    1667          10 :             poDS->GDALMajorObject::SetMetadata(papszSubdatasets, "SUBDATASETS");
    1668             :         }
    1669             : 
    1670         750 :         CSLDestroy(papszSubdatasets);
    1671             :     }
    1672             : 
    1673             :     /* -------------------------------------------------------------------- */
    1674             :     /*      Initialize any PAM information.                                 */
    1675             :     /* -------------------------------------------------------------------- */
    1676         750 :     poDS->SetDescription(poOpenInfo->pszFilename);
    1677         750 :     poDS->SetPhysicalFilename(pszFilename);
    1678             : 
    1679         750 :     if (nSubDSCount > 1 || nIMIndex != -1)
    1680             :     {
    1681         198 :         if (nIMIndex == -1)
    1682             :         {
    1683          10 :             nIMIndex = 0;
    1684             :         }
    1685         188 :         else if (nIMIndex == 0 && nSubDSCount == 1)
    1686             :         {
    1687             :             // If subdataset 0 is explicitly specified, and there's a single
    1688             :             // subdataset, and that PAM .aux.xml doesn't have a Subdataset node,
    1689             :             // then don't set the subdataset name to get metadata from the
    1690             :             // top PAM node.
    1691         160 :             const char *pszPAMFilename = poDS->BuildPamFilename();
    1692             :             VSIStatBufL sStatBuf;
    1693         320 :             if (pszPAMFilename != nullptr &&
    1694         160 :                 VSIStatExL(pszPAMFilename, &sStatBuf,
    1695         320 :                            VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
    1696           2 :                 VSI_ISREG(sStatBuf.st_mode))
    1697             :             {
    1698           4 :                 CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1699           2 :                 CPLXMLNode *psTree = CPLParseXMLFile(pszPAMFilename);
    1700           2 :                 if (psTree)
    1701             :                 {
    1702           2 :                     if (CPLGetXMLNode(psTree, "=PAMDataset.Subdataset") ==
    1703             :                         nullptr)
    1704             :                     {
    1705           1 :                         nIMIndex = -1;
    1706             :                     }
    1707             :                 }
    1708           2 :                 CPLDestroyXMLNode(psTree);
    1709             :             }
    1710             :         }
    1711             : 
    1712         198 :         if (nIMIndex >= 0)
    1713             :         {
    1714         197 :             poDS->SetSubdatasetName(CPLString().Printf("%d", nIMIndex));
    1715         198 :         }
    1716             :     }
    1717         552 :     else if (/* nIMIndex == -1 && */ nSubDSCount == 1)
    1718             :     {
    1719             :         // GDAL 3.4.0 to 3.5.0 used to save the PAM metadata if a Subdataset
    1720             :         // node, even if there was one single subdataset.
    1721             :         // Detect that situation to automatically read it even if not explicitly
    1722             :         // specifying that single subdataset.
    1723         547 :         const char *pszPAMFilename = poDS->BuildPamFilename();
    1724             :         VSIStatBufL sStatBuf;
    1725        1094 :         if (pszPAMFilename != nullptr &&
    1726         547 :             VSIStatExL(pszPAMFilename, &sStatBuf,
    1727        1094 :                        VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
    1728          75 :             VSI_ISREG(sStatBuf.st_mode))
    1729             :         {
    1730         150 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1731          75 :             CPLXMLNode *psTree = CPLParseXMLFile(pszPAMFilename);
    1732          75 :             if (psTree)
    1733             :             {
    1734             :                 const auto psSubdatasetNode =
    1735          75 :                     CPLGetXMLNode(psTree, "=PAMDataset.Subdataset");
    1736          96 :                 if (psSubdatasetNode != nullptr &&
    1737          21 :                     strcmp(CPLGetXMLValue(psSubdatasetNode, "name", ""), "0") ==
    1738             :                         0)
    1739             :                 {
    1740          21 :                     poDS->SetSubdatasetName("0");
    1741          21 :                     poDS->SetPhysicalFilename(pszFilename);
    1742             :                 }
    1743          75 :                 CPLDestroyXMLNode(psTree);
    1744             :             }
    1745             :         }
    1746             :     }
    1747             : 
    1748         750 :     poDS->bInLoadXML = TRUE;
    1749         750 :     poDS->TryLoadXML(poOpenInfo->GetSiblingFiles());
    1750         750 :     poDS->bInLoadXML = FALSE;
    1751             : 
    1752             :     /* -------------------------------------------------------------------- */
    1753             :     /*      Do we have a special overview file?  If not, do we have         */
    1754             :     /*      RSets that should be treated as an overview file?               */
    1755             :     /* -------------------------------------------------------------------- */
    1756             :     const char *pszOverviewFile =
    1757         750 :         poDS->GetMetadataItem("OVERVIEW_FILE", "OVERVIEWS");
    1758             : 
    1759         750 :     if (pszOverviewFile == nullptr)
    1760             :     {
    1761         742 :         if (poDS->CheckForRSets(pszFilename, poOpenInfo->GetSiblingFiles()))
    1762           3 :             pszOverviewFile = poDS->osRSetVRT;
    1763             :     }
    1764             : 
    1765             :     /* -------------------------------------------------------------------- */
    1766             :     /*      If we have jpeg or jpeg2000 bands we may need to set the        */
    1767             :     /*      overview file on their dataset. (#3276)                         */
    1768             :     /* -------------------------------------------------------------------- */
    1769         750 :     GDALDataset *poSubDS = poDS->poJ2KDataset;
    1770         750 :     if (poDS->poJPEGDataset)
    1771          22 :         poSubDS = poDS->poJPEGDataset;
    1772             : 
    1773         750 :     if (poSubDS && pszOverviewFile != nullptr)
    1774             :     {
    1775           2 :         poSubDS->SetMetadataItem("OVERVIEW_FILE", pszOverviewFile, "OVERVIEWS");
    1776             :     }
    1777             : 
    1778             :     /* -------------------------------------------------------------------- */
    1779             :     /*      If we have jpeg, or jpeg2000 bands we may need to clear         */
    1780             :     /*      their PAM dirty flag too.                                       */
    1781             :     /* -------------------------------------------------------------------- */
    1782         787 :     if (poDS->poJ2KDataset != nullptr &&
    1783          37 :         (poDS->poJ2KDataset->GetMOFlags() & GMO_PAM_CLASS))
    1784          36 :         (reinterpret_cast<GDALPamDataset *>(poDS->poJ2KDataset))
    1785          36 :             ->SetPamFlags(
    1786          36 :                 (reinterpret_cast<GDALPamDataset *>(poDS->poJ2KDataset))
    1787          36 :                     ->GetPamFlags() &
    1788             :                 ~GPF_DIRTY);
    1789         772 :     if (poDS->poJPEGDataset != nullptr &&
    1790          22 :         (poDS->poJPEGDataset->GetMOFlags() & GMO_PAM_CLASS))
    1791          22 :         (reinterpret_cast<GDALPamDataset *>(poDS->poJPEGDataset))
    1792          22 :             ->SetPamFlags(
    1793          22 :                 (reinterpret_cast<GDALPamDataset *>(poDS->poJPEGDataset))
    1794          22 :                     ->GetPamFlags() &
    1795             :                 ~GPF_DIRTY);
    1796             : 
    1797             :     /* -------------------------------------------------------------------- */
    1798             :     /*      Check for overviews.                                            */
    1799             :     /* -------------------------------------------------------------------- */
    1800         750 :     if (!EQUAL(poOpenInfo->pszFilename, pszFilename))
    1801          20 :         poDS->oOvManager.Initialize(poDS, ":::VIRTUAL:::");
    1802             :     else
    1803        1460 :         poDS->oOvManager.Initialize(poDS, pszFilename,
    1804         730 :                                     poOpenInfo->GetSiblingFiles());
    1805             : 
    1806             :     /* If there are PAM overviews, don't expose the underlying JPEG dataset */
    1807             :     /* overviews (in case of monoblock C3) */
    1808         750 :     if (poDS->GetRasterCount() > 0 && poDS->GetRasterBand(1) != nullptr)
    1809         745 :         poDS->bExposeUnderlyingJPEGDatasetOverviews =
    1810         745 :             (reinterpret_cast<GDALPamRasterBand *>(poDS->GetRasterBand(1)))
    1811         745 :                 ->GDALPamRasterBand::GetOverviewCount() == 0;
    1812             : 
    1813         750 :     if (CPLFetchBool(poOpenInfo->papszOpenOptions, "VALIDATE", false))
    1814             :     {
    1815           8 :         if (!poDS->Validate() &&
    1816           4 :             CPLFetchBool(poOpenInfo->papszOpenOptions,
    1817             :                          "FAIL_IF_VALIDATION_ERROR", false))
    1818             :         {
    1819           2 :             delete poDS;
    1820           2 :             poDS = nullptr;
    1821             :         }
    1822             :     }
    1823             : 
    1824         750 :     return poDS;
    1825             : }
    1826             : 
    1827             : /************************************************************************/
    1828             : /*                             Validate()                               */
    1829             : /************************************************************************/
    1830             : 
    1831           4 : bool NITFDataset::Validate()
    1832             : {
    1833           4 :     bool bSuccess = InitializeTREMetadata(true);
    1834           4 :     if (!InitializeNITFDESs(true))
    1835           2 :         bSuccess = false;
    1836           4 :     return bSuccess;
    1837             : }
    1838             : 
    1839             : /************************************************************************/
    1840             : /*                            LoadDODDatum()                            */
    1841             : /*                                                                      */
    1842             : /*      Try to turn a US military datum name into a datum definition.   */
    1843             : /************************************************************************/
    1844             : 
    1845           3 : static OGRErr LoadDODDatum(OGRSpatialReference *poSRS, const char *pszDatumName)
    1846             : 
    1847             : {
    1848             :     /* -------------------------------------------------------------------- */
    1849             :     /*      The most common case...                                         */
    1850             :     /* -------------------------------------------------------------------- */
    1851           3 :     if (STARTS_WITH_CI(pszDatumName, "WGE "))
    1852             :     {
    1853           0 :         poSRS->SetWellKnownGeogCS("WGS84");
    1854           0 :         return OGRERR_NONE;
    1855             :     }
    1856             : 
    1857             : #if defined(USE_ONLY_EMBEDDED_RESOURCE_FILES) && !defined(EMBED_RESOURCE_FILES)
    1858             :     return OGRERR_FAILURE;
    1859             : #else
    1860             : 
    1861             :     /* -------------------------------------------------------------------- */
    1862             :     /*      All the rest we will try and load from gt_datum.csv             */
    1863             :     /*      (Geotrans datum file).                                          */
    1864             :     /* -------------------------------------------------------------------- */
    1865             :     char szExpanded[6];
    1866           3 :     const char *pszGTDatum = nullptr;
    1867           3 :     CPL_IGNORE_RET_VAL(pszGTDatum);
    1868             : #ifndef USE_ONLY_EMBEDDED_RESOURCE_FILES
    1869           3 :     pszGTDatum = CSVFilename("gt_datum.csv");
    1870             : #endif
    1871             : #ifdef EMBED_RESOURCE_FILES
    1872             :     std::string osTmpFilename;
    1873             :     // CSVFilename() returns the same content as pszFilename if it does not
    1874             :     // find the file.
    1875             :     if (!pszGTDatum || strcmp(pszGTDatum, "gt_datum.csv") == 0)
    1876             :     {
    1877             :         osTmpFilename = VSIMemGenerateHiddenFilename("gt_datum.csv");
    1878             :         const char *pszFileContent = NITFGetGTDatum();
    1879             :         VSIFCloseL(VSIFileFromMemBuffer(
    1880             :             osTmpFilename.c_str(),
    1881             :             const_cast<GByte *>(
    1882             :                 reinterpret_cast<const GByte *>(pszFileContent)),
    1883             :             static_cast<int>(strlen(pszFileContent)),
    1884             :             /* bTakeOwnership = */ false));
    1885             :         pszGTDatum = osTmpFilename.c_str();
    1886             :     }
    1887             : #endif
    1888             : 
    1889           3 :     strncpy(szExpanded, pszDatumName, 3);
    1890           3 :     szExpanded[3] = '\0';
    1891           3 :     if (pszDatumName[3] != ' ')
    1892             :     {
    1893             :         size_t nLen;
    1894           3 :         strcat(szExpanded, "-");
    1895           3 :         nLen = strlen(szExpanded);
    1896           3 :         szExpanded[nLen] = pszDatumName[3];
    1897           3 :         szExpanded[nLen + 1] = '\0';
    1898             :     }
    1899             : 
    1900             :     CPLString osDName =
    1901           6 :         CSVGetField(pszGTDatum, "CODE", szExpanded, CC_ApproxString, "NAME");
    1902           3 :     if (osDName.empty())
    1903             :     {
    1904           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1905             :                  "Failed to find datum %s/%s in gt_datum.csv.", pszDatumName,
    1906             :                  szExpanded);
    1907             : 
    1908             : #ifdef EMBED_RESOURCE_FILES
    1909             :         if (!osTmpFilename.empty())
    1910             :         {
    1911             :             CSVDeaccess(osTmpFilename.c_str());
    1912             :             VSIUnlink(osTmpFilename.c_str());
    1913             :         }
    1914             : #endif
    1915           0 :         return OGRERR_FAILURE;
    1916             :     }
    1917             : 
    1918             :     CPLString osEllipseCode = CSVGetField(pszGTDatum, "CODE", szExpanded,
    1919           6 :                                           CC_ApproxString, "ELLIPSOID");
    1920           3 :     double dfDeltaX = CPLAtof(
    1921             :         CSVGetField(pszGTDatum, "CODE", szExpanded, CC_ApproxString, "DELTAX"));
    1922           3 :     double dfDeltaY = CPLAtof(
    1923             :         CSVGetField(pszGTDatum, "CODE", szExpanded, CC_ApproxString, "DELTAY"));
    1924           3 :     double dfDeltaZ = CPLAtof(
    1925             :         CSVGetField(pszGTDatum, "CODE", szExpanded, CC_ApproxString, "DELTAZ"));
    1926             : 
    1927             : #ifdef EMBED_RESOURCE_FILES
    1928             :     if (!osTmpFilename.empty())
    1929             :     {
    1930             :         CSVDeaccess(osTmpFilename.c_str());
    1931             :         VSIUnlink(osTmpFilename.c_str());
    1932             :         osTmpFilename.clear();
    1933             :     }
    1934             : #endif
    1935             : 
    1936             :     /* -------------------------------------------------------------------- */
    1937             :     /*      Lookup the ellipse code.                                        */
    1938             :     /* -------------------------------------------------------------------- */
    1939           3 :     const char *pszGTEllipse = nullptr;
    1940           3 :     CPL_IGNORE_RET_VAL(pszGTEllipse);
    1941             : #ifndef USE_ONLY_EMBEDDED_RESOURCE_FILES
    1942           3 :     pszGTEllipse = CSVFilename("gt_ellips.csv");
    1943             : #endif
    1944             : 
    1945             : #ifdef EMBED_RESOURCE_FILES
    1946             :     // CSVFilename() returns the same content as pszFilename if it does not
    1947             :     // find the file.
    1948             :     if (!pszGTEllipse || strcmp(pszGTEllipse, "gt_ellips.csv") == 0)
    1949             :     {
    1950             :         osTmpFilename = VSIMemGenerateHiddenFilename("gt_ellips");
    1951             :         const char *pszFileContent = NITFGetGTEllips();
    1952             :         VSIFCloseL(VSIFileFromMemBuffer(
    1953             :             osTmpFilename.c_str(),
    1954             :             const_cast<GByte *>(
    1955             :                 reinterpret_cast<const GByte *>(pszFileContent)),
    1956             :             static_cast<int>(strlen(pszFileContent)),
    1957             :             /* bTakeOwnership = */ false));
    1958             :         pszGTEllipse = osTmpFilename.c_str();
    1959             :     }
    1960             : #endif
    1961             : 
    1962             :     CPLString osEName = CSVGetField(pszGTEllipse, "CODE", osEllipseCode,
    1963           6 :                                     CC_ApproxString, "NAME");
    1964           3 :     osEName = osEName.Trim();
    1965           3 :     if (osEName.empty())
    1966             :     {
    1967           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1968             :                  "Failed to find datum %s in gt_ellips.csv.",
    1969             :                  osEllipseCode.c_str());
    1970             : 
    1971             : #ifdef EMBED_RESOURCE_FILES
    1972             :         if (!osTmpFilename.empty())
    1973             :         {
    1974             :             CSVDeaccess(osTmpFilename.c_str());
    1975             :             VSIUnlink(osTmpFilename.c_str());
    1976             :         }
    1977             : #endif
    1978           0 :         return OGRERR_FAILURE;
    1979             :     }
    1980             : 
    1981           3 :     double dfA = CPLAtof(
    1982             :         CSVGetField(pszGTEllipse, "CODE", osEllipseCode, CC_ApproxString, "A"));
    1983           3 :     double dfInvF = CPLAtof(CSVGetField(pszGTEllipse, "CODE", osEllipseCode,
    1984             :                                         CC_ApproxString, "RF"));
    1985             : 
    1986             :     /* -------------------------------------------------------------------- */
    1987             :     /*      Create geographic coordinate system.                            */
    1988             :     /* -------------------------------------------------------------------- */
    1989           3 :     poSRS->SetGeogCS(osDName, osDName, osEName, dfA, dfInvF);
    1990             : 
    1991           3 :     poSRS->SetTOWGS84(dfDeltaX, dfDeltaY, dfDeltaZ);
    1992             : 
    1993             : #ifdef EMBED_RESOURCE_FILES
    1994             :     if (!osTmpFilename.empty())
    1995             :     {
    1996             :         CSVDeaccess(osTmpFilename.c_str());
    1997             :         VSIUnlink(osTmpFilename.c_str());
    1998             :         osTmpFilename.clear();
    1999             :     }
    2000             : #endif
    2001             : 
    2002           3 :     return OGRERR_NONE;
    2003             : #endif
    2004             : }
    2005             : 
    2006             : /************************************************************************/
    2007             : /*                          CheckGeoSDEInfo()                           */
    2008             : /*                                                                      */
    2009             : /*      Check for GeoSDE TREs (GEOPSB/PRJPSB and MAPLOB).  If we        */
    2010             : /*      have them, use them to override our coordinate system and       */
    2011             : /*      geotransform info.                                              */
    2012             : /************************************************************************/
    2013             : 
    2014         745 : void NITFDataset::CheckGeoSDEInfo()
    2015             : 
    2016             : {
    2017         745 :     if (!psImage)
    2018         742 :         return;
    2019             : 
    2020             :     /* -------------------------------------------------------------------- */
    2021             :     /*      Do we have the required TREs?                                   */
    2022             :     /* -------------------------------------------------------------------- */
    2023             :     int nGEOPSBSize, nPRJPSBSize, nMAPLOBSize;
    2024             : 
    2025             :     const char *pszGEOPSB =
    2026         745 :         NITFFindTRE(psFile->pachTRE, psFile->nTREBytes, "GEOPSB", &nGEOPSBSize);
    2027             :     const char *pszPRJPSB =
    2028         745 :         NITFFindTRE(psFile->pachTRE, psFile->nTREBytes, "PRJPSB", &nPRJPSBSize);
    2029         745 :     const char *pszMAPLOB = NITFFindTRE(psImage->pachTRE, psImage->nTREBytes,
    2030             :                                         "MAPLOB", &nMAPLOBSize);
    2031             : 
    2032         745 :     if (pszGEOPSB == nullptr || pszPRJPSB == nullptr || pszMAPLOB == nullptr)
    2033         742 :         return;
    2034             : 
    2035             :     /* -------------------------------------------------------------------- */
    2036             :     /*      Collect projection parameters.                                  */
    2037             :     /* -------------------------------------------------------------------- */
    2038             : 
    2039             :     char szParam[16];
    2040           3 :     if (nPRJPSBSize < 82 + 1)
    2041             :     {
    2042           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2043             :                  "Cannot read PRJPSB TRE. Not enough bytes");
    2044           0 :         return;
    2045             :     }
    2046           3 :     const int nParamCount = atoi(NITFGetField(szParam, pszPRJPSB, 82, 1));
    2047           3 :     if (nPRJPSBSize < 83 + 15 * nParamCount + 15 + 15)
    2048             :     {
    2049           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2050             :                  "Cannot read PRJPSB TRE. Not enough bytes");
    2051           0 :         return;
    2052             :     }
    2053             : 
    2054           3 :     double adfParam[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    2055           3 :     for (int i = 0; i < nParamCount; i++)
    2056           0 :         adfParam[i] =
    2057           0 :             CPLAtof(NITFGetField(szParam, pszPRJPSB, 83 + 15 * i, 15));
    2058             : 
    2059             :     const double dfFE =
    2060           3 :         CPLAtof(NITFGetField(szParam, pszPRJPSB, 83 + 15 * nParamCount, 15));
    2061           6 :     const double dfFN = CPLAtof(
    2062           3 :         NITFGetField(szParam, pszPRJPSB, 83 + 15 * nParamCount + 15, 15));
    2063             : 
    2064             :     /* -------------------------------------------------------------------- */
    2065             :     /*      Try to handle the projection.                                   */
    2066             :     /* -------------------------------------------------------------------- */
    2067           3 :     OGRSpatialReference oSRS;
    2068           3 :     oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2069             : 
    2070           3 :     if (STARTS_WITH_CI(pszPRJPSB + 80, "AC"))
    2071           3 :         oSRS.SetACEA(adfParam[1], adfParam[2], adfParam[3], adfParam[0], dfFE,
    2072             :                      dfFN);
    2073             : 
    2074           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "AK"))
    2075           0 :         oSRS.SetLAEA(adfParam[1], adfParam[0], dfFE, dfFN);
    2076             : 
    2077           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "AL"))
    2078           0 :         oSRS.SetAE(adfParam[1], adfParam[0], dfFE, dfFN);
    2079             : 
    2080           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "BF"))
    2081           0 :         oSRS.SetBonne(adfParam[1], adfParam[0], dfFE, dfFN);
    2082             : 
    2083           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "CP"))
    2084           0 :         oSRS.SetEquirectangular(adfParam[1], adfParam[0], dfFE, dfFN);
    2085             : 
    2086           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "CS"))
    2087           0 :         oSRS.SetCS(adfParam[1], adfParam[0], dfFE, dfFN);
    2088             : 
    2089           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "EF"))
    2090           0 :         oSRS.SetEckertIV(adfParam[0], dfFE, dfFN);
    2091             : 
    2092           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "ED"))
    2093           0 :         oSRS.SetEckertVI(adfParam[0], dfFE, dfFN);
    2094             : 
    2095           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "GN"))
    2096           0 :         oSRS.SetGnomonic(adfParam[1], adfParam[0], dfFE, dfFN);
    2097             : 
    2098           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "HX"))
    2099           0 :         oSRS.SetHOM2PNO(adfParam[1], adfParam[3], adfParam[2], adfParam[5],
    2100             :                         adfParam[4], adfParam[0], dfFE, dfFN);
    2101             : 
    2102           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "KA"))
    2103           0 :         oSRS.SetEC(adfParam[1], adfParam[2], adfParam[3], adfParam[0], dfFE,
    2104             :                    dfFN);
    2105             : 
    2106           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "LE"))
    2107           0 :         oSRS.SetLCC(adfParam[1], adfParam[2], adfParam[3], adfParam[0], dfFE,
    2108             :                     dfFN);
    2109             : 
    2110           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "LI"))
    2111           0 :         oSRS.SetCEA(adfParam[1], adfParam[0], dfFE, dfFN);
    2112             : 
    2113           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "MC"))
    2114           0 :         oSRS.SetMercator(adfParam[2], adfParam[1], 1.0, dfFE, dfFN);
    2115             : 
    2116           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "MH"))
    2117           0 :         oSRS.SetMC(0.0, adfParam[1], dfFE, dfFN);
    2118             : 
    2119           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "MP"))
    2120           0 :         oSRS.SetMollweide(adfParam[0], dfFE, dfFN);
    2121             : 
    2122           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "NT"))
    2123           0 :         oSRS.SetNZMG(adfParam[1], adfParam[0], dfFE, dfFN);
    2124             : 
    2125           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "OD"))
    2126           0 :         oSRS.SetOrthographic(adfParam[1], adfParam[0], dfFE, dfFN);
    2127             : 
    2128           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "PC"))
    2129           0 :         oSRS.SetPolyconic(adfParam[1], adfParam[0], dfFE, dfFN);
    2130             : 
    2131           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "PG"))
    2132           0 :         oSRS.SetPS(adfParam[1], adfParam[0], 1.0, dfFE, dfFN);
    2133             : 
    2134           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "RX"))
    2135           0 :         oSRS.SetRobinson(adfParam[0], dfFE, dfFN);
    2136             : 
    2137           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "SA"))
    2138           0 :         oSRS.SetSinusoidal(adfParam[0], dfFE, dfFN);
    2139             : 
    2140           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "TC"))
    2141           0 :         oSRS.SetTM(adfParam[2], adfParam[0], adfParam[1], dfFE, dfFN);
    2142             : 
    2143           0 :     else if (STARTS_WITH_CI(pszPRJPSB + 80, "VA"))
    2144           0 :         oSRS.SetVDG(adfParam[0], dfFE, dfFN);
    2145             : 
    2146             :     else
    2147             :     {
    2148             :         char szName[81];
    2149           0 :         oSRS.SetLocalCS(NITFGetField(szName, pszPRJPSB, 0, 80));
    2150             :     }
    2151             : 
    2152             :     /* -------------------------------------------------------------------- */
    2153             :     /*      Try to apply the datum.                                         */
    2154             :     /* -------------------------------------------------------------------- */
    2155           3 :     if (nGEOPSBSize < 86 + 4)
    2156             :     {
    2157           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2158             :                  "Cannot read GEOPSB TRE. Not enough bytes");
    2159           0 :         return;
    2160             :     }
    2161           3 :     LoadDODDatum(&oSRS, NITFGetField(szParam, pszGEOPSB, 86, 4));
    2162             : 
    2163             :     /* -------------------------------------------------------------------- */
    2164             :     /*      Get the geotransform                                            */
    2165             :     /* -------------------------------------------------------------------- */
    2166           3 :     if (nMAPLOBSize < 28 + 15)
    2167             :     {
    2168           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2169             :                  "Cannot read MAPLOB TRE. Not enough bytes");
    2170           0 :         return;
    2171             :     }
    2172             : 
    2173           3 :     double dfMeterPerUnit = 1.0;
    2174           3 :     if (STARTS_WITH_CI(pszMAPLOB + 0, "DM "))
    2175           0 :         dfMeterPerUnit = 0.1;
    2176           3 :     else if (STARTS_WITH_CI(pszMAPLOB + 0, "CM "))
    2177           0 :         dfMeterPerUnit = 0.01;
    2178           3 :     else if (STARTS_WITH_CI(pszMAPLOB + 0, "MM "))
    2179           0 :         dfMeterPerUnit = 0.001;
    2180           3 :     else if (STARTS_WITH_CI(pszMAPLOB + 0, "UM "))
    2181           0 :         dfMeterPerUnit = 0.000001;
    2182           3 :     else if (STARTS_WITH_CI(pszMAPLOB + 0, "KM "))
    2183           0 :         dfMeterPerUnit = 1000.0;
    2184           3 :     else if (STARTS_WITH_CI(pszMAPLOB + 0, "M  "))
    2185           3 :         dfMeterPerUnit = 1.0;
    2186             :     else
    2187             :     {
    2188           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    2189             :                  "MAPLOB Unit=%3.3s not recognized, geolocation may be wrong.",
    2190             :                  pszMAPLOB + 0);
    2191             :     }
    2192             : 
    2193             :     double adfGT[6];
    2194           3 :     adfGT[0] = CPLAtof(NITFGetField(szParam, pszMAPLOB, 13, 15));
    2195           3 :     adfGT[1] = CPLAtof(NITFGetField(szParam, pszMAPLOB, 3, 5)) * dfMeterPerUnit;
    2196           3 :     adfGT[2] = 0.0;
    2197           3 :     adfGT[3] = CPLAtof(NITFGetField(szParam, pszMAPLOB, 28, 15));
    2198           3 :     adfGT[4] = 0.0;
    2199           3 :     adfGT[5] =
    2200           3 :         -CPLAtof(NITFGetField(szParam, pszMAPLOB, 8, 5)) * dfMeterPerUnit;
    2201             : 
    2202             :     /* -------------------------------------------------------------------- */
    2203             :     /*      Apply back to dataset.                                          */
    2204             :     /* -------------------------------------------------------------------- */
    2205           3 :     m_oSRS = std::move(oSRS);
    2206             : 
    2207           3 :     memcpy(adfGeoTransform, adfGT, sizeof(double) * 6);
    2208           3 :     bGotGeoTransform = TRUE;
    2209             : }
    2210             : 
    2211             : /************************************************************************/
    2212             : /*                             AdviseRead()                             */
    2213             : /************************************************************************/
    2214             : 
    2215          17 : CPLErr NITFDataset::AdviseRead(int nXOff, int nYOff, int nXSize, int nYSize,
    2216             :                                int nBufXSize, int nBufYSize, GDALDataType eDT,
    2217             :                                int nBandCount, int *panBandList,
    2218             :                                char **papszOptions)
    2219             : 
    2220             : {
    2221             :     //go through GDALDataset::AdviseRead for the complex SAR
    2222          17 :     if (poJ2KDataset == nullptr || m_bHasComplexRasterBand)
    2223          15 :         return GDALDataset::AdviseRead(nXOff, nYOff, nXSize, nYSize, nBufXSize,
    2224             :                                        nBufYSize, eDT, nBandCount, panBandList,
    2225          15 :                                        papszOptions);
    2226           2 :     else if (poJPEGDataset != nullptr)
    2227           0 :         return poJPEGDataset->AdviseRead(nXOff, nYOff, nXSize, nYSize,
    2228             :                                          nBufXSize, nBufYSize, eDT, nBandCount,
    2229           0 :                                          panBandList, papszOptions);
    2230             :     else
    2231           2 :         return poJ2KDataset->AdviseRead(nXOff, nYOff, nXSize, nYSize, nBufXSize,
    2232             :                                         nBufYSize, eDT, nBandCount, panBandList,
    2233           2 :                                         papszOptions);
    2234             : }
    2235             : 
    2236             : /************************************************************************/
    2237             : /*                             IRasterIO()                              */
    2238             : /************************************************************************/
    2239             : 
    2240        1206 : CPLErr NITFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2241             :                               int nXSize, int nYSize, void *pData,
    2242             :                               int nBufXSize, int nBufYSize,
    2243             :                               GDALDataType eBufType, int nBandCount,
    2244             :                               BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    2245             :                               GSpacing nLineSpace, GSpacing nBandSpace,
    2246             :                               GDALRasterIOExtraArg *psExtraArg)
    2247             : 
    2248             : {
    2249             :     //go through GDALDataset::IRasterIO for the complex SAR
    2250        1206 :     if (poJ2KDataset != nullptr && !m_bHasComplexRasterBand)
    2251         101 :         return poJ2KDataset->RasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
    2252             :                                       pData, nBufXSize, nBufYSize, eBufType,
    2253             :                                       nBandCount, panBandMap, nPixelSpace,
    2254         101 :                                       nLineSpace, nBandSpace, psExtraArg);
    2255        1105 :     else if (poJPEGDataset != nullptr && !m_bHasComplexRasterBand)
    2256          64 :         return poJPEGDataset->RasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
    2257             :                                        pData, nBufXSize, nBufYSize, eBufType,
    2258             :                                        nBandCount, panBandMap, nPixelSpace,
    2259          64 :                                        nLineSpace, nBandSpace, psExtraArg);
    2260             :     else
    2261        1041 :         return GDALDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
    2262             :                                       pData, nBufXSize, nBufYSize, eBufType,
    2263             :                                       nBandCount, panBandMap, nPixelSpace,
    2264        1041 :                                       nLineSpace, nBandSpace, psExtraArg);
    2265             : }
    2266             : 
    2267             : /************************************************************************/
    2268             : /*                          GetGeoTransform()                           */
    2269             : /************************************************************************/
    2270             : 
    2271         218 : CPLErr NITFDataset::GetGeoTransform(double *padfGeoTransform)
    2272             : 
    2273             : {
    2274         218 :     memcpy(padfGeoTransform, adfGeoTransform, sizeof(double) * 6);
    2275             : 
    2276         218 :     if (bGotGeoTransform)
    2277         200 :         return CE_None;
    2278             : 
    2279          18 :     return GDALPamDataset::GetGeoTransform(padfGeoTransform);
    2280             : }
    2281             : 
    2282             : /************************************************************************/
    2283             : /*                          SetGeoTransform()                           */
    2284             : /************************************************************************/
    2285             : 
    2286         106 : CPLErr NITFDataset::SetGeoTransform(double *padfGeoTransform)
    2287             : 
    2288             : {
    2289         106 :     bGotGeoTransform = TRUE;
    2290             :     /* Valgrind would complain because SetGeoTransform() is called */
    2291             :     /* from SetProjection() with adfGeoTransform as argument */
    2292         106 :     if (adfGeoTransform != padfGeoTransform)
    2293          97 :         memcpy(adfGeoTransform, padfGeoTransform, sizeof(double) * 6);
    2294             : 
    2295         106 :     double dfIGEOLOULX = padfGeoTransform[0] + 0.5 * padfGeoTransform[1] +
    2296         106 :                          0.5 * padfGeoTransform[2];
    2297         106 :     double dfIGEOLOULY = padfGeoTransform[3] + 0.5 * padfGeoTransform[4] +
    2298         106 :                          0.5 * padfGeoTransform[5];
    2299         106 :     double dfIGEOLOURX = dfIGEOLOULX + padfGeoTransform[1] * (nRasterXSize - 1);
    2300         106 :     double dfIGEOLOURY = dfIGEOLOULY + padfGeoTransform[4] * (nRasterXSize - 1);
    2301         106 :     double dfIGEOLOLRX = dfIGEOLOULX +
    2302         106 :                          padfGeoTransform[1] * (nRasterXSize - 1) +
    2303         106 :                          padfGeoTransform[2] * (nRasterYSize - 1);
    2304         106 :     double dfIGEOLOLRY = dfIGEOLOULY +
    2305         106 :                          padfGeoTransform[4] * (nRasterXSize - 1) +
    2306         106 :                          padfGeoTransform[5] * (nRasterYSize - 1);
    2307         106 :     double dfIGEOLOLLX = dfIGEOLOULX + padfGeoTransform[2] * (nRasterYSize - 1);
    2308         106 :     double dfIGEOLOLLY = dfIGEOLOULY + padfGeoTransform[5] * (nRasterYSize - 1);
    2309             : 
    2310         211 :     if (psImage != nullptr &&
    2311         105 :         NITFWriteIGEOLO(psImage, psImage->chICORDS, psImage->nZone, dfIGEOLOULX,
    2312             :                         dfIGEOLOULY, dfIGEOLOURX, dfIGEOLOURY, dfIGEOLOLRX,
    2313             :                         dfIGEOLOLRY, dfIGEOLOLLX, dfIGEOLOLLY))
    2314          86 :         return CE_None;
    2315             : 
    2316          20 :     return GDALPamDataset::SetGeoTransform(padfGeoTransform);
    2317             : }
    2318             : 
    2319             : /************************************************************************/
    2320             : /*                               SetGCPs()                              */
    2321             : /************************************************************************/
    2322             : 
    2323           3 : CPLErr NITFDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
    2324             :                             const OGRSpatialReference *poGCPSRSIn)
    2325             : {
    2326           3 :     if (nGCPCountIn != 4)
    2327             :     {
    2328           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2329             :                  "NITF only supports writing 4 GCPs.");
    2330           0 :         return CE_Failure;
    2331             :     }
    2332             : 
    2333             :     /* Free previous GCPs */
    2334           3 :     GDALDeinitGCPs(nGCPCount, pasGCPList);
    2335           3 :     CPLFree(pasGCPList);
    2336             : 
    2337             :     /* Duplicate in GCPs */
    2338           3 :     nGCPCount = nGCPCountIn;
    2339           3 :     pasGCPList = GDALDuplicateGCPs(nGCPCount, pasGCPListIn);
    2340             : 
    2341           3 :     m_oGCPSRS.Clear();
    2342           3 :     if (poGCPSRSIn)
    2343           3 :         m_oGCPSRS = *poGCPSRSIn;
    2344             : 
    2345           3 :     int iUL = -1;
    2346           3 :     int iUR = -1;
    2347           3 :     int iLR = -1;
    2348           3 :     int iLL = -1;
    2349             : 
    2350             : #define EPS_GCP 1e-5
    2351          15 :     for (int i = 0; i < 4; i++)
    2352             :     {
    2353          12 :         if (fabs(pasGCPList[i].dfGCPPixel - 0.5) < EPS_GCP &&
    2354           6 :             fabs(pasGCPList[i].dfGCPLine - 0.5) < EPS_GCP)
    2355           3 :             iUL = i;
    2356             : 
    2357           9 :         else if (fabs(pasGCPList[i].dfGCPPixel - (nRasterXSize - 0.5)) <
    2358           6 :                      EPS_GCP &&
    2359           6 :                  fabs(pasGCPList[i].dfGCPLine - 0.5) < EPS_GCP)
    2360           3 :             iUR = i;
    2361             : 
    2362           6 :         else if (fabs(pasGCPList[i].dfGCPPixel - (nRasterXSize - 0.5)) <
    2363           3 :                      EPS_GCP &&
    2364           3 :                  fabs(pasGCPList[i].dfGCPLine - (nRasterYSize - 0.5)) < EPS_GCP)
    2365           3 :             iLR = i;
    2366             : 
    2367           3 :         else if (fabs(pasGCPList[i].dfGCPPixel - 0.5) < EPS_GCP &&
    2368           3 :                  fabs(pasGCPList[i].dfGCPLine - (nRasterYSize - 0.5)) < EPS_GCP)
    2369           3 :             iLL = i;
    2370             :     }
    2371             : 
    2372           3 :     if (iUL < 0 || iUR < 0 || iLR < 0 || iLL < 0)
    2373             :     {
    2374           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2375             :                  "The 4 GCPs image coordinates must be exactly "
    2376             :                  "at the *center* of the 4 corners of the image "
    2377             :                  "( (%.1f, %.1f), (%.1f %.1f), (%.1f %.1f), (%.1f %.1f) ).",
    2378           0 :                  0.5, 0.5, nRasterYSize - 0.5, 0.5, nRasterXSize - 0.5,
    2379           0 :                  nRasterYSize - 0.5, nRasterXSize - 0.5, 0.5);
    2380           0 :         return CE_Failure;
    2381             :     }
    2382             : 
    2383           3 :     double dfIGEOLOULX = pasGCPList[iUL].dfGCPX;
    2384           3 :     double dfIGEOLOULY = pasGCPList[iUL].dfGCPY;
    2385           3 :     double dfIGEOLOURX = pasGCPList[iUR].dfGCPX;
    2386           3 :     double dfIGEOLOURY = pasGCPList[iUR].dfGCPY;
    2387           3 :     double dfIGEOLOLRX = pasGCPList[iLR].dfGCPX;
    2388           3 :     double dfIGEOLOLRY = pasGCPList[iLR].dfGCPY;
    2389           3 :     double dfIGEOLOLLX = pasGCPList[iLL].dfGCPX;
    2390           3 :     double dfIGEOLOLLY = pasGCPList[iLL].dfGCPY;
    2391             : 
    2392             :     /* To recompute the zone */
    2393           6 :     OGRSpatialReference oSRSBackup = m_oSRS;
    2394           3 :     CPLErr eErr = SetSpatialRef(&m_oGCPSRS);
    2395           3 :     m_oSRS = std::move(oSRSBackup);
    2396             : 
    2397           3 :     if (eErr != CE_None)
    2398           0 :         return eErr;
    2399             : 
    2400           3 :     if (NITFWriteIGEOLO(psImage, psImage->chICORDS, psImage->nZone, dfIGEOLOULX,
    2401             :                         dfIGEOLOULY, dfIGEOLOURX, dfIGEOLOURY, dfIGEOLOLRX,
    2402           3 :                         dfIGEOLOLRY, dfIGEOLOLLX, dfIGEOLOLLY))
    2403           3 :         return CE_None;
    2404             : 
    2405           0 :     return CE_Failure;
    2406             : }
    2407             : 
    2408             : /************************************************************************/
    2409             : /*                          GetSpatialRef()                             */
    2410             : /************************************************************************/
    2411             : 
    2412         134 : const OGRSpatialReference *NITFDataset::GetSpatialRef() const
    2413             : 
    2414             : {
    2415         134 :     if (bGotGeoTransform)
    2416         120 :         return &m_oSRS;
    2417             : 
    2418          14 :     return GDALPamDataset::GetSpatialRef();
    2419             : }
    2420             : 
    2421             : /************************************************************************/
    2422             : /*                            SetSpatialRef()                           */
    2423             : /************************************************************************/
    2424             : 
    2425          31 : CPLErr NITFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    2426             : 
    2427             : {
    2428             :     int bNorth;
    2429          62 :     OGRSpatialReference oSRS, oSRS_WGS84;
    2430             : 
    2431          31 :     if (poSRS == nullptr)
    2432           0 :         return CE_Failure;
    2433             : 
    2434          31 :     oSRS_WGS84.SetWellKnownGeogCS("WGS84");
    2435          31 :     if (poSRS->IsSameGeogCS(&oSRS_WGS84) == FALSE)
    2436             :     {
    2437           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2438             :                  "NITF only supports WGS84 geographic and UTM projections.\n");
    2439           0 :         return CE_Failure;
    2440             :     }
    2441             : 
    2442          31 :     if (poSRS->IsGeographic() && poSRS->GetPrimeMeridian() == 0.0)
    2443             :     {
    2444          30 :         if (psImage->chICORDS != 'G' && psImage->chICORDS != 'D')
    2445             :         {
    2446          19 :             CPLError(CE_Failure, CPLE_NotSupported,
    2447             :                      "NITF file should have been created with creation option "
    2448             :                      "'ICORDS=G' (or 'ICORDS=D').\n");
    2449          19 :             return CE_Failure;
    2450             :         }
    2451             :     }
    2452           1 :     else if (poSRS->GetUTMZone(&bNorth) > 0)
    2453             :     {
    2454           1 :         if (bNorth && psImage->chICORDS != 'N')
    2455             :         {
    2456           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2457             :                      "NITF file should have been created with creation option "
    2458             :                      "'ICORDS=N'.\n");
    2459           0 :             return CE_Failure;
    2460             :         }
    2461           1 :         else if (!bNorth && psImage->chICORDS != 'S')
    2462             :         {
    2463           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2464             :                      "NITF file should have been created with creation option "
    2465             :                      "'ICORDS=S'.\n");
    2466           0 :             return CE_Failure;
    2467             :         }
    2468             : 
    2469           1 :         psImage->nZone = poSRS->GetUTMZone(nullptr);
    2470             :     }
    2471             :     else
    2472             :     {
    2473           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2474             :                  "NITF only supports WGS84 geographic and UTM projections.\n");
    2475           0 :         return CE_Failure;
    2476             :     }
    2477             : 
    2478          12 :     m_oSRS = *poSRS;
    2479             : 
    2480          12 :     if (bGotGeoTransform)
    2481           9 :         SetGeoTransform(adfGeoTransform);
    2482             : 
    2483          12 :     return CE_None;
    2484             : }
    2485             : 
    2486             : #ifdef ESRI_BUILD
    2487             : /************************************************************************/
    2488             : /*                       InitializeNITFDESMetadata()                    */
    2489             : /************************************************************************/
    2490             : 
    2491             : void NITFDataset::InitializeNITFDESMetadata()
    2492             : {
    2493             :     static const char *const pszDESMetadataDomain = "NITF_DES_METADATA";
    2494             :     static const char *const pszDESsDomain = "xml:DES";
    2495             :     static const char *const pszMDXmlDataContentDESDATA =
    2496             :         "NITF_DES_XML_DATA_CONTENT_DESDATA";
    2497             :     static const char *const pszXmlDataContent = "XML_DATA_CONTENT";
    2498             :     constexpr int idxXmlDataContentDESDATA = 973;
    2499             :     static const int sizeXmlDataContent =
    2500             :         static_cast<int>(strlen(pszXmlDataContent));
    2501             : 
    2502             :     char **ppszDESMetadataList = oSpecialMD.GetMetadata(pszDESMetadataDomain);
    2503             : 
    2504             :     if (ppszDESMetadataList != NULL)
    2505             :         return;
    2506             : 
    2507             :     char **ppszDESsList = this->GetMetadata(pszDESsDomain);
    2508             : 
    2509             :     if (ppszDESsList == NULL)
    2510             :         return;
    2511             : 
    2512             :     bool foundXmlDataContent = false;
    2513             :     char *pachNITFDES = NULL;
    2514             : 
    2515             :     // Set metadata "NITF_DES_XML_DATA_CONTENT_DESDATA".
    2516             :     // NOTE: There should only be one instance of XML_DATA_CONTENT DES.
    2517             : 
    2518             :     while (((pachNITFDES = *ppszDESsList) != NULL) && (!foundXmlDataContent))
    2519             :     {
    2520             :         // The data stream has been Base64 encoded, need to decode it.
    2521             :         // NOTE: The actual length of the DES data stream is appended at the
    2522             :         // beginning of the encoded
    2523             :         //       data and is separated by a space.
    2524             : 
    2525             :         const char *pszSpace = strchr(pachNITFDES, ' ');
    2526             : 
    2527             :         char *pszData = NULL;
    2528             :         int nDataLen = 0;
    2529             :         if (pszSpace)
    2530             :         {
    2531             :             pszData = CPLStrdup(pszSpace + 1);
    2532             :             nDataLen =
    2533             :                 CPLBase64DecodeInPlace(reinterpret_cast<GByte *>(pszData));
    2534             :             pszData[nDataLen] = 0;
    2535             :         }
    2536             : 
    2537             :         if (nDataLen > 2 + sizeXmlDataContent && STARTS_WITH_CI(pszData, "DE"))
    2538             :         {
    2539             :             // Check to see if this is a XML_DATA_CONTENT DES.
    2540             :             if (EQUALN(pszData + 2, pszXmlDataContent, sizeXmlDataContent) &&
    2541             :                 nDataLen > idxXmlDataContentDESDATA)
    2542             :             {
    2543             :                 foundXmlDataContent = true;
    2544             : 
    2545             :                 // Get the value of the DESDATA field and set metadata
    2546             :                 // "NITF_DES_XML_DATA_CONTENT_DESDATA".
    2547             :                 const char *pszXML = pszData + idxXmlDataContentDESDATA;
    2548             : 
    2549             :                 // Set the metadata.
    2550             :                 oSpecialMD.SetMetadataItem(pszMDXmlDataContentDESDATA, pszXML,
    2551             :                                            pszDESMetadataDomain);
    2552             :             }
    2553             :         }
    2554             : 
    2555             :         CPLFree(pszData);
    2556             : 
    2557             :         pachNITFDES = NULL;
    2558             :         ppszDESsList += 1;
    2559             :     }
    2560             : }
    2561             : 
    2562             : /************************************************************************/
    2563             : /*                       InitializeNITFTREs()                           */
    2564             : /************************************************************************/
    2565             : 
    2566             : void NITFDataset::InitializeNITFTREs()
    2567             : {
    2568             :     static const char *const pszFileHeaderTREsDomain = "NITF_FILE_HEADER_TRES";
    2569             :     static const char *const pszImageSegmentTREsDomain =
    2570             :         "NITF_IMAGE_SEGMENT_TRES";
    2571             : 
    2572             :     char **ppszFileHeaderTREsList =
    2573             :         oSpecialMD.GetMetadata(pszFileHeaderTREsDomain);
    2574             :     char **ppszImageSegmentTREsList =
    2575             :         oSpecialMD.GetMetadata(pszImageSegmentTREsDomain);
    2576             : 
    2577             :     if ((ppszFileHeaderTREsList != NULL) && (ppszImageSegmentTREsList != NULL))
    2578             :         return;
    2579             : 
    2580             :     /* -------------------------------------------------------------------- */
    2581             :     /*      Loop over TRE sources (file and image).                         */
    2582             :     /* -------------------------------------------------------------------- */
    2583             : 
    2584             :     for (int nTRESrc = 0; nTRESrc < 2; nTRESrc++)
    2585             :     {
    2586             :         int nTREBytes = 0;
    2587             :         char *pszTREData = NULL;
    2588             :         const char *pszTREsDomain = NULL;
    2589             :         CPLStringList aosList;
    2590             : 
    2591             :         /* --------------------------------------------------------------------
    2592             :          */
    2593             :         /*      Extract file header or image segment TREs. */
    2594             :         /* --------------------------------------------------------------------
    2595             :          */
    2596             : 
    2597             :         if (nTRESrc == 0)
    2598             :         {
    2599             :             if (ppszFileHeaderTREsList != NULL)
    2600             :                 continue;
    2601             : 
    2602             :             nTREBytes = psFile->nTREBytes;
    2603             :             pszTREData = psFile->pachTRE;
    2604             :             pszTREsDomain = pszFileHeaderTREsDomain;
    2605             :         }
    2606             :         else
    2607             :         {
    2608             :             if (ppszImageSegmentTREsList != NULL)
    2609             :                 continue;
    2610             : 
    2611             :             if (psImage)
    2612             :             {
    2613             :                 nTREBytes = psImage->nTREBytes;
    2614             :                 pszTREData = psImage->pachTRE;
    2615             :                 pszTREsDomain = pszImageSegmentTREsDomain;
    2616             :             }
    2617             :             else
    2618             :             {
    2619             :                 nTREBytes = 0;
    2620             :                 pszTREData = NULL;
    2621             :             }
    2622             :         }
    2623             : 
    2624             :         /* --------------------------------------------------------------------
    2625             :          */
    2626             :         /*      Loop over TREs. */
    2627             :         /* --------------------------------------------------------------------
    2628             :          */
    2629             : 
    2630             :         while (nTREBytes >= 11)
    2631             :         {
    2632             :             char szTemp[100];
    2633             :             char szTag[7];
    2634             :             char *pszEscapedData = NULL;
    2635             :             int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5));
    2636             : 
    2637             :             if (nThisTRESize < 0)
    2638             :             {
    2639             :                 NITFGetField(szTemp, pszTREData, 0, 6);
    2640             :                 CPLError(CE_Failure, CPLE_AppDefined,
    2641             :                          "Invalid size (%d) for TRE %s", nThisTRESize, szTemp);
    2642             :                 return;
    2643             :             }
    2644             : 
    2645             :             if (nThisTRESize > nTREBytes - 11)
    2646             :             {
    2647             :                 CPLError(CE_Failure, CPLE_AppDefined,
    2648             :                          "Not enough bytes in TRE");
    2649             :                 return;
    2650             :             }
    2651             : 
    2652             :             strncpy(szTag, pszTREData, 6);
    2653             :             szTag[6] = '\0';
    2654             : 
    2655             :             // trim white off tag.
    2656             :             while (strlen(szTag) > 0 && szTag[strlen(szTag) - 1] == ' ')
    2657             :                 szTag[strlen(szTag) - 1] = '\0';
    2658             : 
    2659             :             // escape data.
    2660             :             pszEscapedData = CPLEscapeString(pszTREData + 6, nThisTRESize + 5,
    2661             :                                              CPLES_BackslashQuotable);
    2662             : 
    2663             :             const size_t nLineLen = strlen(szTag) + strlen(pszEscapedData) + 2;
    2664             :             char *pszLine = reinterpret_cast<char *>(CPLMalloc(nLineLen));
    2665             :             snprintf(pszLine, nLineLen, "%s=%s", szTag, pszEscapedData);
    2666             :             aosList.AddString(pszLine);
    2667             :             CPLFree(pszLine);
    2668             :             pszLine = NULL;
    2669             : 
    2670             :             CPLFree(pszEscapedData);
    2671             :             pszEscapedData = NULL;
    2672             : 
    2673             :             nTREBytes -= (nThisTRESize + 11);
    2674             :             pszTREData += (nThisTRESize + 11);
    2675             :         }
    2676             : 
    2677             :         if (!aosList.empty())
    2678             :             oSpecialMD.SetMetadata(aosList.List(), pszTREsDomain);
    2679             :     }
    2680             : }
    2681             : #endif
    2682             : 
    2683             : /************************************************************************/
    2684             : /*                       InitializeNITFDESs()                           */
    2685             : /************************************************************************/
    2686             : 
    2687          14 : bool NITFDataset::InitializeNITFDESs(bool bValidate)
    2688             : {
    2689          14 :     char **papszDESsList = oSpecialMD.GetMetadata("xml:DES");
    2690             : 
    2691          14 :     if (papszDESsList != nullptr)
    2692             :     {
    2693           1 :         return true;
    2694             :     }
    2695             : 
    2696          13 :     bool bSuccess = true;
    2697             :     CPLXMLNode *psDesListNode =
    2698          13 :         CPLCreateXMLNode(nullptr, CXT_Element, "des_list");
    2699             : 
    2700          39 :     for (int iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++)
    2701             :     {
    2702          26 :         NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;
    2703             : 
    2704          26 :         if (EQUAL(psSegInfo->szSegmentType, "DE"))
    2705             :         {
    2706          11 :             bool bGotError = false;
    2707             :             CPLXMLNode *psDesNode =
    2708          11 :                 NITFDESGetXml(psFile, iSegment, bValidate, &bGotError);
    2709          11 :             if (bGotError)
    2710           2 :                 bSuccess = false;
    2711             : 
    2712          11 :             if (psDesNode != nullptr)
    2713             :             {
    2714          11 :                 CPLAddXMLChild(psDesListNode, psDesNode);
    2715             :             }
    2716             :         }
    2717             :     }
    2718             : 
    2719          13 :     if (psDesListNode->psChild != nullptr)
    2720             :     {
    2721          10 :         char *pszXML = CPLSerializeXMLTree(psDesListNode);
    2722          10 :         char *apszMD[2] = {pszXML, nullptr};
    2723          10 :         oSpecialMD.SetMetadata(apszMD, "xml:DES");
    2724          10 :         CPLFree(pszXML);
    2725             :     }
    2726          13 :     CPLDestroyXMLNode(psDesListNode);
    2727          13 :     return bSuccess;
    2728             : }
    2729             : 
    2730             : /************************************************************************/
    2731             : /*                       InitializeNITFMetadata()                        */
    2732             : /************************************************************************/
    2733             : 
    2734           5 : void NITFDataset::InitializeNITFMetadata()
    2735             : 
    2736             : {
    2737             :     static const char *const pszDomainName = "NITF_METADATA";
    2738             :     static const char *const pszTagNITFFileHeader = "NITFFileHeader";
    2739             :     static const char *const pszTagNITFImageSubheader = "NITFImageSubheader";
    2740             : 
    2741           5 :     if (oSpecialMD.GetMetadata(pszDomainName) != nullptr)
    2742           1 :         return;
    2743             : 
    2744             :     // nHeaderLenOffset is the number of bytes to skip from the beginning of the
    2745             :     // NITF file header in order to get to the field HL (NITF file header
    2746             :     // length).
    2747             : 
    2748           4 :     int nHeaderLen = 0;
    2749           4 :     int nHeaderLenOffset = 0;
    2750             : 
    2751             :     // Get the NITF file header length.
    2752             : 
    2753           4 :     if (psFile->pachHeader != nullptr)
    2754             :     {
    2755           4 :         if ((STARTS_WITH(psFile->pachHeader, "NITF02.10")) ||
    2756           0 :             (STARTS_WITH(psFile->pachHeader, "NSIF01.00")))
    2757           4 :             nHeaderLenOffset = 354;
    2758           0 :         else if ((STARTS_WITH(psFile->pachHeader, "NITF01.10")) ||
    2759           0 :                  (STARTS_WITH(psFile->pachHeader, "NITF02.00")))
    2760           0 :             nHeaderLenOffset =
    2761           0 :                 (STARTS_WITH((psFile->pachHeader + 280), "999998")) ? 394 : 354;
    2762             :     }
    2763             : 
    2764             :     char fieldHL[7];
    2765             : 
    2766           4 :     if (nHeaderLenOffset > 0)
    2767             :     {
    2768           4 :         char *pszFieldHL = psFile->pachHeader + nHeaderLenOffset;
    2769             : 
    2770           4 :         memcpy(fieldHL, pszFieldHL, 6);
    2771           4 :         fieldHL[6] = '\0';
    2772           4 :         nHeaderLen = atoi(fieldHL);
    2773             :     }
    2774             : 
    2775           4 :     if (nHeaderLen <= 0)
    2776             :     {
    2777           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Zero length NITF file header!");
    2778           0 :         return;
    2779             :     }
    2780             : 
    2781           8 :     char *encodedHeader = CPLBase64Encode(
    2782           4 :         nHeaderLen, reinterpret_cast<GByte *>(psFile->pachHeader));
    2783             : 
    2784           4 :     if (encodedHeader == nullptr || strlen(encodedHeader) == 0)
    2785             :     {
    2786           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2787             :                  "Failed to encode NITF file header!");
    2788           0 :         CPLFree(encodedHeader);
    2789           0 :         return;
    2790             :     }
    2791             : 
    2792             :     // The length of the NITF file header plus a space is append to the
    2793             :     // beginning of the encoded string so that we can recover the length of the
    2794             :     // NITF file header when we decode it without having to pull it out the HL
    2795             :     // field again.
    2796             : 
    2797           4 :     std::string nitfFileheaderStr(fieldHL);
    2798           4 :     nitfFileheaderStr.append(" ");
    2799           4 :     nitfFileheaderStr.append(encodedHeader);
    2800             : 
    2801           4 :     CPLFree(encodedHeader);
    2802             : 
    2803           4 :     oSpecialMD.SetMetadataItem(pszTagNITFFileHeader, nitfFileheaderStr.c_str(),
    2804             :                                pszDomainName);
    2805             : 
    2806             :     // Get the image subheader length.
    2807             : 
    2808           4 :     int nImageSubheaderLen = 0;
    2809             : 
    2810           4 :     if (psImage != nullptr &&
    2811           3 :         STARTS_WITH(psFile->pasSegmentInfo[psImage->iSegment].szSegmentType,
    2812             :                     "IM"))
    2813             :     {
    2814           3 :         nImageSubheaderLen =
    2815           3 :             psFile->pasSegmentInfo[psImage->iSegment].nSegmentHeaderSize;
    2816             :     }
    2817             : 
    2818           4 :     if (nImageSubheaderLen < 0)
    2819             :     {
    2820           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2821             :                  "Invalid length NITF image subheader!");
    2822           0 :         return;
    2823             :     }
    2824             : 
    2825           4 :     if (nImageSubheaderLen > 0)
    2826             :     {
    2827           6 :         char *encodedImageSubheader = CPLBase64Encode(
    2828           3 :             nImageSubheaderLen, reinterpret_cast<GByte *>(psImage->pachHeader));
    2829             : 
    2830           3 :         if (encodedImageSubheader == nullptr ||
    2831           3 :             strlen(encodedImageSubheader) == 0)
    2832             :         {
    2833           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2834             :                      "Failed to encode image subheader!");
    2835           0 :             CPLFree(encodedImageSubheader);
    2836           0 :             return;
    2837             :         }
    2838             : 
    2839             :         // The length of the image subheader plus a space is append to the
    2840             :         // beginning of the encoded string so that we can recover the actual
    2841             :         // length of the image subheader when we decode it.
    2842             : 
    2843             :         char buffer[20];
    2844             : 
    2845           3 :         snprintf(buffer, sizeof(buffer), "%d", nImageSubheaderLen);
    2846             : 
    2847           6 :         std::string imageSubheaderStr(buffer);
    2848           3 :         imageSubheaderStr.append(" ");
    2849           3 :         imageSubheaderStr.append(encodedImageSubheader);
    2850             : 
    2851           3 :         CPLFree(encodedImageSubheader);
    2852             : 
    2853           3 :         oSpecialMD.SetMetadataItem(pszTagNITFImageSubheader,
    2854             :                                    imageSubheaderStr.c_str(), pszDomainName);
    2855             :     }
    2856             : }
    2857             : 
    2858             : /************************************************************************/
    2859             : /*                       InitializeCGMMetadata()                        */
    2860             : /************************************************************************/
    2861             : 
    2862          16 : void NITFDataset::InitializeCGMMetadata()
    2863             : 
    2864             : {
    2865          16 :     if (oSpecialMD.GetMetadataItem("SEGMENT_COUNT", "CGM") != nullptr)
    2866           5 :         return;
    2867             : 
    2868          11 :     int iCGM = 0;
    2869          11 :     char **papszCGMMetadata = CSLSetNameValue(nullptr, "SEGMENT_COUNT", "0");
    2870             : 
    2871             :     /* ==================================================================== */
    2872             :     /*      Process all graphics segments.                                  */
    2873             :     /* ==================================================================== */
    2874          27 :     for (int iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++)
    2875             :     {
    2876          16 :         NITFSegmentInfo *psSegment = psFile->pasSegmentInfo + iSegment;
    2877             : 
    2878          16 :         if (!EQUAL(psSegment->szSegmentType, "GR") &&
    2879          13 :             !EQUAL(psSegment->szSegmentType, "SY"))
    2880          13 :             continue;
    2881             : 
    2882           3 :         papszCGMMetadata = CSLSetNameValue(
    2883           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_SLOC_ROW", iCGM),
    2884           6 :             CPLString().Printf("%d", psSegment->nLOC_R));
    2885           3 :         papszCGMMetadata = CSLSetNameValue(
    2886           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_SLOC_COL", iCGM),
    2887           6 :             CPLString().Printf("%d", psSegment->nLOC_C));
    2888             : 
    2889           3 :         papszCGMMetadata = CSLSetNameValue(
    2890           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_CCS_ROW", iCGM),
    2891           6 :             CPLString().Printf("%d", psSegment->nCCS_R));
    2892           3 :         papszCGMMetadata = CSLSetNameValue(
    2893           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_CCS_COL", iCGM),
    2894           6 :             CPLString().Printf("%d", psSegment->nCCS_C));
    2895             : 
    2896           3 :         papszCGMMetadata = CSLSetNameValue(
    2897           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_SDLVL", iCGM),
    2898           6 :             CPLString().Printf("%d", psSegment->nDLVL));
    2899           3 :         papszCGMMetadata = CSLSetNameValue(
    2900           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_SALVL", iCGM),
    2901           6 :             CPLString().Printf("%d", psSegment->nALVL));
    2902             : 
    2903             :         /* --------------------------------------------------------------------
    2904             :          */
    2905             :         /*      Load the raw CGM data itself. */
    2906             :         /* --------------------------------------------------------------------
    2907             :          */
    2908             : 
    2909           3 :         char *pabyCGMData = reinterpret_cast<char *>(VSI_CALLOC_VERBOSE(
    2910             :             1, static_cast<size_t>(psSegment->nSegmentSize)));
    2911           3 :         if (pabyCGMData == nullptr)
    2912             :         {
    2913           0 :             CSLDestroy(papszCGMMetadata);
    2914           0 :             return;
    2915             :         }
    2916           6 :         if (VSIFSeekL(psFile->fp, psSegment->nSegmentStart, SEEK_SET) != 0 ||
    2917           6 :             VSIFReadL(pabyCGMData, 1, (size_t)psSegment->nSegmentSize,
    2918           3 :                       psFile->fp) != psSegment->nSegmentSize)
    2919             :         {
    2920           0 :             CPLError(CE_Warning, CPLE_FileIO,
    2921             :                      "Failed to read " CPL_FRMT_GUIB
    2922             :                      " bytes of graphic data at " CPL_FRMT_GUIB ".",
    2923             :                      psSegment->nSegmentSize, psSegment->nSegmentStart);
    2924           0 :             CPLFree(pabyCGMData);
    2925           0 :             CSLDestroy(papszCGMMetadata);
    2926           0 :             return;
    2927             :         }
    2928             : 
    2929           6 :         char *pszEscapedCGMData = CPLEscapeString(
    2930           3 :             pabyCGMData, static_cast<int>(psSegment->nSegmentSize),
    2931             :             CPLES_BackslashQuotable);
    2932             : 
    2933           3 :         if (pszEscapedCGMData == nullptr)
    2934             :         {
    2935           0 :             CPLFree(pabyCGMData);
    2936           0 :             CSLDestroy(papszCGMMetadata);
    2937           0 :             return;
    2938             :         }
    2939             : 
    2940           3 :         papszCGMMetadata = CSLSetNameValue(
    2941           6 :             papszCGMMetadata, CPLString().Printf("SEGMENT_%d_DATA", iCGM),
    2942             :             pszEscapedCGMData);
    2943           3 :         CPLFree(pszEscapedCGMData);
    2944           3 :         CPLFree(pabyCGMData);
    2945             : 
    2946           3 :         iCGM++;
    2947             :     }
    2948             : 
    2949             :     /* -------------------------------------------------------------------- */
    2950             :     /*      Record the CGM segment count.                                   */
    2951             :     /* -------------------------------------------------------------------- */
    2952          11 :     papszCGMMetadata = CSLSetNameValue(papszCGMMetadata, "SEGMENT_COUNT",
    2953          22 :                                        CPLString().Printf("%d", iCGM));
    2954             : 
    2955          11 :     oSpecialMD.SetMetadata(papszCGMMetadata, "CGM");
    2956             : 
    2957          11 :     CSLDestroy(papszCGMMetadata);
    2958             : }
    2959             : 
    2960             : /************************************************************************/
    2961             : /*                       InitializeTextMetadata()                       */
    2962             : /************************************************************************/
    2963             : 
    2964          17 : void NITFDataset::InitializeTextMetadata()
    2965             : 
    2966             : {
    2967          17 :     if (oSpecialMD.GetMetadata("TEXT") != nullptr)
    2968           2 :         return;
    2969             : 
    2970          15 :     int iText = 0;
    2971             : 
    2972             :     /* ==================================================================== */
    2973             :     /*      Process all text segments.                                  */
    2974             :     /* ==================================================================== */
    2975          37 :     for (int iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++)
    2976             :     {
    2977          22 :         NITFSegmentInfo *psSegment = psFile->pasSegmentInfo + iSegment;
    2978             : 
    2979          22 :         if (!EQUAL(psSegment->szSegmentType, "TX"))
    2980          16 :             continue;
    2981             : 
    2982             :         /* --------------------------------------------------------------------
    2983             :          */
    2984             :         /*      Load the text header */
    2985             :         /* --------------------------------------------------------------------
    2986             :          */
    2987             : 
    2988             :         /* Allocate one extra byte for the NULL terminating character */
    2989          12 :         char *pabyHeaderData = reinterpret_cast<char *>(CPLCalloc(
    2990           6 :             1, static_cast<size_t>(psSegment->nSegmentHeaderSize + 1)));
    2991           6 :         if (VSIFSeekL(psFile->fp, psSegment->nSegmentHeaderStart, SEEK_SET) !=
    2992          12 :                 0 ||
    2993          12 :             VSIFReadL(pabyHeaderData, 1, (size_t)psSegment->nSegmentHeaderSize,
    2994           6 :                       psFile->fp) != psSegment->nSegmentHeaderSize)
    2995             :         {
    2996           0 :             CPLError(
    2997             :                 CE_Warning, CPLE_FileIO,
    2998             :                 "Failed to read %d bytes of text header data at " CPL_FRMT_GUIB
    2999             :                 ".",
    3000             :                 psSegment->nSegmentHeaderSize, psSegment->nSegmentHeaderStart);
    3001           0 :             CPLFree(pabyHeaderData);
    3002           0 :             return;
    3003             :         }
    3004             : 
    3005           6 :         oSpecialMD.SetMetadataItem(CPLString().Printf("HEADER_%d", iText),
    3006             :                                    pabyHeaderData, "TEXT");
    3007           6 :         CPLFree(pabyHeaderData);
    3008             : 
    3009             :         /* --------------------------------------------------------------------
    3010             :          */
    3011             :         /*      Load the raw TEXT data itself. */
    3012             :         /* --------------------------------------------------------------------
    3013             :          */
    3014             :         /* Allocate one extra byte for the NULL terminating character */
    3015             :         char *pabyTextData = reinterpret_cast<char *>(
    3016           6 :             VSI_CALLOC_VERBOSE(1, (size_t)psSegment->nSegmentSize + 1));
    3017           6 :         if (pabyTextData == nullptr)
    3018             :         {
    3019           0 :             return;
    3020             :         }
    3021          12 :         if (VSIFSeekL(psFile->fp, psSegment->nSegmentStart, SEEK_SET) != 0 ||
    3022          12 :             VSIFReadL(pabyTextData, 1,
    3023           6 :                       static_cast<size_t>(psSegment->nSegmentSize),
    3024           6 :                       psFile->fp) != psSegment->nSegmentSize)
    3025             :         {
    3026           0 :             CPLError(CE_Warning, CPLE_FileIO,
    3027             :                      "Failed to read " CPL_FRMT_GUIB
    3028             :                      " bytes of text data at " CPL_FRMT_GUIB ".",
    3029             :                      psSegment->nSegmentSize, psSegment->nSegmentStart);
    3030           0 :             CPLFree(pabyTextData);
    3031           0 :             return;
    3032             :         }
    3033             : 
    3034           6 :         oSpecialMD.SetMetadataItem(CPLString().Printf("DATA_%d", iText),
    3035             :                                    pabyTextData, "TEXT");
    3036           6 :         CPLFree(pabyTextData);
    3037             : 
    3038           6 :         iText++;
    3039             :     }
    3040             : }
    3041             : 
    3042             : /************************************************************************/
    3043             : /*                       InitializeTREMetadata()                        */
    3044             : /************************************************************************/
    3045             : 
    3046          71 : bool NITFDataset::InitializeTREMetadata(bool bValidate)
    3047             : 
    3048             : {
    3049         135 :     if (oSpecialMD.GetMetadata("TRE") != nullptr ||
    3050          64 :         oSpecialMD.GetMetadata("xml:TRE") != nullptr)
    3051           7 :         return true;
    3052             : 
    3053          64 :     bool bGotError = false;
    3054          64 :     CPLXMLNode *psTresNode = CPLCreateXMLNode(nullptr, CXT_Element, "tres");
    3055             : 
    3056             :     /* -------------------------------------------------------------------- */
    3057             :     /*      Loop over TRE sources (file and image).                         */
    3058             :     /* -------------------------------------------------------------------- */
    3059         192 :     for (int nTRESrc = 0; nTRESrc < 2; nTRESrc++)
    3060             :     {
    3061         128 :         int nTREBytes = 0;
    3062         128 :         char *pszTREData = nullptr;
    3063             : 
    3064         128 :         if (nTRESrc == 0)
    3065             :         {
    3066          64 :             nTREBytes = psFile->nTREBytes;
    3067          64 :             pszTREData = psFile->pachTRE;
    3068             :         }
    3069             :         else
    3070             :         {
    3071          64 :             if (psImage)
    3072             :             {
    3073          62 :                 nTREBytes = psImage->nTREBytes;
    3074          62 :                 pszTREData = psImage->pachTRE;
    3075             :             }
    3076             :             else
    3077             :             {
    3078           2 :                 nTREBytes = 0;
    3079           2 :                 pszTREData = nullptr;
    3080             :             }
    3081             :         }
    3082             : 
    3083             :         /* --------------------------------------------------------------------
    3084             :          */
    3085             :         /*      Loop over TREs. */
    3086             :         /* --------------------------------------------------------------------
    3087             :          */
    3088             : 
    3089         184 :         while (nTREBytes >= 11)
    3090             :         {
    3091             :             char szTemp[100];
    3092             :             char szTag[7];
    3093             :             const int nThisTRESize =
    3094          56 :                 atoi(NITFGetField(szTemp, pszTREData, 6, 5));
    3095             : 
    3096          56 :             if (nThisTRESize < 0)
    3097             :             {
    3098           0 :                 NITFGetField(szTemp, pszTREData, 0, 6);
    3099           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3100             :                          "Invalid size (%d) for TRE %s", nThisTRESize, szTemp);
    3101           0 :                 CPLDestroyXMLNode(psTresNode);
    3102           0 :                 bGotError = true;
    3103           0 :                 return bGotError;
    3104             :             }
    3105          56 :             if (nThisTRESize > nTREBytes - 11)
    3106             :             {
    3107           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3108             :                          "Not enough bytes in TRE");
    3109           0 :                 CPLDestroyXMLNode(psTresNode);
    3110           0 :                 bGotError = true;
    3111           0 :                 return bGotError;
    3112             :             }
    3113             : 
    3114          56 :             strncpy(szTag, pszTREData, 6);
    3115          56 :             szTag[6] = '\0';
    3116             : 
    3117             :             // trim white off tag.
    3118          56 :             while (strlen(szTag) > 0 && szTag[strlen(szTag) - 1] == ' ')
    3119           0 :                 szTag[strlen(szTag) - 1] = '\0';
    3120             : 
    3121             :             CPLXMLNode *psTreNode =
    3122          56 :                 NITFCreateXMLTre(psFile, szTag, pszTREData + 11, nThisTRESize,
    3123             :                                  bValidate, &bGotError);
    3124          56 :             if (psTreNode)
    3125             :             {
    3126          51 :                 CPLCreateXMLNode(
    3127             :                     CPLCreateXMLNode(psTreNode, CXT_Attribute, "location"),
    3128             :                     CXT_Text, nTRESrc == 0 ? "file" : "image");
    3129          51 :                 CPLAddXMLChild(psTresNode, psTreNode);
    3130             :             }
    3131             : 
    3132             :             // escape data.
    3133         112 :             char *pszEscapedData = CPLEscapeString(
    3134          56 :                 pszTREData + 11, nThisTRESize, CPLES_BackslashQuotable);
    3135          56 :             if (pszEscapedData == nullptr)
    3136             :             {
    3137           0 :                 bGotError = true;
    3138             :             }
    3139             :             else
    3140             :             {
    3141             :                 char szUniqueTag[32];
    3142          56 :                 strcpy(szUniqueTag, szTag);
    3143          56 :                 int nCountUnique = 2;
    3144          56 :                 while (oSpecialMD.GetMetadataItem(szUniqueTag, "TRE") !=
    3145             :                        nullptr)
    3146             :                 {
    3147           0 :                     snprintf(szUniqueTag, sizeof(szUniqueTag), "%s_%d", szTag,
    3148             :                              nCountUnique);
    3149           0 :                     nCountUnique++;
    3150             :                 }
    3151          56 :                 oSpecialMD.SetMetadataItem(szUniqueTag, pszEscapedData, "TRE");
    3152          56 :                 CPLFree(pszEscapedData);
    3153             :             }
    3154             : 
    3155          56 :             nTREBytes -= (nThisTRESize + 11);
    3156          56 :             pszTREData += (nThisTRESize + 11);
    3157             :         }
    3158             :     }
    3159             : 
    3160             :     /* -------------------------------------------------------------------- */
    3161             :     /*      Loop over TRE in DES                                            */
    3162             :     /* -------------------------------------------------------------------- */
    3163         132 :     for (int iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++)
    3164             :     {
    3165          68 :         NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;
    3166          68 :         if (!EQUAL(psSegInfo->szSegmentType, "DE"))
    3167          64 :             continue;
    3168             : 
    3169           4 :         NITFDES *psDES = NITFDESAccess(psFile, iSegment);
    3170           4 :         if (psDES == nullptr)
    3171           0 :             continue;
    3172             : 
    3173           4 :         char *pabyTREData = nullptr;
    3174           4 :         int nOffset = 0;
    3175             :         char szTREName[7];
    3176             :         int nThisTRESize;
    3177             : 
    3178           9 :         while (NITFDESGetTRE(psDES, nOffset, szTREName, &pabyTREData,
    3179           9 :                              &nThisTRESize))
    3180             :         {
    3181           5 :             char *pszEscapedData = CPLEscapeString(pabyTREData, nThisTRESize,
    3182             :                                                    CPLES_BackslashQuotable);
    3183           5 :             if (pszEscapedData == nullptr)
    3184             :             {
    3185           0 :                 NITFDESFreeTREData(pabyTREData);
    3186           0 :                 bGotError = true;
    3187           0 :                 break;
    3188             :             }
    3189             : 
    3190             :             // trim white off tag.
    3191           5 :             while (strlen(szTREName) > 0 &&
    3192           5 :                    szTREName[strlen(szTREName) - 1] == ' ')
    3193           0 :                 szTREName[strlen(szTREName) - 1] = '\0';
    3194             : 
    3195             :             CPLXMLNode *psTreNode =
    3196           5 :                 NITFCreateXMLTre(psFile, szTREName, pabyTREData, nThisTRESize,
    3197             :                                  bValidate, &bGotError);
    3198           5 :             if (psTreNode)
    3199             :             {
    3200             :                 const char *pszDESID =
    3201           5 :                     CSLFetchNameValue(psDES->papszMetadata, "DESID");
    3202          10 :                 CPLCreateXMLNode(
    3203             :                     CPLCreateXMLNode(psTreNode, CXT_Attribute, "location"),
    3204             :                     CXT_Text,
    3205           5 :                     pszDESID ? CPLSPrintf("des %s", pszDESID) : "des");
    3206           5 :                 CPLAddXMLChild(psTresNode, psTreNode);
    3207             :             }
    3208             : 
    3209             :             char szUniqueTag[32];
    3210           5 :             strcpy(szUniqueTag, szTREName);
    3211           5 :             int nCountUnique = 2;
    3212           5 :             while (oSpecialMD.GetMetadataItem(szUniqueTag, "TRE") != nullptr)
    3213             :             {
    3214           0 :                 snprintf(szUniqueTag, sizeof(szUniqueTag), "%s_%d", szTREName,
    3215             :                          nCountUnique);
    3216           0 :                 nCountUnique++;
    3217             :             }
    3218           5 :             oSpecialMD.SetMetadataItem(szUniqueTag, pszEscapedData, "TRE");
    3219             : 
    3220           5 :             CPLFree(pszEscapedData);
    3221             : 
    3222           5 :             nOffset += 11 + nThisTRESize;
    3223             : 
    3224           5 :             NITFDESFreeTREData(pabyTREData);
    3225             :         }
    3226             : 
    3227           4 :         NITFDESDeaccess(psDES);
    3228             :     }
    3229             : 
    3230          64 :     if (psTresNode->psChild != nullptr)
    3231             :     {
    3232          53 :         char *pszXML = CPLSerializeXMLTree(psTresNode);
    3233          53 :         char *apszMD[2] = {pszXML, nullptr};
    3234          53 :         oSpecialMD.SetMetadata(apszMD, "xml:TRE");
    3235          53 :         CPLFree(pszXML);
    3236             :     }
    3237          64 :     CPLDestroyXMLNode(psTresNode);
    3238             : 
    3239          64 :     return !bGotError;
    3240             : }
    3241             : 
    3242             : /************************************************************************/
    3243             : /*                      GetMetadataDomainList()                         */
    3244             : /************************************************************************/
    3245             : 
    3246           1 : char **NITFDataset::GetMetadataDomainList()
    3247             : {
    3248           1 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3249             :                                    TRUE, "NITF_METADATA", "xml:DES",
    3250             :                                    "NITF_DES_METADATA", "NITF_FILE_HEADER_TRES",
    3251             :                                    "NITF_IMAGE_SEGMENT_TRES", "CGM", "TEXT",
    3252           1 :                                    "TRE", "xml:TRE", "OVERVIEWS", nullptr);
    3253             : }
    3254             : 
    3255             : /************************************************************************/
    3256             : /*                      InitializeImageStructureMetadata()              */
    3257             : /************************************************************************/
    3258             : 
    3259           2 : void NITFDataset::InitializeImageStructureMetadata()
    3260             : {
    3261           2 :     if (oSpecialMD.GetMetadata("IMAGE_STRUCTURE") != nullptr)
    3262           0 :         return;
    3263             : 
    3264           2 :     oSpecialMD.SetMetadata(GDALPamDataset::GetMetadata("IMAGE_STRUCTURE"),
    3265             :                            "IMAGE_STRUCTURE");
    3266           2 :     if (poJ2KDataset)
    3267             :     {
    3268           4 :         const char *pszReversibility = poJ2KDataset->GetMetadataItem(
    3269           2 :             "COMPRESSION_REVERSIBILITY", "IMAGE_STRUCTURE");
    3270           2 :         if (pszReversibility)
    3271             :         {
    3272           2 :             oSpecialMD.SetMetadataItem("COMPRESSION_REVERSIBILITY",
    3273             :                                        pszReversibility, "IMAGE_STRUCTURE");
    3274             :         }
    3275             :     }
    3276             : }
    3277             : 
    3278             : /************************************************************************/
    3279             : /*                            GetMetadata()                             */
    3280             : /************************************************************************/
    3281             : 
    3282         342 : char **NITFDataset::GetMetadata(const char *pszDomain)
    3283             : 
    3284             : {
    3285         342 :     if (pszDomain != nullptr && EQUAL(pszDomain, "NITF_METADATA"))
    3286             :     {
    3287             :         // InitializeNITFMetadata retrieves the NITF file header and all image
    3288             :         // segment file headers. (NOTE: The returned strings are
    3289             :         // base64-encoded).
    3290             : 
    3291           4 :         InitializeNITFMetadata();
    3292           4 :         return oSpecialMD.GetMetadata(pszDomain);
    3293             :     }
    3294             : 
    3295         338 :     if (pszDomain != nullptr && EQUAL(pszDomain, "xml:DES"))
    3296             :     {
    3297             :         // InitializeNITFDESs retrieves all the DES file headers (NOTE: The
    3298             :         // returned strings are base64-encoded).
    3299             : 
    3300          10 :         InitializeNITFDESs(false);
    3301          10 :         return oSpecialMD.GetMetadata(pszDomain);
    3302             :     }
    3303             : 
    3304             : #ifdef ESRI_BUILD
    3305             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_DES_METADATA"))
    3306             :     {
    3307             :         // InitializeNITFDESs retrieves all the DES file headers (NOTE: The
    3308             :         // returned strings are base64-encoded).
    3309             : 
    3310             :         InitializeNITFDESMetadata(false);
    3311             :         return oSpecialMD.GetMetadata(pszDomain);
    3312             :     }
    3313             : 
    3314             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_FILE_HEADER_TRES"))
    3315             :     {
    3316             :         // InitializeNITFTREs retrieves all the TREs that are resides in the
    3317             :         // NITF file header and all the TREs that are resides in the current
    3318             :         // image segment. NOTE: the returned strings are backslash-escaped
    3319             : 
    3320             :         InitializeNITFTREs();
    3321             :         return oSpecialMD.GetMetadata(pszDomain);
    3322             :     }
    3323             : 
    3324             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_IMAGE_SEGMENT_TRES"))
    3325             :     {
    3326             :         // InitializeNITFTREs retrieves all the TREs that are resides in the
    3327             :         // NITF file header and all the TREs that are resides in the current
    3328             :         // image segment. NOTE: the returned strings are backslash-escaped
    3329             : 
    3330             :         InitializeNITFTREs();
    3331             :         return oSpecialMD.GetMetadata(pszDomain);
    3332             :     }
    3333             : #endif
    3334             : 
    3335         328 :     if (pszDomain != nullptr && EQUAL(pszDomain, "CGM"))
    3336             :     {
    3337          15 :         InitializeCGMMetadata();
    3338          15 :         return oSpecialMD.GetMetadata(pszDomain);
    3339             :     }
    3340             : 
    3341         313 :     if (pszDomain != nullptr && EQUAL(pszDomain, "TEXT"))
    3342             :     {
    3343          16 :         InitializeTextMetadata();
    3344          16 :         return oSpecialMD.GetMetadata(pszDomain);
    3345             :     }
    3346             : 
    3347         297 :     if (pszDomain != nullptr && EQUAL(pszDomain, "TRE"))
    3348             :     {
    3349          20 :         InitializeTREMetadata(false);
    3350          20 :         return oSpecialMD.GetMetadata(pszDomain);
    3351             :     }
    3352             : 
    3353         277 :     if (pszDomain != nullptr && EQUAL(pszDomain, "xml:TRE"))
    3354             :     {
    3355          25 :         InitializeTREMetadata(false);
    3356          25 :         return oSpecialMD.GetMetadata(pszDomain);
    3357             :     }
    3358             : 
    3359         252 :     if (pszDomain != nullptr && EQUAL(pszDomain, "IMAGE_STRUCTURE") &&
    3360          12 :         poJ2KDataset)
    3361             :     {
    3362           1 :         InitializeImageStructureMetadata();
    3363           1 :         return oSpecialMD.GetMetadata(pszDomain);
    3364             :     }
    3365             : 
    3366         251 :     return GDALPamDataset::GetMetadata(pszDomain);
    3367             : }
    3368             : 
    3369             : /************************************************************************/
    3370             : /*                          GetMetadataItem()                           */
    3371             : /************************************************************************/
    3372             : 
    3373        2581 : const char *NITFDataset::GetMetadataItem(const char *pszName,
    3374             :                                          const char *pszDomain)
    3375             : 
    3376             : {
    3377        2581 :     if (pszDomain != nullptr && EQUAL(pszDomain, "NITF_METADATA"))
    3378             :     {
    3379             :         // InitializeNITFMetadata retrieves the NITF file header and all image
    3380             :         // segment file headers. (NOTE: The returned strings are
    3381             :         // base64-encoded).
    3382             : 
    3383           1 :         InitializeNITFMetadata();
    3384           1 :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3385             :     }
    3386             : 
    3387             : #ifdef ESRI_BUILD
    3388             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_DES_METADATA"))
    3389             :     {
    3390             :         // InitializeNITFDESs retrieves all the DES file headers (NOTE: The
    3391             :         // returned strings are base64-encoded).
    3392             : 
    3393             :         InitializeNITFDESMetadata(false);
    3394             :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3395             :     }
    3396             : 
    3397             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_FILE_HEADER_TRES"))
    3398             :     {
    3399             :         // InitializeNITFTREs retrieves all the TREs that are resides in the
    3400             :         // NITF file header and all the TREs that are resides in the current
    3401             :         // image segment. NOTE: the returned strings are backslash-escaped
    3402             : 
    3403             :         InitializeNITFTREs();
    3404             :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3405             :     }
    3406             : 
    3407             :     if (pszDomain != NULL && EQUAL(pszDomain, "NITF_IMAGE_SEGMENT_TRES"))
    3408             :     {
    3409             :         // InitializeNITFTREs retrieves all the TREs that are resides in the
    3410             :         // NITF file header and all the TREs that are resides in the current
    3411             :         // image segment. NOTE: the returned strings are backslash-escaped
    3412             : 
    3413             :         InitializeNITFTREs();
    3414             :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3415             :     }
    3416             : #endif
    3417             : 
    3418        2580 :     if (pszDomain != nullptr && EQUAL(pszDomain, "CGM"))
    3419             :     {
    3420           1 :         InitializeCGMMetadata();
    3421           1 :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3422             :     }
    3423             : 
    3424        2579 :     if (pszDomain != nullptr && EQUAL(pszDomain, "TEXT"))
    3425             :     {
    3426           1 :         InitializeTextMetadata();
    3427           1 :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3428             :     }
    3429             : 
    3430        2578 :     if (pszDomain != nullptr && EQUAL(pszDomain, "TRE"))
    3431             :     {
    3432          22 :         InitializeTREMetadata(false);
    3433          22 :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3434             :     }
    3435             : 
    3436        4056 :     if (pszDomain != nullptr && EQUAL(pszDomain, "OVERVIEWS") &&
    3437        1500 :         !osRSetVRT.empty())
    3438           2 :         return osRSetVRT;
    3439             : 
    3440        2554 :     if (pszDomain != nullptr && EQUAL(pszDomain, "IMAGE_STRUCTURE") &&
    3441         964 :         poJ2KDataset && EQUAL(pszName, "COMPRESSION_REVERSIBILITY"))
    3442             :     {
    3443           1 :         InitializeImageStructureMetadata();
    3444           1 :         return oSpecialMD.GetMetadataItem(pszName, pszDomain);
    3445             :     }
    3446             : 
    3447             :     // For unit test purposes
    3448        2553 :     if (pszDomain != nullptr && EQUAL(pszDomain, "DEBUG") &&
    3449           5 :         EQUAL(pszName, "JPEG2000_DATASET_NAME") && poJ2KDataset)
    3450           3 :         return poJ2KDataset->GetDescription();
    3451             : 
    3452             :     // For unit test purposes
    3453        2550 :     if (pszDomain != nullptr && EQUAL(pszDomain, "DEBUG") &&
    3454           2 :         EQUAL(pszName, "COMRAT") && psImage)
    3455           2 :         return psImage->szCOMRAT;
    3456             : 
    3457        2548 :     return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
    3458             : }
    3459             : 
    3460             : /************************************************************************/
    3461             : /*                            GetGCPCount()                             */
    3462             : /************************************************************************/
    3463             : 
    3464          29 : int NITFDataset::GetGCPCount()
    3465             : 
    3466             : {
    3467          29 :     return nGCPCount;
    3468             : }
    3469             : 
    3470             : /************************************************************************/
    3471             : /*                      GetGCPSpatialRef()                              */
    3472             : /************************************************************************/
    3473             : 
    3474           8 : const OGRSpatialReference *NITFDataset::GetGCPSpatialRef() const
    3475             : 
    3476             : {
    3477           8 :     if (nGCPCount > 0 && !m_oGCPSRS.IsEmpty())
    3478           2 :         return &m_oGCPSRS;
    3479             : 
    3480           6 :     return nullptr;
    3481             : }
    3482             : 
    3483             : /************************************************************************/
    3484             : /*                               GetGCP()                               */
    3485             : /************************************************************************/
    3486             : 
    3487           5 : const GDAL_GCP *NITFDataset::GetGCPs()
    3488             : 
    3489             : {
    3490           5 :     return pasGCPList;
    3491             : }
    3492             : 
    3493             : /************************************************************************/
    3494             : /*                           CheckForRSets()                            */
    3495             : /*                                                                      */
    3496             : /*      Check for reduced resolution images in .r<n> files and if       */
    3497             : /*      found return filename for a virtual file wrapping them as an    */
    3498             : /*      overview file. (#3457)                                          */
    3499             : /************************************************************************/
    3500             : 
    3501         742 : int NITFDataset::CheckForRSets(const char *pszNITFFilename,
    3502             :                                char **papszSiblingFiles)
    3503             : 
    3504             : {
    3505         742 :     bool isR0File = EQUAL(CPLGetExtension(pszNITFFilename), "r0");
    3506             : 
    3507             :     /* -------------------------------------------------------------------- */
    3508             :     /*      Check to see if we have RSets.                                  */
    3509             :     /* -------------------------------------------------------------------- */
    3510        1484 :     std::vector<CPLString> aosRSetFilenames;
    3511             : 
    3512         748 :     for (int i = 1; i <= 5; i++)
    3513             :     {
    3514         748 :         CPLString osTarget;
    3515             :         VSIStatBufL sStat;
    3516             : 
    3517         748 :         if (isR0File)
    3518             :         {
    3519           9 :             osTarget = pszNITFFilename;
    3520           9 :             osTarget.back() = static_cast<char>('0' + i);
    3521             :         }
    3522             :         else
    3523         739 :             osTarget.Printf("%s.r%d", pszNITFFilename, i);
    3524             : 
    3525         748 :         if (papszSiblingFiles == nullptr)
    3526             :         {
    3527          12 :             if (VSIStatL(osTarget, &sStat) != 0)
    3528          12 :                 break;
    3529             :         }
    3530             :         else
    3531             :         {
    3532         736 :             if (CSLFindStringCaseSensitive(papszSiblingFiles,
    3533         736 :                                            CPLGetFilename(osTarget)) < 0)
    3534         730 :                 break;
    3535             :         }
    3536             : 
    3537           6 :         aosRSetFilenames.push_back(osTarget);
    3538             :     }
    3539             : 
    3540         742 :     if (aosRSetFilenames.empty())
    3541             :     {
    3542             :         //try for remoteview RRDS (with .rv%d extension)
    3543         739 :         for (int i = 1; i <= 7; i++)
    3544             :         {
    3545         739 :             CPLString osTarget;
    3546             :             VSIStatBufL sStat;
    3547             : 
    3548         739 :             osTarget.Printf("%s.rv%d", pszNITFFilename, i);
    3549             : 
    3550         739 :             if (VSIStatL(osTarget, &sStat) != 0)
    3551         739 :                 break;
    3552             : 
    3553           0 :             aosRSetFilenames.push_back(osTarget);
    3554             :         }
    3555             : 
    3556         739 :         if (aosRSetFilenames.empty())
    3557         739 :             return FALSE;
    3558             :     }
    3559             : 
    3560             :     /* -------------------------------------------------------------------- */
    3561             :     /*      We do, so try to create a wrapping VRT file.                    */
    3562             :     /* -------------------------------------------------------------------- */
    3563           3 :     CPLString osFragment;
    3564             : 
    3565             :     osRSetVRT.Printf("<VRTDataset rasterXSize=\"%d\" rasterYSize=\"%d\">\n",
    3566           3 :                      GetRasterXSize() / 2, GetRasterYSize() / 2);
    3567             : 
    3568          12 :     for (int iBand = 0; iBand < GetRasterCount(); iBand++)
    3569             :     {
    3570           9 :         GDALRasterBand *poBand = GetRasterBand(iBand + 1);
    3571             : 
    3572             :         osRSetVRT += osFragment.Printf(
    3573             :             "  <VRTRasterBand dataType=\"%s\" band=\"%d\">\n",
    3574           9 :             GDALGetDataTypeName(poBand->GetRasterDataType()), iBand + 1);
    3575             : 
    3576          27 :         for (int i = 0; i < static_cast<int>(aosRSetFilenames.size()); i++)
    3577             :         {
    3578             :             char *pszEscaped =
    3579          18 :                 CPLEscapeString(aosRSetFilenames[i].c_str(), -1, CPLES_XML);
    3580          18 :             if (i == 0)
    3581             :                 osRSetVRT +=
    3582             :                     osFragment.Printf("    "
    3583             :                                       "<SimpleSource><SourceFilename>%s</"
    3584             :                                       "SourceFilename><SourceBand>%d</"
    3585             :                                       "SourceBand></SimpleSource>\n",
    3586           9 :                                       pszEscaped, iBand + 1);
    3587             :             else
    3588             :                 osRSetVRT += osFragment.Printf(
    3589             :                     "    "
    3590             :                     "<Overview><SourceFilename>%s</"
    3591             :                     "SourceFilename><SourceBand>%d</SourceBand></Overview>\n",
    3592           9 :                     pszEscaped, iBand + 1);
    3593          18 :             CPLFree(pszEscaped);
    3594             :         }
    3595           9 :         osRSetVRT += osFragment.Printf("  </VRTRasterBand>\n");
    3596             :     }
    3597             : 
    3598           3 :     osRSetVRT += "</VRTDataset>\n";
    3599             : 
    3600           3 :     return TRUE;
    3601             : }
    3602             : 
    3603             : /************************************************************************/
    3604             : /*                          IBuildOverviews()                           */
    3605             : /************************************************************************/
    3606             : 
    3607           5 : CPLErr NITFDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    3608             :                                     const int *panOverviewList, int nListBands,
    3609             :                                     const int *panBandList,
    3610             :                                     GDALProgressFunc pfnProgress,
    3611             :                                     void *pProgressData,
    3612             :                                     CSLConstList papszOptions)
    3613             : 
    3614             : {
    3615             :     /* -------------------------------------------------------------------- */
    3616             :     /*      If we have been using RSets we will need to clear them first.   */
    3617             :     /* -------------------------------------------------------------------- */
    3618           5 :     if (!osRSetVRT.empty())
    3619             :     {
    3620           1 :         oOvManager.CleanOverviews();
    3621           1 :         osRSetVRT = "";
    3622             :     }
    3623             : 
    3624           5 :     bExposeUnderlyingJPEGDatasetOverviews = FALSE;
    3625             : 
    3626             :     /* -------------------------------------------------------------------- */
    3627             :     /*      If we have an underlying JPEG2000 dataset (hopefully via        */
    3628             :     /*      JP2KAK) we will try and build zero overviews as a way of        */
    3629             :     /*      tricking it into clearing existing overviews-from-jpeg2000.     */
    3630             :     /* -------------------------------------------------------------------- */
    3631           7 :     if (poJ2KDataset != nullptr &&
    3632           2 :         !poJ2KDataset->GetMetadataItem("OVERVIEW_FILE", "OVERVIEWS"))
    3633           2 :         poJ2KDataset->BuildOverviews(pszResampling, 0, nullptr, nListBands,
    3634             :                                      panBandList, GDALDummyProgress, nullptr,
    3635             :                                      /* papszOptions = */ nullptr);
    3636             : 
    3637             :     /* -------------------------------------------------------------------- */
    3638             :     /*      Use the overview manager to build requested overviews.          */
    3639             :     /* -------------------------------------------------------------------- */
    3640           5 :     CPLErr eErr = GDALPamDataset::IBuildOverviews(
    3641             :         pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
    3642             :         pfnProgress, pProgressData, papszOptions);
    3643             : 
    3644             :     /* -------------------------------------------------------------------- */
    3645             :     /*      If we are working with jpeg or jpeg2000, let the underlying     */
    3646             :     /*      dataset know about the overview file.                           */
    3647             :     /* -------------------------------------------------------------------- */
    3648           5 :     GDALDataset *poSubDS = poJ2KDataset;
    3649           5 :     if (poJPEGDataset)
    3650           1 :         poSubDS = poJPEGDataset;
    3651             : 
    3652           5 :     const char *pszOverviewFile = GetMetadataItem("OVERVIEW_FILE", "OVERVIEWS");
    3653             : 
    3654           8 :     if (poSubDS && pszOverviewFile != nullptr && eErr == CE_None &&
    3655           3 :         poSubDS->GetMetadataItem("OVERVIEW_FILE", "OVERVIEWS") == nullptr)
    3656             :     {
    3657           3 :         poSubDS->SetMetadataItem("OVERVIEW_FILE", pszOverviewFile, "OVERVIEWS");
    3658             :     }
    3659             : 
    3660           5 :     return eErr;
    3661             : }
    3662             : 
    3663             : /************************************************************************/
    3664             : /*                           ScanJPEGQLevel()                           */
    3665             : /*                                                                      */
    3666             : /*      Search the NITF APP header in the jpeg data stream to find      */
    3667             : /*      out what predefined Q level tables should be used (or -1 if     */
    3668             : /*      they are inline).                                               */
    3669             : /************************************************************************/
    3670             : 
    3671          28 : int NITFDataset::ScanJPEGQLevel(GUIntBig *pnDataStart, bool *pbError)
    3672             : 
    3673             : {
    3674          28 :     if (VSIFSeekL(psFile->fp, *pnDataStart, SEEK_SET) != 0)
    3675             :     {
    3676           0 :         CPLError(CE_Failure, CPLE_FileIO, "Seek error to jpeg data stream.");
    3677           0 :         *pbError = true;
    3678           0 :         return 0;
    3679             :     }
    3680             : 
    3681             :     GByte abyHeader[100];
    3682          28 :     if (VSIFReadL(abyHeader, 1, sizeof(abyHeader), psFile->fp) <
    3683             :         sizeof(abyHeader))
    3684             :     {
    3685           0 :         CPLError(CE_Failure, CPLE_FileIO, "Read error to jpeg data stream.");
    3686           0 :         *pbError = true;
    3687           0 :         return 0;
    3688             :     }
    3689             : 
    3690             :     /* -------------------------------------------------------------------- */
    3691             :     /*      Scan ahead for jpeg magic code.  In some files (eg. NSIF)       */
    3692             :     /*      there seems to be some extra junk before the image data stream. */
    3693             :     /* -------------------------------------------------------------------- */
    3694          28 :     GUInt32 nOffset = 0;
    3695          28 :     while (nOffset < sizeof(abyHeader) - 23 &&
    3696          28 :            (abyHeader[nOffset + 0] != 0xff || abyHeader[nOffset + 1] != 0xd8 ||
    3697          28 :             abyHeader[nOffset + 2] != 0xff))
    3698           0 :         nOffset++;
    3699             : 
    3700          28 :     if (nOffset >= sizeof(abyHeader) - 23)
    3701             :     {
    3702           0 :         *pbError = true;
    3703           0 :         return 0;
    3704             :     }
    3705             : 
    3706          28 :     *pbError = false;
    3707          28 :     *pnDataStart += nOffset;
    3708             : 
    3709          28 :     if (nOffset > 0)
    3710           0 :         CPLDebug("NITF",
    3711             :                  "JPEG data stream at offset %d from start of data segment, "
    3712             :                  "NSIF?",
    3713             :                  nOffset);
    3714             : 
    3715             :     /* -------------------------------------------------------------------- */
    3716             :     /*      Do we have an NITF app tag?  If so, pull out the Q level.       */
    3717             :     /* -------------------------------------------------------------------- */
    3718          28 :     if (memcmp(abyHeader + nOffset + 6, "NITF\0", 5) != 0)
    3719           5 :         return 0;
    3720             : 
    3721          23 :     return abyHeader[22 + nOffset];
    3722             : }
    3723             : 
    3724             : /************************************************************************/
    3725             : /*                           ScanJPEGBlocks()                           */
    3726             : /************************************************************************/
    3727             : 
    3728           2 : CPLErr NITFDataset::ScanJPEGBlocks()
    3729             : 
    3730             : {
    3731           2 :     GUIntBig nJPEGStart =
    3732           2 :         psFile->pasSegmentInfo[psImage->iSegment].nSegmentStart;
    3733           2 :     bool bError = false;
    3734           2 :     nQLevel = ScanJPEGQLevel(&nJPEGStart, &bError);
    3735           2 :     if (bError)
    3736             :     {
    3737           0 :         return CE_Failure;
    3738             :     }
    3739             : 
    3740             :     /* -------------------------------------------------------------------- */
    3741             :     /*      Allocate offset array                                           */
    3742             :     /* -------------------------------------------------------------------- */
    3743           2 :     panJPEGBlockOffset = reinterpret_cast<GIntBig *>(VSI_CALLOC_VERBOSE(
    3744             :         sizeof(GIntBig), static_cast<size_t>(psImage->nBlocksPerRow) *
    3745             :                              psImage->nBlocksPerColumn));
    3746           2 :     if (panJPEGBlockOffset == nullptr)
    3747             :     {
    3748           0 :         return CE_Failure;
    3749             :     }
    3750           2 :     panJPEGBlockOffset[0] = nJPEGStart;
    3751             : 
    3752           2 :     if (psImage->nBlocksPerRow * psImage->nBlocksPerColumn == 1)
    3753           0 :         return CE_None;
    3754             : 
    3755           2 :     for (int iBlock = psImage->nBlocksPerRow * psImage->nBlocksPerColumn - 1;
    3756          44 :          iBlock > 0; iBlock--)
    3757          42 :         panJPEGBlockOffset[iBlock] = -1;
    3758             : 
    3759             :     /* -------------------------------------------------------------------- */
    3760             :     /*      Scan through the whole image data stream identifying all        */
    3761             :     /*      block boundaries.  Each block starts with 0xFFD8 (SOI).         */
    3762             :     /*      They also end with 0xFFD9, but we don't currently look for      */
    3763             :     /*      that.                                                           */
    3764             :     /* -------------------------------------------------------------------- */
    3765           2 :     int iNextBlock = 1;
    3766           2 :     GIntBig iSegOffset = 2;
    3767           2 :     if (psFile->pasSegmentInfo[psImage->iSegment].nSegmentSize <
    3768           2 :         nJPEGStart - psFile->pasSegmentInfo[psImage->iSegment].nSegmentStart)
    3769           0 :         return CE_Failure;
    3770           2 :     GIntBig iSegSize =
    3771           2 :         psFile->pasSegmentInfo[psImage->iSegment].nSegmentSize -
    3772           2 :         (nJPEGStart - psFile->pasSegmentInfo[psImage->iSegment].nSegmentStart);
    3773             :     GByte abyBlock[512];
    3774           2 :     int ignoreBytes = 0;
    3775             : 
    3776          65 :     while (iSegOffset < iSegSize - 1)
    3777             :     {
    3778             :         const size_t nReadSize = std::min(
    3779          65 :             sizeof(abyBlock), static_cast<size_t>(iSegSize - iSegOffset));
    3780             : 
    3781          65 :         if (VSIFSeekL(psFile->fp, panJPEGBlockOffset[0] + iSegOffset,
    3782          65 :                       SEEK_SET) != 0)
    3783             :         {
    3784           0 :             CPLError(CE_Failure, CPLE_FileIO,
    3785             :                      "Seek error to jpeg data stream.");
    3786           0 :             return CE_Failure;
    3787             :         }
    3788             : 
    3789          65 :         if (VSIFReadL(abyBlock, 1, nReadSize, psFile->fp) < (size_t)nReadSize)
    3790             :         {
    3791           0 :             CPLError(CE_Failure, CPLE_FileIO,
    3792             :                      "Read error to jpeg data stream.");
    3793           0 :             return CE_Failure;
    3794             :         }
    3795             : 
    3796       32563 :         for (size_t i = 0; i < nReadSize - 1; i++)
    3797             :         {
    3798       32500 :             if (ignoreBytes == 0)
    3799             :             {
    3800       32446 :                 if (abyBlock[i] == 0xff)
    3801             :                 {
    3802             :                     /* start-of-image marker */
    3803         759 :                     if (abyBlock[i + 1] == 0xd8)
    3804             :                     {
    3805          42 :                         panJPEGBlockOffset[iNextBlock++] =
    3806          42 :                             panJPEGBlockOffset[0] + iSegOffset + i;
    3807             : 
    3808          42 :                         if (iNextBlock ==
    3809          42 :                             psImage->nBlocksPerRow * psImage->nBlocksPerColumn)
    3810             :                         {
    3811           2 :                             return CE_None;
    3812             :                         }
    3813             :                     }
    3814             :                     /* Skip application-specific data to avoid false positive
    3815             :                      * while detecting */
    3816             :                     /* start-of-image markers (#2927). The size of the
    3817             :                      * application data is */
    3818             :                     /* found in the two following bytes */
    3819             :                     /* We need this complex mechanism of ignoreBytes for dealing
    3820             :                      * with */
    3821             :                     /* application data crossing several abyBlock ... */
    3822         717 :                     else if (abyBlock[i + 1] >= 0xe0 && abyBlock[i + 1] < 0xf0)
    3823             :                     {
    3824           2 :                         ignoreBytes = -2;
    3825             :                     }
    3826             :                 }
    3827             :             }
    3828          54 :             else if (ignoreBytes < 0)
    3829             :             {
    3830           4 :                 if (ignoreBytes == -1)
    3831             :                 {
    3832             :                     /* Size of the application data */
    3833           2 :                     ignoreBytes = abyBlock[i] * 256 + abyBlock[i + 1];
    3834             :                 }
    3835             :                 else
    3836           2 :                     ignoreBytes++;
    3837             :             }
    3838             :             else
    3839             :             {
    3840          50 :                 ignoreBytes--;
    3841             :             }
    3842             :         }
    3843             : 
    3844          63 :         iSegOffset += nReadSize - 1;
    3845             :     }
    3846             : 
    3847           0 :     return CE_None;
    3848             : }
    3849             : 
    3850             : /************************************************************************/
    3851             : /*                           ReadJPEGBlock()                            */
    3852             : /************************************************************************/
    3853             : 
    3854         128 : CPLErr NITFDataset::ReadJPEGBlock(int iBlockX, int iBlockY)
    3855             : 
    3856             : {
    3857             :     CPLErr eErr;
    3858             : 
    3859             :     /* -------------------------------------------------------------------- */
    3860             :     /*      If this is our first request, do a scan for block boundaries.   */
    3861             :     /* -------------------------------------------------------------------- */
    3862         128 :     if (panJPEGBlockOffset == nullptr)
    3863             :     {
    3864           3 :         if (EQUAL(psImage->szIC, "M3"))
    3865             :         {
    3866             :             /* --------------------------------------------------------------------
    3867             :              */
    3868             :             /*      When a data mask subheader is present, we don't need to scan
    3869             :              */
    3870             :             /*      the whole file. We just use the psImage->panBlockStart table
    3871             :              */
    3872             :             /* --------------------------------------------------------------------
    3873             :              */
    3874           1 :             panJPEGBlockOffset = reinterpret_cast<GIntBig *>(VSI_CALLOC_VERBOSE(
    3875             :                 sizeof(GIntBig), static_cast<size_t>(psImage->nBlocksPerRow) *
    3876             :                                      psImage->nBlocksPerColumn));
    3877           1 :             if (panJPEGBlockOffset == nullptr)
    3878             :             {
    3879           0 :                 return CE_Failure;
    3880             :             }
    3881           5 :             for (int i = 0;
    3882           5 :                  i < psImage->nBlocksPerRow * psImage->nBlocksPerColumn; i++)
    3883             :             {
    3884           4 :                 panJPEGBlockOffset[i] = psImage->panBlockStart[i];
    3885           4 :                 if (panJPEGBlockOffset[i] != -1 &&
    3886           4 :                     panJPEGBlockOffset[i] != UINT_MAX)
    3887             :                 {
    3888           4 :                     GUIntBig nOffset = panJPEGBlockOffset[i];
    3889           4 :                     bool bError = false;
    3890           4 :                     nQLevel = ScanJPEGQLevel(&nOffset, &bError);
    3891             :                     /* The beginning of the JPEG stream should be the offset */
    3892             :                     /* from the panBlockStart table */
    3893           4 :                     if (bError || nOffset != (GUIntBig)panJPEGBlockOffset[i])
    3894             :                     {
    3895           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    3896             :                                  "JPEG block doesn't start at expected offset");
    3897           0 :                         return CE_Failure;
    3898             :                     }
    3899             :                 }
    3900             :             }
    3901             :         }
    3902             :         else /* 'C3' case */
    3903             :         {
    3904             :             /* --------------------------------------------------------------------
    3905             :              */
    3906             :             /*      Scan through the whole image data stream identifying all */
    3907             :             /*      block boundaries. */
    3908             :             /* --------------------------------------------------------------------
    3909             :              */
    3910           2 :             eErr = ScanJPEGBlocks();
    3911           2 :             if (eErr != CE_None)
    3912           0 :                 return eErr;
    3913             :         }
    3914             :     }
    3915             : 
    3916             :     /* -------------------------------------------------------------------- */
    3917             :     /*    Allocate image data block (where the uncompressed image will go)  */
    3918             :     /* -------------------------------------------------------------------- */
    3919         128 :     if (pabyJPEGBlock == nullptr)
    3920             :     {
    3921             :         /* Allocate enough memory to hold 12bit JPEG data */
    3922           3 :         pabyJPEGBlock = reinterpret_cast<GByte *>(VSI_CALLOC_VERBOSE(
    3923             :             psImage->nBands, static_cast<size_t>(psImage->nBlockWidth) *
    3924             :                                  psImage->nBlockHeight * 2));
    3925           3 :         if (pabyJPEGBlock == nullptr)
    3926             :         {
    3927           0 :             return CE_Failure;
    3928             :         }
    3929             :     }
    3930             : 
    3931             :     /* -------------------------------------------------------------------- */
    3932             :     /*      Read JPEG Chunk.                                                */
    3933             :     /* -------------------------------------------------------------------- */
    3934         128 :     const int iBlock = iBlockX + iBlockY * psImage->nBlocksPerRow;
    3935             : 
    3936         128 :     if (panJPEGBlockOffset[iBlock] == -1 ||
    3937         128 :         panJPEGBlockOffset[iBlock] == UINT_MAX)
    3938             :     {
    3939           0 :         memset(pabyJPEGBlock, 0,
    3940           0 :                static_cast<size_t>(psImage->nBands) * psImage->nBlockWidth *
    3941           0 :                    psImage->nBlockHeight * 2);
    3942           0 :         return CE_None;
    3943             :     }
    3944             : 
    3945         256 :     CPLString osFilename;
    3946             :     osFilename.Printf("JPEG_SUBFILE:Q%d," CPL_FRMT_GIB ",%d,%s", nQLevel,
    3947         128 :                       panJPEGBlockOffset[iBlock], 0, osNITFFilename.c_str());
    3948             : 
    3949             :     GDALDataset *poDS =
    3950         128 :         GDALDataset::FromHandle(GDALOpen(osFilename, GA_ReadOnly));
    3951         128 :     if (poDS == nullptr)
    3952           0 :         return CE_Failure;
    3953             : 
    3954         256 :     if (poDS->GetRasterXSize() != psImage->nBlockWidth ||
    3955         128 :         poDS->GetRasterYSize() != psImage->nBlockHeight)
    3956             :     {
    3957           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3958             :                  "JPEG block %d not same size as NITF blocksize.", iBlock);
    3959           0 :         delete poDS;
    3960           0 :         return CE_Failure;
    3961             :     }
    3962             : 
    3963         128 :     if (poDS->GetRasterCount() < psImage->nBands)
    3964             :     {
    3965           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3966             :                  "JPEG block %d has not enough bands.", iBlock);
    3967           0 :         delete poDS;
    3968           0 :         return CE_Failure;
    3969             :     }
    3970             : 
    3971         128 :     if (poDS->GetRasterBand(1)->GetRasterDataType() !=
    3972         128 :         GetRasterBand(1)->GetRasterDataType())
    3973             :     {
    3974           0 :         CPLError(
    3975             :             CE_Failure, CPLE_AppDefined,
    3976             :             "JPEG block %d data type (%s) not consistent with band data type "
    3977             :             "(%s).",
    3978             :             iBlock,
    3979             :             GDALGetDataTypeName(poDS->GetRasterBand(1)->GetRasterDataType()),
    3980             :             GDALGetDataTypeName(GetRasterBand(1)->GetRasterDataType()));
    3981           0 :         delete poDS;
    3982           0 :         return CE_Failure;
    3983             :     }
    3984             : 
    3985         128 :     int anBands[3] = {1, 2, 3};
    3986         128 :     eErr = poDS->RasterIO(GF_Read, 0, 0, psImage->nBlockWidth,
    3987         128 :                           psImage->nBlockHeight, pabyJPEGBlock,
    3988         128 :                           psImage->nBlockWidth, psImage->nBlockHeight,
    3989             :                           GetRasterBand(1)->GetRasterDataType(),
    3990         128 :                           psImage->nBands, anBands, 0, 0, 0, nullptr);
    3991             : 
    3992         128 :     delete poDS;
    3993             : 
    3994         128 :     return eErr;
    3995             : }
    3996             : 
    3997             : /************************************************************************/
    3998             : /*                            GetFileList()                             */
    3999             : /************************************************************************/
    4000             : 
    4001         190 : char **NITFDataset::GetFileList()
    4002             : 
    4003             : {
    4004         190 :     char **papszFileList = GDALPamDataset::GetFileList();
    4005             : 
    4006             :     // Small optimization to avoid useless file probing.
    4007         190 :     if (CSLCount(papszFileList) == 0)
    4008           0 :         return papszFileList;
    4009             : 
    4010             :     /* -------------------------------------------------------------------- */
    4011             :     /*      Check for .imd file.                                            */
    4012             :     /* -------------------------------------------------------------------- */
    4013         190 :     papszFileList = AddFile(papszFileList, "IMD", "imd");
    4014             : 
    4015             :     /* -------------------------------------------------------------------- */
    4016             :     /*      Check for .rpb file.                                            */
    4017             :     /* -------------------------------------------------------------------- */
    4018         190 :     papszFileList = AddFile(papszFileList, "RPB", "rpb");
    4019             : 
    4020         190 :     if (!m_osRPCTXTFilename.empty())
    4021           3 :         papszFileList = CSLAddString(papszFileList, m_osRPCTXTFilename);
    4022             : 
    4023             :     /* -------------------------------------------------------------------- */
    4024             :     /*      Check for other files.                                          */
    4025             :     /* -------------------------------------------------------------------- */
    4026         190 :     papszFileList = AddFile(papszFileList, "ATT", "att");
    4027         190 :     papszFileList = AddFile(papszFileList, "EPH", "eph");
    4028         190 :     papszFileList = AddFile(papszFileList, "GEO", "geo");
    4029         190 :     papszFileList = AddFile(papszFileList, "XML", "xml");
    4030             : 
    4031         190 :     return papszFileList;
    4032             : }
    4033             : 
    4034             : /************************************************************************/
    4035             : /*                              AddFile()                               */
    4036             : /*                                                                      */
    4037             : /*      Helper method for GetFileList()                                 */
    4038             : /************************************************************************/
    4039        1140 : char **NITFDataset::AddFile(char **papszFileList, const char *EXTENSION,
    4040             :                             const char *extension)
    4041             : {
    4042             :     VSIStatBufL sStatBuf;
    4043        1140 :     CPLString osTarget = CPLResetExtension(osNITFFilename, EXTENSION);
    4044        1140 :     if (oOvManager.GetSiblingFiles() != nullptr)
    4045             :     {
    4046        1140 :         if (CSLFindStringCaseSensitive(oOvManager.GetSiblingFiles(),
    4047        1140 :                                        CPLGetFilename(osTarget)) >= 0)
    4048           0 :             papszFileList = CSLAddString(papszFileList, osTarget);
    4049             :         else
    4050             :         {
    4051        1140 :             osTarget = CPLResetExtension(osNITFFilename, extension);
    4052        1140 :             if (CSLFindStringCaseSensitive(oOvManager.GetSiblingFiles(),
    4053        1140 :                                            CPLGetFilename(osTarget)) >= 0)
    4054           0 :                 papszFileList = CSLAddString(papszFileList, osTarget);
    4055             :         }
    4056             :     }
    4057             :     else
    4058             :     {
    4059           0 :         if (VSIStatL(osTarget, &sStatBuf) == 0)
    4060           0 :             papszFileList = CSLAddString(papszFileList, osTarget);
    4061             :         else
    4062             :         {
    4063           0 :             osTarget = CPLResetExtension(osNITFFilename, extension);
    4064           0 :             if (VSIStatL(osTarget, &sStatBuf) == 0)
    4065           0 :                 papszFileList = CSLAddString(papszFileList, osTarget);
    4066             :         }
    4067             :     }
    4068             : 
    4069        2280 :     return papszFileList;
    4070             : }
    4071             : 
    4072             : /************************************************************************/
    4073             : /*                         GDALToNITFDataType()                         */
    4074             : /************************************************************************/
    4075             : 
    4076         282 : static const char *GDALToNITFDataType(GDALDataType eType)
    4077             : 
    4078             : {
    4079         282 :     const char *pszPVType = nullptr;
    4080             : 
    4081         282 :     switch (eType)
    4082             :     {
    4083         245 :         case GDT_Byte:
    4084             :         case GDT_UInt16:
    4085             :         case GDT_UInt32:
    4086         245 :             pszPVType = "INT";
    4087         245 :             break;
    4088             : 
    4089          10 :         case GDT_Int16:
    4090             :         case GDT_Int32:
    4091          10 :             pszPVType = "SI";
    4092          10 :             break;
    4093             : 
    4094           9 :         case GDT_Float32:
    4095             :         case GDT_Float64:
    4096           9 :             pszPVType = "R";
    4097           9 :             break;
    4098             : 
    4099           6 :         case GDT_CInt16:
    4100             :         case GDT_CInt32:
    4101           6 :             CPLError(CE_Failure, CPLE_AppDefined,
    4102             :                      "NITF format does not support complex integer data.");
    4103           6 :             return nullptr;
    4104             : 
    4105           3 :         case GDT_CFloat32:
    4106           3 :             pszPVType = "C";
    4107           3 :             break;
    4108             : 
    4109           9 :         default:
    4110           9 :             CPLError(CE_Failure, CPLE_AppDefined,
    4111             :                      "Unsupported raster pixel type (%s).",
    4112             :                      GDALGetDataTypeName(eType));
    4113           9 :             return nullptr;
    4114             :     }
    4115             : 
    4116         267 :     return pszPVType;
    4117             : }
    4118             : 
    4119             : /************************************************************************/
    4120             : /*                          NITFJP2ECWOptions()                         */
    4121             : /*                                                                      */
    4122             : /*      Prepare JP2-in-NITF creation options based in part of the       */
    4123             : /*      NITF creation options.                                          */
    4124             : /************************************************************************/
    4125             : 
    4126           4 : static char **NITFJP2ECWOptions(char **papszOptions)
    4127             : 
    4128             : {
    4129           4 :     char **papszJP2Options = CSLAddString(nullptr, "PROFILE=NPJE");
    4130           4 :     papszJP2Options = CSLAddString(papszJP2Options, "CODESTREAM_ONLY=TRUE");
    4131             : 
    4132          19 :     for (int i = 0; papszOptions != nullptr && papszOptions[i] != nullptr; i++)
    4133             :     {
    4134          15 :         if (STARTS_WITH_CI(papszOptions[i], "PROFILE="))
    4135             :         {
    4136           0 :             CPLFree(papszJP2Options[0]);
    4137           0 :             papszJP2Options[0] = CPLStrdup(papszOptions[i]);
    4138             :         }
    4139          15 :         else if (STARTS_WITH_CI(papszOptions[i], "TARGET="))
    4140           3 :             papszJP2Options = CSLAddString(papszJP2Options, papszOptions[i]);
    4141             :     }
    4142             : 
    4143           4 :     return papszJP2Options;
    4144             : }
    4145             : 
    4146             : /************************************************************************/
    4147             : /*                           NITFJP2KAKOptions()                        */
    4148             : /*                                                                      */
    4149             : /*      Prepare JP2-in-NITF creation options based in part of the       */
    4150             : /*      NITF creation options.                                          */
    4151             : /************************************************************************/
    4152             : 
    4153           0 : static char **NITFJP2KAKOptions(char **papszOptions, int nABPP)
    4154             : 
    4155             : {
    4156           0 :     char **papszJP2Options = CSLAddString(nullptr, "CODEC=J2K");
    4157             : 
    4158           0 :     for (int i = 0; papszOptions != nullptr && papszOptions[i] != nullptr; i++)
    4159             :     {
    4160           0 :         if (STARTS_WITH_CI(papszOptions[i], "QUALITY=") ||
    4161           0 :             STARTS_WITH_CI(papszOptions[i], "BLOCKXSIZE=") ||
    4162           0 :             STARTS_WITH_CI(papszOptions[i], "BLOCKYSIZE=") ||
    4163           0 :             STARTS_WITH_CI(papszOptions[i], "LAYERS=") ||
    4164           0 :             STARTS_WITH_CI(papszOptions[i], "ROI="))
    4165             :         {
    4166           0 :             papszJP2Options = CSLAddString(papszJP2Options, papszOptions[i]);
    4167             :         }
    4168             :     }
    4169             : 
    4170             :     papszJP2Options =
    4171           0 :         CSLSetNameValue(papszJP2Options, "NBITS", CPLSPrintf("%d", nABPP));
    4172             : 
    4173           0 :     return papszJP2Options;
    4174             : }
    4175             : 
    4176             : /************************************************************************/
    4177             : /*                      NITFJP2OPENJPEGOptions()                        */
    4178             : /*                                                                      */
    4179             : /*      Prepare JP2-in-NITF creation options based in part of the       */
    4180             : /*      NITF creation options.                                          */
    4181             : /************************************************************************/
    4182             : 
    4183           8 : static char **NITFJP2OPENJPEGOptions(GDALDriver *poJ2KDriver,
    4184             :                                      CSLConstList papszOptions, int nABPP)
    4185             : 
    4186             : {
    4187           8 :     char **papszJP2Options = CSLAddString(nullptr, "CODEC=J2K");
    4188             : 
    4189           8 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    4190           8 :     double dfQuality = 0;
    4191           8 :     if (pszQuality)
    4192             :     {
    4193          16 :         for (const char *pszVal :
    4194          13 :              CPLStringList(CSLTokenizeString2(pszQuality, ",", 0)))
    4195           8 :             dfQuality = std::max(dfQuality, CPLAtof(pszVal));
    4196             :     }
    4197             : 
    4198             :     double dfTarget =
    4199           8 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "TARGET", "0"));
    4200             : 
    4201           8 :     if (dfTarget > 0 && dfTarget < 100)
    4202           0 :         dfQuality = 100. - dfTarget;
    4203             : 
    4204          63 :     for (int i = 0; papszOptions != nullptr && papszOptions[i] != nullptr; i++)
    4205             :     {
    4206          55 :         if (STARTS_WITH_CI(papszOptions[i], "BLOCKXSIZE=") ||
    4207          50 :             STARTS_WITH_CI(papszOptions[i], "BLOCKYSIZE="))
    4208             :         {
    4209          10 :             papszJP2Options = CSLAddString(papszJP2Options, papszOptions[i]);
    4210             :         }
    4211             :     }
    4212             : 
    4213             :     // Set it now before the NPJE profiles have a chance to override it
    4214           8 :     if (pszQuality)
    4215             :     {
    4216             :         papszJP2Options =
    4217           5 :             CSLSetNameValue(papszJP2Options, "QUALITY", pszQuality);
    4218             :     }
    4219             : 
    4220           8 :     const char *pszProfile = CSLFetchNameValueDef(papszOptions, "PROFILE", "");
    4221           8 :     if (STARTS_WITH_CI(pszProfile, "NPJE"))
    4222             :     {
    4223             :         // Follow STDI-0006 NCDRD "2.3 Data Compression - JPEG 2000" and
    4224             :         // ISO/IEC BIIF Profile BPJ2K01.10
    4225             :         // (https://nsgreg.nga.mil/doc/view?i=2031&month=3&day=22&year=2021),
    4226             :         // for NPJE (Appendix D ) profile
    4227             : 
    4228           4 :         if (pszQuality && strchr(pszQuality, ','))
    4229             :         {
    4230           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    4231             :                      "Only largest value of QUALITY used when PROFILE=%s "
    4232             :                      "is specified",
    4233             :                      pszProfile);
    4234             :         }
    4235             : 
    4236             :         papszJP2Options =
    4237           4 :             CSLAddString(papszJP2Options, "@BLOCKSIZE_STRICT=YES");
    4238             : 
    4239             :         // Empty PRECINCTS option to ask for no custom precincts
    4240           4 :         papszJP2Options = CSLAddString(papszJP2Options, "PRECINCTS=");
    4241             : 
    4242             :         // See Table 2.3-3 - Target Bit Rates for Each Tile in Panchromatic
    4243             :         // Image Segments of STDI-0006
    4244             :         std::vector<double> adfBPP = {
    4245             :             0.03125, 0.0625, 0.125, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
    4246           8 :             1.1,     1.2,    1.3,   1.5,  1.7, 2.0, 2.3, 3.5, 3.9};
    4247           4 :         if (STARTS_WITH_CI(pszProfile, "NPJE_NUMERICALLY_LOSSLESS"))
    4248             :         {
    4249             :             // given that we consider a compression ratio afterwards, we
    4250             :             // arbitrarily consider a Byte datatype, and thus lossless quality
    4251             :             // is achieved at worse with 8 bpp
    4252           2 :             adfBPP.push_back(8.0);
    4253             : 
    4254             :             // Lossless 5x3 wavelet
    4255           2 :             papszJP2Options = CSLAddString(papszJP2Options, "REVERSIBLE=YES");
    4256             :         }
    4257             : 
    4258           4 :         std::string osQuality;
    4259          80 :         for (double dfBPP : adfBPP)
    4260             :         {
    4261          77 :             if (!osQuality.empty())
    4262          73 :                 osQuality += ',';
    4263             :             // the JP2OPENJPEG QUALITY setting is 100. / compression_ratio
    4264             :             // and compression_ratio = 8 / bpp
    4265          77 :             double dfLayerQuality = 100.0 / (8.0 / dfBPP);
    4266          77 :             if (dfLayerQuality > dfQuality && dfQuality != 0.0)
    4267             :             {
    4268           1 :                 osQuality += CPLSPrintf("%f", dfQuality);
    4269           1 :                 break;
    4270             :             }
    4271          76 :             osQuality += CPLSPrintf("%f", dfLayerQuality);
    4272             :         }
    4273             :         papszJP2Options =
    4274           4 :             CSLSetNameValue(papszJP2Options, "QUALITY", osQuality.c_str());
    4275             : 
    4276           4 :         papszJP2Options = CSLAddString(papszJP2Options, "PROGRESSION=LRCP");
    4277             : 
    4278             :         // Disable MCT
    4279           4 :         papszJP2Options = CSLAddString(papszJP2Options, "YCC=NO");
    4280             : 
    4281             :         // TLM option added in OpenJPEG 2.5
    4282           4 :         if (strstr(poJ2KDriver->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST),
    4283           4 :                    "TLM") != nullptr)
    4284             :         {
    4285           0 :             papszJP2Options = CSLAddString(papszJP2Options, "PLT=YES");
    4286           0 :             papszJP2Options = CSLAddString(papszJP2Options, "TLM=YES");
    4287             :         }
    4288             :         else
    4289             :         {
    4290           4 :             CPLError(CE_Warning, CPLE_AppDefined,
    4291             :                      "TLM option not available in JP2OPENJPEG driver. "
    4292             :                      "Use OpenJPEG 2.5 or later");
    4293             :         }
    4294             : 
    4295           4 :         papszJP2Options = CSLAddString(papszJP2Options, "RESOLUTIONS=6");
    4296             :     }
    4297           4 :     else if (EQUAL(pszProfile, "PROFILE_1"))
    4298             :     {
    4299           0 :         papszJP2Options = CSLAddString(papszJP2Options, "PROFILE=PROFILE_1");
    4300             :     }
    4301           4 :     else if (EQUAL(pszProfile, "PROFILE_2"))
    4302             :     {
    4303           0 :         papszJP2Options = CSLAddString(papszJP2Options, "PROFILE=UNRESTRICTED");
    4304             :     }
    4305             : 
    4306             :     papszJP2Options =
    4307           8 :         CSLSetNameValue(papszJP2Options, "NBITS", CPLSPrintf("%d", nABPP));
    4308             : 
    4309           8 :     return papszJP2Options;
    4310             : }
    4311             : 
    4312             : /************************************************************************/
    4313             : /*              NITFExtractTEXTAndCGMCreationOption()                   */
    4314             : /************************************************************************/
    4315             : 
    4316         282 : static char **NITFExtractTEXTAndCGMCreationOption(GDALDataset *poSrcDS,
    4317             :                                                   char **papszOptions,
    4318             :                                                   char ***ppapszTextMD,
    4319             :                                                   char ***ppapszCgmMD)
    4320             : {
    4321         282 :     char **papszFullOptions = CSLDuplicate(papszOptions);
    4322             : 
    4323             :     /* -------------------------------------------------------------------- */
    4324             :     /*      Prepare for text segments.                                      */
    4325             :     /* -------------------------------------------------------------------- */
    4326         282 :     char **papszTextMD = CSLFetchNameValueMultiple(papszOptions, "TEXT");
    4327             :     // Notice: CSLFetchNameValueMultiple remove the leading "TEXT=" when
    4328             :     // returning the list, which is what we want.
    4329             : 
    4330             :     // Use TEXT information from original image if no creation option is passed
    4331             :     // in.
    4332         282 :     if (poSrcDS != nullptr && papszTextMD == nullptr)
    4333             :     {
    4334             :         // Read CGM adata from original image, duplicate the list because
    4335             :         // we frees papszCgmMD at end of the function.
    4336         119 :         papszTextMD = CSLDuplicate(poSrcDS->GetMetadata("TEXT"));
    4337             :     }
    4338             : 
    4339         282 :     int nNUMT = 0;
    4340         290 :     for (int iOpt = 0; papszTextMD != nullptr && papszTextMD[iOpt] != nullptr;
    4341             :          iOpt++)
    4342             :     {
    4343           8 :         if (!STARTS_WITH_CI(papszTextMD[iOpt], "DATA_"))
    4344           3 :             continue;
    4345             : 
    4346           5 :         nNUMT++;
    4347             :     }
    4348             : 
    4349         282 :     if (nNUMT > 0)
    4350             :     {
    4351           4 :         papszFullOptions = CSLAddString(papszFullOptions,
    4352           8 :                                         CPLString().Printf("NUMT=%d", nNUMT));
    4353             :     }
    4354             : 
    4355             :     /* -------------------------------------------------------------------- */
    4356             :     /*      Prepare for CGM segments.                                       */
    4357             :     /* -------------------------------------------------------------------- */
    4358         282 :     char **papszCgmMD = CSLFetchNameValueMultiple(papszOptions, "CGM");
    4359             :     // Notice: CSLFetchNameValueMultiple remove the leading "CGM=" when
    4360             :     // returning the list, which is what we want.
    4361             : 
    4362             :     // Use CGM information from original image if no creation option is passed
    4363             :     // in.
    4364         282 :     if (poSrcDS != nullptr && papszCgmMD == nullptr)
    4365             :     {
    4366             :         // Read CGM adata from original image, duplicate the list because
    4367             :         // we frees papszCgmMD at end of the function.
    4368         119 :         papszCgmMD = CSLDuplicate(poSrcDS->GetMetadata("CGM"));
    4369             :     }
    4370             : 
    4371             :     // Set NUMS based on the number of segments
    4372             :     const char *pszNUMS;  // graphic segment option string
    4373         282 :     int nNUMS = 0;
    4374         282 :     if (papszCgmMD != nullptr)
    4375             :     {
    4376          12 :         pszNUMS = CSLFetchNameValue(papszCgmMD, "SEGMENT_COUNT");
    4377             : 
    4378          12 :         if (pszNUMS != nullptr)
    4379             :         {
    4380          12 :             nNUMS = atoi(pszNUMS);
    4381             :         }
    4382          12 :         papszFullOptions = CSLAddString(papszFullOptions,
    4383          24 :                                         CPLString().Printf("NUMS=%d", nNUMS));
    4384             :     }
    4385             : 
    4386         282 :     *ppapszTextMD = papszTextMD;
    4387         282 :     *ppapszCgmMD = papszCgmMD;
    4388             : 
    4389         282 :     return papszFullOptions;
    4390             : }
    4391             : 
    4392             : /************************************************************************/
    4393             : /*                         NITFDatasetCreate()                          */
    4394             : /************************************************************************/
    4395             : 
    4396         174 : GDALDataset *NITFDataset::NITFDatasetCreate(const char *pszFilename, int nXSize,
    4397             :                                             int nYSize, int nBandsIn,
    4398             :                                             GDALDataType eType,
    4399             :                                             char **papszOptions)
    4400             : 
    4401             : {
    4402         174 :     const char *pszPVType = GDALToNITFDataType(eType);
    4403         174 :     if (pszPVType == nullptr)
    4404          12 :         return nullptr;
    4405             : 
    4406         162 :     const char *pszIC = CSLFetchNameValue(papszOptions, "IC");
    4407             : 
    4408             :     /* -------------------------------------------------------------------- */
    4409             :     /*      We disallow any IC value except NC when creating this way.      */
    4410             :     /* -------------------------------------------------------------------- */
    4411         162 :     GDALDriver *poJ2KDriver = nullptr;
    4412             : 
    4413         162 :     if (pszIC != nullptr && EQUAL(pszIC, "C8"))
    4414             :     {
    4415           1 :         bool bHasCreate = false;
    4416             : 
    4417           1 :         poJ2KDriver = GetGDALDriverManager()->GetDriverByName("JP2ECW");
    4418           1 :         if (poJ2KDriver != nullptr)
    4419           1 :             bHasCreate = poJ2KDriver->GetMetadataItem(GDAL_DCAP_CREATE,
    4420           1 :                                                       nullptr) != nullptr;
    4421           1 :         if (!bHasCreate)
    4422             :         {
    4423           0 :             CPLError(
    4424             :                 CE_Failure, CPLE_AppDefined,
    4425             :                 "Unable to create JPEG2000 encoded NITF files.  The\n"
    4426             :                 "JP2ECW driver is unavailable, or missing Create support.");
    4427           0 :             return nullptr;
    4428             :         }
    4429             : 
    4430           1 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "J2KLRA", "NO")))
    4431             :         {
    4432           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    4433             :                      "J2KLRA TRE can only be written in CreateCopy() mode, and "
    4434             :                      "when using the JP2OPENJPEG driver in NPJE profiles");
    4435           1 :         }
    4436             :     }
    4437             : 
    4438         161 :     else if (pszIC != nullptr && !EQUAL(pszIC, "NC"))
    4439             :     {
    4440           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    4441             :                  "Unsupported compression (IC=%s) used in direct\n"
    4442             :                  "NITF File creation",
    4443             :                  pszIC);
    4444           0 :         return nullptr;
    4445             :     }
    4446             : 
    4447         162 :     const char *const apszIgnoredOptions[] = {"SDE_TRE", "RPC00B", "RPCTXT",
    4448             :                                               nullptr};
    4449         648 :     for (int i = 0; apszIgnoredOptions[i] != nullptr; ++i)
    4450             :     {
    4451         486 :         if (CSLFetchNameValue(papszOptions, apszIgnoredOptions[i]))
    4452             :         {
    4453           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    4454             :                      "%s creation option ignored by Create() method "
    4455             :                      "(only valid in CreateCopy())",
    4456           0 :                      apszIgnoredOptions[i]);
    4457             :         }
    4458             :     }
    4459             : 
    4460             :     /* -------------------------------------------------------------------- */
    4461             :     /*      Prepare for text and CGM segments.                              */
    4462             :     /* -------------------------------------------------------------------- */
    4463         162 :     char **papszTextMD = nullptr;
    4464         162 :     char **papszCgmMD = nullptr;
    4465         162 :     char **papszFullOptions = NITFExtractTEXTAndCGMCreationOption(
    4466             :         nullptr, papszOptions, &papszTextMD, &papszCgmMD);
    4467             : 
    4468         162 :     const char *pszBlockSize = CSLFetchNameValue(papszFullOptions, "BLOCKSIZE");
    4469         162 :     if (pszBlockSize != nullptr &&
    4470           0 :         CSLFetchNameValue(papszFullOptions, "BLOCKXSIZE") == nullptr)
    4471             :     {
    4472             :         papszFullOptions =
    4473           0 :             CSLSetNameValue(papszFullOptions, "BLOCKXSIZE", pszBlockSize);
    4474             :     }
    4475         162 :     if (pszBlockSize != nullptr &&
    4476           0 :         CSLFetchNameValue(papszFullOptions, "BLOCKYSIZE") == nullptr)
    4477             :     {
    4478             :         papszFullOptions =
    4479           0 :             CSLSetNameValue(papszFullOptions, "BLOCKYSIZE", pszBlockSize);
    4480             :     }
    4481             : 
    4482         162 :     if (const char *pszNBITS = CSLFetchNameValue(papszFullOptions, "NBITS"))
    4483             :     {
    4484           1 :         papszFullOptions = CSLSetNameValue(papszFullOptions, "ABPP", pszNBITS);
    4485             :     }
    4486             : 
    4487             :     /* -------------------------------------------------------------------- */
    4488             :     /*      Create the file.                                                */
    4489             :     /* -------------------------------------------------------------------- */
    4490             : 
    4491         162 :     int nIMIndex = 0;
    4492         162 :     int nImageCount = 0;
    4493         162 :     vsi_l_offset nImageOffset = 0;
    4494         162 :     vsi_l_offset nICOffset = 0;
    4495         162 :     if (!NITFCreateEx(pszFilename, nXSize, nYSize, nBandsIn,
    4496             :                       GDALGetDataTypeSize(eType), pszPVType, papszFullOptions,
    4497             :                       &nIMIndex, &nImageCount, &nImageOffset, &nICOffset))
    4498             :     {
    4499           3 :         CSLDestroy(papszTextMD);
    4500           3 :         CSLDestroy(papszCgmMD);
    4501           3 :         CSLDestroy(papszFullOptions);
    4502           3 :         return nullptr;
    4503             :     }
    4504             : 
    4505             :     /* -------------------------------------------------------------------- */
    4506             :     /*      Various special hacks related to JPEG2000 encoded files.        */
    4507             :     /* -------------------------------------------------------------------- */
    4508         159 :     GDALDataset *poWritableJ2KDataset = nullptr;
    4509         159 :     if (poJ2KDriver)
    4510             :     {
    4511           1 :         CPLString osDSName;
    4512             : 
    4513             :         osDSName.Printf("/vsisubfile/" CPL_FRMT_GUIB "_%d,%s",
    4514           1 :                         static_cast<GUIntBig>(nImageOffset), -1, pszFilename);
    4515             : 
    4516           1 :         char **papszJP2Options = NITFJP2ECWOptions(papszFullOptions);
    4517           1 :         poWritableJ2KDataset = poJ2KDriver->Create(
    4518             :             osDSName, nXSize, nYSize, nBandsIn, eType, papszJP2Options);
    4519           1 :         CSLDestroy(papszJP2Options);
    4520             : 
    4521           1 :         if (poWritableJ2KDataset == nullptr)
    4522             :         {
    4523           0 :             CSLDestroy(papszTextMD);
    4524           0 :             CSLDestroy(papszCgmMD);
    4525           0 :             return nullptr;
    4526             :         }
    4527             :     }
    4528         159 :     CSLDestroy(papszFullOptions);
    4529             : 
    4530             :     /* -------------------------------------------------------------------- */
    4531             :     /*      Open the dataset in update mode.                                */
    4532             :     /* -------------------------------------------------------------------- */
    4533         159 :     GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
    4534         159 :     NITFDataset *poDS = NITFDataset::OpenInternal(
    4535             :         &oOpenInfo, poWritableJ2KDataset, true, nIMIndex);
    4536         159 :     if (poDS)
    4537             :     {
    4538         159 :         poDS->m_nImageOffset = nImageOffset;
    4539         159 :         poDS->m_nIMIndex = nIMIndex;
    4540         159 :         poDS->m_nImageCount = nImageCount;
    4541         159 :         poDS->m_nICOffset = nICOffset;
    4542         159 :         poDS->papszTextMDToWrite = papszTextMD;
    4543         159 :         poDS->papszCgmMDToWrite = papszCgmMD;
    4544         159 :         poDS->aosCreationOptions.Assign(CSLDuplicate(papszOptions), true);
    4545             :     }
    4546             :     else
    4547             :     {
    4548           0 :         CSLDestroy(papszTextMD);
    4549           0 :         CSLDestroy(papszCgmMD);
    4550             :     }
    4551         159 :     return poDS;
    4552             : }
    4553             : 
    4554             : /************************************************************************/
    4555             : /*                           NITFCreateCopy()                           */
    4556             : /************************************************************************/
    4557             : 
    4558         121 : GDALDataset *NITFDataset::NITFCreateCopy(const char *pszFilename,
    4559             :                                          GDALDataset *poSrcDS, int bStrict,
    4560             :                                          char **papszOptions,
    4561             :                                          GDALProgressFunc pfnProgress,
    4562             :                                          void *pProgressData)
    4563             : 
    4564             : {
    4565             : 
    4566         121 :     int nBands = poSrcDS->GetRasterCount();
    4567         121 :     if (nBands == 0)
    4568             :     {
    4569           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    4570             :                  "Unable to export files with zero bands.");
    4571           1 :         return nullptr;
    4572             :     }
    4573             : 
    4574         120 :     GDALRasterBand *poBand1 = poSrcDS->GetRasterBand(1);
    4575         120 :     if (poBand1 == nullptr)
    4576             :     {
    4577           0 :         return nullptr;
    4578             :     }
    4579             : 
    4580             :     /* -------------------------------------------------------------------- */
    4581             :     /*      Only allow supported compression values.                        */
    4582             :     /* -------------------------------------------------------------------- */
    4583         120 :     bool bJPEG2000 = false;
    4584         120 :     bool bJPEG = false;
    4585         120 :     GDALDriver *poJ2KDriver = nullptr;
    4586             :     const char *pszJPEG2000_DRIVER =
    4587         120 :         CSLFetchNameValue(papszOptions, "JPEG2000_DRIVER");
    4588         120 :     if (pszJPEG2000_DRIVER != nullptr)
    4589             :         poJ2KDriver =
    4590           4 :             GetGDALDriverManager()->GetDriverByName(pszJPEG2000_DRIVER);
    4591             : 
    4592         120 :     const char *pszIC = CSLFetchNameValue(papszOptions, "IC");
    4593         120 :     if (pszIC != nullptr)
    4594             :     {
    4595          21 :         if (EQUAL(pszIC, "NC"))
    4596             :             /* ok */;
    4597          21 :         else if (EQUAL(pszIC, "C8"))
    4598             :         {
    4599          11 :             if (pszJPEG2000_DRIVER == nullptr)
    4600             :             {
    4601           7 :                 poJ2KDriver = GetGDALDriverManager()->GetDriverByName("JP2ECW");
    4602          10 :                 if (poJ2KDriver == nullptr ||
    4603           3 :                     poJ2KDriver->GetMetadataItem(GDAL_DCAP_CREATECOPY,
    4604           3 :                                                  nullptr) == nullptr)
    4605             :                 {
    4606             :                     /* Try with  JP2KAK as an alternate driver */
    4607             :                     poJ2KDriver =
    4608           4 :                         GetGDALDriverManager()->GetDriverByName("JP2KAK");
    4609             :                 }
    4610           7 :                 if (poJ2KDriver == nullptr)
    4611             :                 {
    4612             :                     /* Try with JP2OPENJPEG as an alternate driver */
    4613             :                     poJ2KDriver =
    4614           4 :                         GetGDALDriverManager()->GetDriverByName("JP2OPENJPEG");
    4615             :                 }
    4616             :             }
    4617          11 :             if (poJ2KDriver == nullptr)
    4618             :             {
    4619           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    4620             :                          "Unable to write JPEG2000 compressed NITF file.\n"
    4621             :                          "No 'subfile' JPEG2000 write supporting drivers are\n"
    4622             :                          "configured.");
    4623           0 :                 return nullptr;
    4624             :             }
    4625             : 
    4626          11 :             if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "J2KLRA", "NO")))
    4627             :             {
    4628           0 :                 if (!EQUAL(poJ2KDriver->GetDescription(), "JP2OPENJPEG"))
    4629             :                 {
    4630           0 :                     CPLError(
    4631             :                         CE_Warning, CPLE_NotSupported,
    4632             :                         "J2KLRA TRE can only be written "
    4633             :                         "when using the JP2OPENJPEG driver in NPJE profiles");
    4634             :                 }
    4635           0 :                 else if (!STARTS_WITH_CI(
    4636             :                              CSLFetchNameValueDef(papszOptions, "PROFILE", ""),
    4637             :                              "NPJE"))
    4638             :                 {
    4639           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    4640             :                              "J2KLRA TRE can only be written in NPJE profiles");
    4641             :                 }
    4642             :             }
    4643          11 :             bJPEG2000 = TRUE;
    4644             :         }
    4645          10 :         else if (EQUAL(pszIC, "C3") || EQUAL(pszIC, "M3"))
    4646             :         {
    4647          10 :             bJPEG = TRUE;
    4648             : #ifndef JPEG_SUPPORTED
    4649             :             CPLError(CE_Failure, CPLE_AppDefined,
    4650             :                      "Unable to write JPEG compressed NITF file.\n"
    4651             :                      "Libjpeg is not configured into build.");
    4652             :             return nullptr;
    4653             : #endif
    4654             :         }
    4655             :         else
    4656             :         {
    4657           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4658             :                      "Only IC=NC (uncompressed), IC=C3/M3 (JPEG) and IC=C8 "
    4659             :                      "(JPEG2000)\n"
    4660             :                      "allowed with NITF CreateCopy method.");
    4661           0 :             return nullptr;
    4662             :         }
    4663             :     }
    4664             : 
    4665             :     /* -------------------------------------------------------------------- */
    4666             :     /*      Get the data type.  Complex integers isn't supported by         */
    4667             :     /*      NITF, so map that to complex float if we aren't in strict       */
    4668             :     /*      mode.                                                           */
    4669             :     /* -------------------------------------------------------------------- */
    4670         120 :     GDALDataType eType = poBand1->GetRasterDataType();
    4671         120 :     if (!bStrict && (eType == GDT_CInt16 || eType == GDT_CInt32))
    4672           0 :         eType = GDT_CFloat32;
    4673             : 
    4674             :     /* -------------------------------------------------------------------- */
    4675             :     /*      Prepare for text and CGM segments.                              */
    4676             :     /* -------------------------------------------------------------------- */
    4677         120 :     char **papszTextMD = nullptr;
    4678         120 :     char **papszCgmMD = nullptr;
    4679         120 :     char **papszFullOptions = NITFExtractTEXTAndCGMCreationOption(
    4680             :         poSrcDS, papszOptions, &papszTextMD, &papszCgmMD);
    4681             : 
    4682         120 :     const char *pszBlockSize = CSLFetchNameValue(papszFullOptions, "BLOCKSIZE");
    4683         123 :     if (pszBlockSize != nullptr &&
    4684           3 :         CSLFetchNameValue(papszFullOptions, "BLOCKXSIZE") == nullptr)
    4685             :     {
    4686             :         papszFullOptions =
    4687           3 :             CSLSetNameValue(papszFullOptions, "BLOCKXSIZE", pszBlockSize);
    4688             :     }
    4689         123 :     if (pszBlockSize != nullptr &&
    4690           3 :         CSLFetchNameValue(papszFullOptions, "BLOCKYSIZE") == nullptr)
    4691             :     {
    4692             :         papszFullOptions =
    4693           3 :             CSLSetNameValue(papszFullOptions, "BLOCKYSIZE", pszBlockSize);
    4694             :     }
    4695             : 
    4696             :     /* -------------------------------------------------------------------- */
    4697             :     /*      Copy over other source metadata items as creation options       */
    4698             :     /*      that seem useful, unless they are already set as creation       */
    4699             :     /*      options.                                                        */
    4700             :     /* -------------------------------------------------------------------- */
    4701             :     const bool bUseSrcNITFMetadata =
    4702         120 :         CPLFetchBool(papszOptions, "USE_SRC_NITF_METADATA", true);
    4703         120 :     char **papszSrcMD = poSrcDS->GetMetadata();
    4704             : 
    4705         858 :     for (int iMD = 0; bUseSrcNITFMetadata && papszSrcMD && papszSrcMD[iMD];
    4706             :          iMD++)
    4707             :     {
    4708         738 :         bool bPreserveSrcMDAsCreationOption = false;
    4709         738 :         if (STARTS_WITH_CI(papszSrcMD[iMD], "NITF_BLOCKA"))
    4710             :         {
    4711          30 :             bPreserveSrcMDAsCreationOption =
    4712          50 :                 CSLPartialFindString(papszOptions, "BLOCKA_") < 0 &&
    4713          20 :                 CSLPartialFindString(papszOptions, "TRE=BLOCKA=") < 0;
    4714             :         }
    4715         708 :         else if (STARTS_WITH_CI(papszSrcMD[iMD], "NITF_FHDR"))
    4716             :         {
    4717          10 :             bPreserveSrcMDAsCreationOption =
    4718          10 :                 CSLFetchNameValue(papszOptions, "FHDR") == nullptr;
    4719             :         }
    4720         738 :         if (bPreserveSrcMDAsCreationOption)
    4721             :         {
    4722          19 :             char *pszName = nullptr;
    4723          19 :             const char *pszValue = CPLParseNameValue(papszSrcMD[iMD], &pszName);
    4724          38 :             if (pszName != nullptr &&
    4725          19 :                 CSLFetchNameValue(papszFullOptions, pszName + 5) == nullptr)
    4726             :                 papszFullOptions =
    4727          19 :                     CSLSetNameValue(papszFullOptions, pszName + 5, pszValue);
    4728          19 :             CPLFree(pszName);
    4729             :         }
    4730             :     }
    4731             : 
    4732             :     /* -------------------------------------------------------------------- */
    4733             :     /*      Copy TRE definitions as creation options, unless they are       */
    4734             :     /*      already set as creation options.                                */
    4735             :     /* -------------------------------------------------------------------- */
    4736         120 :     papszSrcMD = poSrcDS->GetMetadata("TRE");
    4737             : 
    4738         125 :     for (int iMD = 0; bUseSrcNITFMetadata && papszSrcMD && papszSrcMD[iMD];
    4739             :          iMD++)
    4740             :     {
    4741           5 :         CPLString osTRE;
    4742             : 
    4743           5 :         if (STARTS_WITH_CI(papszSrcMD[iMD], "RPFHDR") ||
    4744           5 :             STARTS_WITH_CI(papszSrcMD[iMD], "RPFIMG") ||
    4745           5 :             STARTS_WITH_CI(papszSrcMD[iMD], "RPFDES"))
    4746             :         {
    4747             :             /* Do not copy RPF TRE. They contain absolute offsets */
    4748             :             /* No chance that they make sense in the new NITF file */
    4749           0 :             continue;
    4750             :         }
    4751           8 :         if (STARTS_WITH_CI(papszSrcMD[iMD], "BLOCKA") &&
    4752           3 :             CSLPartialFindString(papszOptions, "BLOCKA_") >= 0)
    4753             :         {
    4754             :             /* Do not copy BLOCKA TRE if there are BLOCKA_ creation options */
    4755           1 :             continue;
    4756             :         }
    4757             : 
    4758           4 :         osTRE = "TRE=";
    4759           4 :         osTRE += papszSrcMD[iMD];
    4760             : 
    4761           4 :         char *pszName = nullptr;
    4762           4 :         CPLParseNameValue(papszSrcMD[iMD], &pszName);
    4763           8 :         if (pszName != nullptr &&
    4764           4 :             CSLPartialFindString(papszOptions, CPLSPrintf("TRE=%s", pszName)) <
    4765             :                 0)
    4766             :         {
    4767           3 :             papszFullOptions = CSLAddString(papszFullOptions, osTRE);
    4768             :         }
    4769           4 :         CPLFree(pszName);
    4770             :     }
    4771             : 
    4772             :     /* -------------------------------------------------------------------- */
    4773             :     /*      Set if we can set IREP.                                         */
    4774             :     /* -------------------------------------------------------------------- */
    4775         120 :     if (CSLFetchNameValue(papszFullOptions, "IREP") == nullptr)
    4776             :     {
    4777         138 :         if (((poSrcDS->GetRasterCount() == 3 && bJPEG) ||
    4778         114 :              (poSrcDS->GetRasterCount() >= 3 && !bJPEG)) &&
    4779          22 :             poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
    4780          15 :                 GCI_RedBand &&
    4781          15 :             poSrcDS->GetRasterBand(2)->GetColorInterpretation() ==
    4782         240 :                 GCI_GreenBand &&
    4783          15 :             poSrcDS->GetRasterBand(3)->GetColorInterpretation() == GCI_BlueBand)
    4784             :         {
    4785          15 :             if (bJPEG)
    4786             :                 papszFullOptions =
    4787           5 :                     CSLSetNameValue(papszFullOptions, "IREP", "YCbCr601");
    4788             :             else
    4789             :                 papszFullOptions =
    4790          10 :                     CSLSetNameValue(papszFullOptions, "IREP", "RGB");
    4791             :         }
    4792         112 :         else if (poSrcDS->GetRasterCount() >= 3 && !bJPEG &&
    4793           6 :                  poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
    4794           2 :                      GCI_BlueBand &&
    4795           2 :                  poSrcDS->GetRasterBand(2)->GetColorInterpretation() ==
    4796           2 :                      GCI_GreenBand &&
    4797           2 :                  poSrcDS->GetRasterBand(3)->GetColorInterpretation() ==
    4798         112 :                      GCI_RedBand &&
    4799           2 :                  CSLFetchNameValue(papszFullOptions, "IREPBAND") == nullptr)
    4800             :         {
    4801             :             papszFullOptions =
    4802           2 :                 CSLSetNameValue(papszFullOptions, "IREP", "MULTI");
    4803           2 :             std::string osIREPBAND = "B,G,R";
    4804           3 :             for (int i = 4; i <= poSrcDS->GetRasterCount(); ++i)
    4805           1 :                 osIREPBAND += ",M";
    4806           2 :             papszFullOptions = CSLSetNameValue(papszFullOptions, "IREPBAND",
    4807             :                                                osIREPBAND.c_str());
    4808             :         }
    4809         178 :         else if (poSrcDS->GetRasterCount() == 1 && eType == GDT_Byte &&
    4810          75 :                  poBand1->GetColorTable() != nullptr)
    4811             :         {
    4812             :             papszFullOptions =
    4813           1 :                 CSLSetNameValue(papszFullOptions, "IREP", "RGB/LUT");
    4814           1 :             papszFullOptions = CSLSetNameValue(
    4815             :                 papszFullOptions, "LUT_SIZE",
    4816           2 :                 CPLString().Printf(
    4817           1 :                     "%d", poBand1->GetColorTable()->GetColorEntryCount()));
    4818             :         }
    4819         102 :         else if (GDALDataTypeIsComplex(eType))
    4820             :             papszFullOptions =
    4821           4 :                 CSLSetNameValue(papszFullOptions, "IREP", "NODISPLY");
    4822             : 
    4823             :         else
    4824             :             papszFullOptions =
    4825          98 :                 CSLSetNameValue(papszFullOptions, "IREP", "MONO");
    4826             :     }
    4827             : 
    4828             :     /* -------------------------------------------------------------------- */
    4829             :     /*      Do we have lat/long georeferencing information?                 */
    4830             :     /* -------------------------------------------------------------------- */
    4831         120 :     const char *pszWKT = poSrcDS->GetProjectionRef();
    4832         120 :     if (pszWKT == nullptr || pszWKT[0] == '\0')
    4833          49 :         pszWKT = poSrcDS->GetGCPProjection();
    4834             : 
    4835             :     double adfGeoTransform[6];
    4836         120 :     bool bWriteGeoTransform = false;
    4837         120 :     bool bWriteGCPs = false;
    4838         120 :     int nZone = 0;
    4839         240 :     OGRSpatialReference oSRS;
    4840         240 :     OGRSpatialReference oSRS_WGS84;
    4841         120 :     int nGCIFFlags = GCIF_PAM_DEFAULT;
    4842         120 :     double dfIGEOLOULX = 0;
    4843         120 :     double dfIGEOLOULY = 0;
    4844         120 :     double dfIGEOLOURX = 0;
    4845         120 :     double dfIGEOLOURY = 0;
    4846         120 :     double dfIGEOLOLRX = 0;
    4847         120 :     double dfIGEOLOLRY = 0;
    4848         120 :     double dfIGEOLOLLX = 0;
    4849         120 :     double dfIGEOLOLLY = 0;
    4850         120 :     bool bManualWriteOfIGEOLO = false;
    4851             : 
    4852         120 :     if (pszWKT != nullptr && pszWKT[0] != '\0')
    4853             :     {
    4854          72 :         oSRS.importFromWkt(pszWKT);
    4855             : 
    4856             :         /* NITF is only WGS84 */
    4857          72 :         oSRS_WGS84.SetWellKnownGeogCS("WGS84");
    4858          72 :         if (oSRS.IsSameGeogCS(&oSRS_WGS84) == FALSE)
    4859             :         {
    4860          16 :             CPLError(
    4861             :                 (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    4862             :                 "NITF only supports WGS84 geographic and UTM projections.\n");
    4863          16 :             if (bStrict)
    4864             :             {
    4865           0 :                 CSLDestroy(papszFullOptions);
    4866           0 :                 CSLDestroy(papszCgmMD);
    4867           0 :                 CSLDestroy(papszTextMD);
    4868           1 :                 return nullptr;
    4869             :             }
    4870             :         }
    4871             : 
    4872          72 :         const char *pszICORDS = CSLFetchNameValue(papszFullOptions, "ICORDS");
    4873             : 
    4874             :         /* --------------------------------------------------------------------
    4875             :          */
    4876             :         /*      Should we write DIGEST Spatial Data Extension TRE ? */
    4877             :         /* --------------------------------------------------------------------
    4878             :          */
    4879          72 :         const char *pszSDE_TRE = CSLFetchNameValue(papszFullOptions, "SDE_TRE");
    4880          72 :         const bool bSDE_TRE = pszSDE_TRE && CPLTestBool(pszSDE_TRE);
    4881          72 :         if (bSDE_TRE)
    4882             :         {
    4883           2 :             if (oSRS.IsGeographic() && oSRS.GetPrimeMeridian() == 0.0 &&
    4884           1 :                 poSrcDS->GetGeoTransform(adfGeoTransform) == CE_None &&
    4885           3 :                 adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 &&
    4886           1 :                 adfGeoTransform[5] < 0.0)
    4887             :             {
    4888             :                 /* Override ICORDS to G if necessary */
    4889           1 :                 if (pszICORDS != nullptr && EQUAL(pszICORDS, "D"))
    4890             :                 {
    4891             :                     papszFullOptions =
    4892           0 :                         CSLSetNameValue(papszFullOptions, "ICORDS", "G");
    4893           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    4894             :                              "Forcing ICORDS=G when writing GEOLOB");
    4895             :                 }
    4896             :                 else
    4897             :                 {
    4898             :                     /* Code a bit below will complain with other ICORDS value */
    4899             :                 }
    4900             : 
    4901           1 :                 if (CSLPartialFindString(papszFullOptions, "TRE=GEOLOB=") != -1)
    4902             :                 {
    4903           0 :                     CPLDebug("NITF", "GEOLOB TRE was explicitly defined "
    4904             :                                      "before.  Overriding it with current "
    4905             :                                      "georeferencing info.");
    4906             :                 }
    4907             : 
    4908             :                 /* Structure of SDE TRE documented here */
    4909             :                 // http://www.gwg.nga.mil/ntb/baseline/docs/digest/part2_annex_d.pdf
    4910             : 
    4911             :                 /* --------------------------------------------------------------------
    4912             :                  */
    4913             :                 /*      Write GEOLOB TRE */
    4914             :                 /* --------------------------------------------------------------------
    4915             :                  */
    4916             :                 // Extra (useless) bytes to avoid CLang 18 erroneous -Wformat-truncation
    4917           1 :                 constexpr int MARGIN_FOR_CLANG_18 = 2;
    4918             :                 char szGEOLOB[48 + 1 + MARGIN_FOR_CLANG_18];
    4919           1 :                 const double dfARV = 360.0 / adfGeoTransform[1];
    4920           1 :                 const double dfBRV = 360.0 / -adfGeoTransform[5];
    4921           1 :                 const double dfLSO = adfGeoTransform[0];
    4922           1 :                 const double dfPSO = adfGeoTransform[3];
    4923           1 :                 CPLsnprintf(szGEOLOB, sizeof(szGEOLOB),
    4924             :                             "%09d%09d%#+015.10f%#+015.10f",
    4925           1 :                             static_cast<int>(dfARV + 0.5),
    4926           1 :                             static_cast<int>(dfBRV + 0.5), dfLSO, dfPSO);
    4927             : 
    4928           2 :                 CPLString osGEOLOB("TRE=GEOLOB=");
    4929           1 :                 osGEOLOB += szGEOLOB;
    4930           1 :                 papszFullOptions = CSLAddString(papszFullOptions, osGEOLOB);
    4931             : 
    4932             :                 /* --------------------------------------------------------------------
    4933             :                  */
    4934             :                 /*      Write GEOPSB TRE if not already explicitly provided */
    4935             :                 /* --------------------------------------------------------------------
    4936             :                  */
    4937           1 :                 if (CSLPartialFindString(papszFullOptions,
    4938           2 :                                          "FILE_TRE=GEOPSB=") == -1 &&
    4939           1 :                     CSLPartialFindString(papszFullOptions, "TRE=GEOPSB=") == -1)
    4940             :                 {
    4941             :                     char szGEOPSB[443 + 1];
    4942           1 :                     memset(szGEOPSB, ' ', 443);
    4943           1 :                     szGEOPSB[443] = 0;
    4944             : #define WRITE_STR_NOSZ(dst, src) memcpy(dst, src, strlen(src))
    4945           1 :                     char *pszGEOPSB = szGEOPSB;
    4946           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "GEO");
    4947           1 :                     pszGEOPSB += 3;
    4948           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "DEG");
    4949           1 :                     pszGEOPSB += 3;
    4950           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "World Geodetic System 1984");
    4951           1 :                     pszGEOPSB += 80;
    4952           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "WGE");
    4953           1 :                     pszGEOPSB += 4;
    4954           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "World Geodetic System 1984");
    4955           1 :                     pszGEOPSB += 80;
    4956           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "WE");
    4957           1 :                     pszGEOPSB += 3;
    4958           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "Geodetic");
    4959           1 :                     pszGEOPSB += 80; /* DVR */
    4960           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "GEOD");
    4961           1 :                     pszGEOPSB += 4; /* VDCDVR */
    4962           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "Mean Sea");
    4963           1 :                     pszGEOPSB += 80; /* SDA */
    4964           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "MSL");
    4965           1 :                     pszGEOPSB += 4; /* VDCSDA */
    4966           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "000000000000000");
    4967           1 :                     pszGEOPSB += 15; /* ZOR */
    4968           1 :                     pszGEOPSB += 3;  /* GRD */
    4969           1 :                     pszGEOPSB += 80; /* GRN */
    4970           1 :                     WRITE_STR_NOSZ(pszGEOPSB, "0000");
    4971           1 :                     pszGEOPSB += 4; /* ZNA */
    4972           1 :                     CPL_IGNORE_RET_VAL(pszGEOPSB);
    4973           1 :                     CPLAssert(pszGEOPSB == szGEOPSB + 443);
    4974             : 
    4975           1 :                     CPLString osGEOPSB("FILE_TRE=GEOPSB=");
    4976           1 :                     osGEOPSB += szGEOPSB;
    4977           1 :                     papszFullOptions = CSLAddString(papszFullOptions, osGEOPSB);
    4978             :                 }
    4979             :                 else
    4980             :                 {
    4981           0 :                     CPLDebug("NITF", "GEOPSB TRE was explicitly defined "
    4982             :                                      "before. Keeping it.");
    4983             :                 }
    4984             :             }
    4985             :             else
    4986             :             {
    4987           0 :                 CPLError((bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    4988             :                          "Georeferencing info isn't compatible with writing a "
    4989             :                          "GEOLOB TRE (only geographic SRS handled for now)");
    4990           0 :                 if (bStrict)
    4991             :                 {
    4992           0 :                     CSLDestroy(papszFullOptions);
    4993           0 :                     CSLDestroy(papszCgmMD);
    4994           0 :                     CSLDestroy(papszTextMD);
    4995           0 :                     return nullptr;
    4996             :                 }
    4997             :             }
    4998             :         }
    4999             : 
    5000          72 :         bWriteGeoTransform =
    5001          72 :             (poSrcDS->GetGeoTransform(adfGeoTransform) == CE_None);
    5002          72 :         bWriteGCPs = (!bWriteGeoTransform && poSrcDS->GetGCPCount() == 4);
    5003             : 
    5004             :         int bNorth;
    5005             :         const bool bHasIGEOLO =
    5006          72 :             CSLFetchNameValue(papszFullOptions, "IGEOLO") != nullptr;
    5007          72 :         if (bHasIGEOLO && pszICORDS == nullptr)
    5008             :         {
    5009           1 :             CPLError((bStrict) ? CE_Failure : CE_Warning, CPLE_AppDefined,
    5010             :                      "IGEOLO specified, but ICORDS not.%s",
    5011             :                      bStrict ? "" : " Ignoring IGEOLO");
    5012           1 :             if (bStrict)
    5013             :             {
    5014           1 :                 CSLDestroy(papszFullOptions);
    5015           1 :                 CSLDestroy(papszCgmMD);
    5016           1 :                 CSLDestroy(papszTextMD);
    5017           1 :                 return nullptr;
    5018             :             }
    5019             :         }
    5020             : 
    5021          71 :         if (CSLFetchNameValue(papszFullOptions, "IGEOLO") != nullptr &&
    5022             :             pszICORDS != nullptr)
    5023             :         {
    5024             :             // if both IGEOLO and ICORDS are specified, do not try to write
    5025             :             // computed values
    5026             : 
    5027           1 :             bWriteGeoTransform = false;
    5028           1 :             bWriteGCPs = false;
    5029           1 :             nGCIFFlags &= ~GCIF_PROJECTION;
    5030           1 :             nGCIFFlags &= ~GCIF_GEOTRANSFORM;
    5031             :         }
    5032          70 :         else if (oSRS.IsGeographic() && oSRS.GetPrimeMeridian() == 0.0)
    5033             :         {
    5034          50 :             if (pszICORDS == nullptr)
    5035             :             {
    5036             :                 papszFullOptions =
    5037          48 :                     CSLSetNameValue(papszFullOptions, "ICORDS", "G");
    5038             :             }
    5039           2 :             else if (EQUAL(pszICORDS, "G") || EQUAL(pszICORDS, "D"))
    5040             :             {
    5041             :                 /* Do nothing */
    5042             :             }
    5043             :             else
    5044             :             {
    5045           0 :                 CPLError((bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    5046             :                          "Inconsistent ICORDS value with SRS : %s%s.\n",
    5047             :                          pszICORDS,
    5048             :                          (!bStrict) ? ". Setting it to G instead" : "");
    5049           0 :                 if (bStrict)
    5050             :                 {
    5051           0 :                     CSLDestroy(papszFullOptions);
    5052           0 :                     CSLDestroy(papszCgmMD);
    5053           0 :                     CSLDestroy(papszTextMD);
    5054           0 :                     return nullptr;
    5055             :                 }
    5056             :                 papszFullOptions =
    5057           0 :                     CSLSetNameValue(papszFullOptions, "ICORDS", "G");
    5058             :             }
    5059             :         }
    5060             : 
    5061          20 :         else if (oSRS.GetUTMZone(&bNorth) > 0)
    5062             :         {
    5063          20 :             const char *pszComputedICORDS = bNorth ? "N" : "S";
    5064          20 :             nZone = oSRS.GetUTMZone(nullptr);
    5065          20 :             if (pszICORDS == nullptr)
    5066             :             {
    5067          19 :                 papszFullOptions = CSLSetNameValue(papszFullOptions, "ICORDS",
    5068             :                                                    pszComputedICORDS);
    5069             :             }
    5070           1 :             else if (EQUAL(pszICORDS, pszComputedICORDS))
    5071             :             {
    5072             :                 // ok
    5073             :             }
    5074           1 :             else if ((EQUAL(pszICORDS, "G") || EQUAL(pszICORDS, "D")) &&
    5075             :                      bWriteGeoTransform)
    5076             :             {
    5077             :                 // Reproject UTM corner coordinates to geographic.
    5078             :                 // This can be used when there is no way to write an
    5079             :                 // equatorial image whose one of the northing value is below
    5080             :                 // -1e6
    5081             : 
    5082           1 :                 const int nXSize = poSrcDS->GetRasterXSize();
    5083           1 :                 const int nYSize = poSrcDS->GetRasterYSize();
    5084             : 
    5085           1 :                 dfIGEOLOULX = adfGeoTransform[0] + 0.5 * adfGeoTransform[1] +
    5086           1 :                               0.5 * adfGeoTransform[2];
    5087           1 :                 dfIGEOLOULY = adfGeoTransform[3] + 0.5 * adfGeoTransform[4] +
    5088           1 :                               0.5 * adfGeoTransform[5];
    5089           1 :                 dfIGEOLOURX = dfIGEOLOULX + adfGeoTransform[1] * (nXSize - 1);
    5090           1 :                 dfIGEOLOURY = dfIGEOLOULY + adfGeoTransform[4] * (nXSize - 1);
    5091           1 :                 dfIGEOLOLRX = dfIGEOLOULX + adfGeoTransform[1] * (nXSize - 1) +
    5092           1 :                               adfGeoTransform[2] * (nYSize - 1);
    5093           1 :                 dfIGEOLOLRY = dfIGEOLOULY + adfGeoTransform[4] * (nXSize - 1) +
    5094           1 :                               adfGeoTransform[5] * (nYSize - 1);
    5095           1 :                 dfIGEOLOLLX = dfIGEOLOULX + adfGeoTransform[2] * (nYSize - 1);
    5096           1 :                 dfIGEOLOLLY = dfIGEOLOULY + adfGeoTransform[5] * (nYSize - 1);
    5097             : 
    5098           1 :                 oSRS_WGS84.SetWellKnownGeogCS("WGS84");
    5099           1 :                 oSRS_WGS84.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    5100             : 
    5101             :                 auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
    5102           1 :                     OGRCreateCoordinateTransformation(&oSRS, &oSRS_WGS84));
    5103           2 :                 if (poCT && poCT->Transform(1, &dfIGEOLOULX, &dfIGEOLOULY) &&
    5104           1 :                     poCT->Transform(1, &dfIGEOLOURX, &dfIGEOLOURY) &&
    5105           3 :                     poCT->Transform(1, &dfIGEOLOLRX, &dfIGEOLOLRY) &&
    5106           1 :                     poCT->Transform(1, &dfIGEOLOLLX, &dfIGEOLOLLY))
    5107             :                 {
    5108           1 :                     nZone = 0;
    5109           1 :                     bWriteGeoTransform = false;
    5110           1 :                     bManualWriteOfIGEOLO = true;
    5111           1 :                     nGCIFFlags &= ~GCIF_PROJECTION;
    5112           1 :                     nGCIFFlags &= ~GCIF_GEOTRANSFORM;
    5113             :                 }
    5114             :                 else
    5115             :                 {
    5116           0 :                     CPLError(
    5117             :                         CE_Failure, CPLE_AppDefined,
    5118             :                         "Cannot reproject UTM coordinates to geographic ones");
    5119           0 :                     CSLDestroy(papszFullOptions);
    5120           0 :                     CSLDestroy(papszCgmMD);
    5121           0 :                     CSLDestroy(papszTextMD);
    5122           0 :                     return nullptr;
    5123           1 :                 }
    5124             :             }
    5125             :             else
    5126             :             {
    5127           0 :                 CPLError((bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    5128             :                          "Inconsistent ICORDS value with SRS : %s.", pszICORDS);
    5129           0 :                 if (bStrict)
    5130             :                 {
    5131           0 :                     CSLDestroy(papszFullOptions);
    5132           0 :                     CSLDestroy(papszCgmMD);
    5133           0 :                     CSLDestroy(papszTextMD);
    5134           0 :                     return nullptr;
    5135             :                 }
    5136             :             }
    5137             :         }
    5138             :         else
    5139             :         {
    5140           0 :             CPLError(
    5141             :                 (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    5142             :                 "NITF only supports WGS84 geographic and UTM projections.\n");
    5143           0 :             if (bStrict)
    5144             :             {
    5145           0 :                 CSLDestroy(papszFullOptions);
    5146           0 :                 CSLDestroy(papszCgmMD);
    5147           0 :                 CSLDestroy(papszTextMD);
    5148           0 :                 return nullptr;
    5149             :             }
    5150             :         }
    5151             :     }
    5152             : 
    5153             :     /* -------------------------------------------------------------------- */
    5154             :     /*      Do we have RPC information?                                     */
    5155             :     /* -------------------------------------------------------------------- */
    5156         119 :     if (!bUseSrcNITFMetadata)
    5157           1 :         nGCIFFlags &= ~GCIF_METADATA;
    5158             : 
    5159         119 :     char **papszRPC = poSrcDS->GetMetadata("RPC");
    5160         147 :     if (papszRPC != nullptr && bUseSrcNITFMetadata &&
    5161          28 :         CPLFetchBool(papszFullOptions, "RPC00B", true))
    5162             :     {
    5163          27 :         if (CSLPartialFindString(papszFullOptions, "TRE=RPC00B=") >= 0)
    5164             :         {
    5165           1 :             CPLDebug("NITF",
    5166             :                      "Both TRE=RPC00B and RPC metadata are available. "
    5167             :                      "Ignoring RPC metadata and re-using source TRE=RPC00B");
    5168             :         }
    5169             :         else
    5170             :         {
    5171          26 :             int bPrecisionLoss = FALSE;
    5172             :             char *pszRPC =
    5173          26 :                 NITFFormatRPC00BFromMetadata(papszRPC, &bPrecisionLoss);
    5174          26 :             if (pszRPC == nullptr)
    5175             :             {
    5176          11 :                 CPLError(
    5177             :                     (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
    5178             :                     "Cannot format a valid RPC00B TRE from the RPC metadata");
    5179          11 :                 if (bStrict)
    5180             :                 {
    5181          11 :                     CSLDestroy(papszFullOptions);
    5182          11 :                     CSLDestroy(papszCgmMD);
    5183          11 :                     CSLDestroy(papszTextMD);
    5184          11 :                     return nullptr;
    5185             :                 }
    5186             :             }
    5187             :             else
    5188             :             {
    5189          30 :                 CPLString osRPC00B("TRE=RPC00B=");
    5190          15 :                 osRPC00B += pszRPC;
    5191          15 :                 papszFullOptions = CSLAddString(papszFullOptions, osRPC00B);
    5192             : 
    5193             :                 // If no precision loss occurred during RPC conversion, then
    5194             :                 // we can suppress it from PAM
    5195          15 :                 if (!bPrecisionLoss)
    5196           3 :                     nGCIFFlags &= ~GCIF_METADATA;
    5197             :             }
    5198          15 :             CPLFree(pszRPC);
    5199             :         }
    5200             :     }
    5201          92 :     else if (!CPLFetchBool(papszFullOptions, "RPC00B", true))
    5202             :     {
    5203           1 :         int nIdx = CSLPartialFindString(papszFullOptions, "TRE=RPC00B=");
    5204           1 :         if (nIdx >= 0)
    5205             :         {
    5206             :             papszFullOptions =
    5207           0 :                 CSLRemoveStrings(papszFullOptions, nIdx, 1, nullptr);
    5208             :         }
    5209             :     }
    5210             : 
    5211         108 :     if (papszRPC != nullptr && CPLFetchBool(papszFullOptions, "RPCTXT", false))
    5212             :     {
    5213           1 :         GDALWriteRPCTXTFile(pszFilename, papszRPC);
    5214             :     }
    5215             : 
    5216             :     /* -------------------------------------------------------------------- */
    5217             :     /*      Create the output file.                                         */
    5218             :     /* -------------------------------------------------------------------- */
    5219         108 :     const int nXSize = poSrcDS->GetRasterXSize();
    5220         108 :     const int nYSize = poSrcDS->GetRasterYSize();
    5221         108 :     const char *pszPVType = GDALToNITFDataType(eType);
    5222             : 
    5223         108 :     if (pszPVType == nullptr)
    5224             :     {
    5225           3 :         CSLDestroy(papszFullOptions);
    5226           3 :         CSLDestroy(papszCgmMD);
    5227           3 :         CSLDestroy(papszTextMD);
    5228           3 :         return nullptr;
    5229             :     }
    5230             : 
    5231         105 :     int nABPP = GDALGetDataTypeSize(eType);
    5232         105 :     if (const char *pszABPP = CSLFetchNameValue(papszFullOptions, "ABPP"))
    5233             :     {
    5234           1 :         nABPP = atoi(pszABPP);
    5235             :     }
    5236         104 :     else if (const char *pszNBITS = CSLFetchNameValueDef(
    5237             :                  papszFullOptions, "NBITS",
    5238         104 :                  poBand1->GetMetadataItem("NBITS", "IMAGE_STRUCTURE")))
    5239             :     {
    5240           2 :         papszFullOptions = CSLSetNameValue(papszFullOptions, "ABPP", pszNBITS);
    5241           2 :         nABPP = atoi(pszNBITS);
    5242             :     }
    5243             : 
    5244         116 :     if (poJ2KDriver != nullptr &&
    5245          11 :         EQUAL(poJ2KDriver->GetDescription(), "JP2ECW"))
    5246             :     {
    5247           3 :         if (STARTS_WITH_CI(
    5248             :                 CSLFetchNameValueDef(papszFullOptions, "PROFILE", "NPJE"),
    5249           5 :                 "NPJE") &&
    5250           2 :             (nXSize >= 1024 || nYSize >= 1024))
    5251             :         {
    5252             :             int nBlockXSize =
    5253           1 :                 atoi(CSLFetchNameValueDef(papszFullOptions, "BLOCKXSIZE", "0"));
    5254             :             int nBlockYSize =
    5255           1 :                 atoi(CSLFetchNameValueDef(papszFullOptions, "BLOCKYSIZE", "0"));
    5256           1 :             if (nBlockXSize > 0 && nBlockXSize != 1024)
    5257             :             {
    5258           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    5259             :                          "BLOCKXSIZE != 1024 inconsistent with PROFILE=NPJE");
    5260             :             }
    5261           1 :             if (nBlockYSize > 0 && nBlockYSize != 1024)
    5262             :             {
    5263           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    5264             :                          "BLOCKYSIZE != 1024 inconsistent with PROFILE=NPJE");
    5265             :             }
    5266           1 :             if (nBlockXSize == 0)
    5267             :             {
    5268             :                 papszFullOptions =
    5269           1 :                     CSLSetNameValue(papszFullOptions, "BLOCKXSIZE", "1024");
    5270             :             }
    5271           1 :             if (nBlockYSize == 0)
    5272             :             {
    5273             :                 papszFullOptions =
    5274           1 :                     CSLSetNameValue(papszFullOptions, "BLOCKYSIZE", "1024");
    5275             :             }
    5276             :         }
    5277             :     }
    5278         110 :     else if (poJ2KDriver != nullptr &&
    5279           8 :              EQUAL(poJ2KDriver->GetDescription(), "JP2OPENJPEG"))
    5280             :     {
    5281           8 :         const char *pszProfile = CSLFetchNameValue(papszFullOptions, "PROFILE");
    5282           8 :         if (pszProfile && EQUAL(pszProfile, "EPJE"))
    5283             :         {
    5284           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    5285             :                      "PROFILE=EPJE not handled by JP2OPENJPEG driver");
    5286             :         }
    5287             : 
    5288             :         int nBlockXSize =
    5289           8 :             atoi(CSLFetchNameValueDef(papszFullOptions, "BLOCKXSIZE", "0"));
    5290             :         int nBlockYSize =
    5291           8 :             atoi(CSLFetchNameValueDef(papszFullOptions, "BLOCKYSIZE", "0"));
    5292           8 :         if (pszProfile && STARTS_WITH_CI(pszProfile, "NPJE") &&
    5293           4 :             ((nBlockXSize != 0 && nBlockXSize != 1024) ||
    5294           0 :              (nBlockYSize != 0 && nBlockYSize != 1024)))
    5295             :         {
    5296           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    5297             :                      "PROFILE=NPJE implies 1024x1024 tiles");
    5298             :         }
    5299             : 
    5300           8 :         if (nXSize >= 1024 || nYSize >= 1024 ||
    5301           4 :             (pszProfile && STARTS_WITH_CI(pszProfile, "NPJE")))
    5302             :         {
    5303             :             // The JP2OPENJPEG driver uses 1024 block size by default. Set it
    5304             :             // explicitly for NITFCreate() purposes.
    5305           5 :             if (nBlockXSize == 0)
    5306             :             {
    5307             :                 papszFullOptions =
    5308           5 :                     CSLSetNameValue(papszFullOptions, "BLOCKXSIZE", "1024");
    5309             :             }
    5310           5 :             if (nBlockYSize == 0)
    5311             :             {
    5312             :                 papszFullOptions =
    5313           5 :                     CSLSetNameValue(papszFullOptions, "BLOCKYSIZE", "1024");
    5314             :             }
    5315             :         }
    5316             : 
    5317             :         // Compose J2KLRA TRE for NPJE profiles
    5318          12 :         if (pszProfile && STARTS_WITH_CI(pszProfile, "NPJE") &&
    5319           4 :             CPLTestBool(
    5320             :                 CSLFetchNameValueDef(papszFullOptions, "J2KLRA", "YES")))
    5321             :         {
    5322             :             // See Table 2.3-3 - Target Bit Rates for Each Tile in Panchromatic
    5323             :             // Image Segments of STDI-0006
    5324             :             std::vector<double> adfBPP = {
    5325             :                 0.03125, 0.0625, 0.125, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
    5326           8 :                 1.1,     1.2,    1.3,   1.5,  1.7, 2.0, 2.3, 3.5, 3.9};
    5327             : 
    5328           4 :             if (EQUAL(pszProfile, "NPJE") ||
    5329           4 :                 EQUAL(pszProfile, "NPJE_NUMERICALLY_LOSSLESS"))
    5330             :             {
    5331           2 :                 adfBPP.push_back(nABPP);
    5332             :             }
    5333             : 
    5334             :             double dfQuality =
    5335           4 :                 CPLAtof(CSLFetchNameValueDef(papszFullOptions, "QUALITY", "0"));
    5336             :             double dfTarget =
    5337           4 :                 CPLAtof(CSLFetchNameValueDef(papszFullOptions, "TARGET", "0"));
    5338           4 :             if (dfTarget > 0 && dfTarget < 100)
    5339           0 :                 dfQuality = 100. - dfTarget;
    5340             : 
    5341           4 :             if (dfQuality != 0.0)
    5342             :             {
    5343          27 :                 for (size_t i = 0; i < adfBPP.size(); ++i)
    5344             :                 {
    5345             :                     // the JP2OPENJPEG QUALITY setting is 100. /
    5346             :                     // compression_ratio and compression_ratio = 8 / bpp
    5347          27 :                     double dfLayerQuality = 100.0 / (8.0 / adfBPP[i]);
    5348          27 :                     if (dfLayerQuality > dfQuality)
    5349             :                     {
    5350           2 :                         adfBPP[i] = dfQuality / 100.0 * nABPP;
    5351           2 :                         adfBPP.resize(i + 1);
    5352           2 :                         break;
    5353             :                     }
    5354             :                 }
    5355             :             }
    5356             : 
    5357           4 :             CPLString osJ2KLRA("TRE=J2KLRA=");
    5358           4 :             osJ2KLRA += '0';   // ORIG: 0=Original NPJE
    5359           4 :             osJ2KLRA += "05";  // Number of wavelets decompositions.
    5360             :                                // This corresponds to the value of the
    5361             :                                // RESOLUTIONS JP2OPENJPEG creation option - 1
    5362           4 :             osJ2KLRA += CPLSPrintf("%05d", poSrcDS->GetRasterCount());
    5363           4 :             osJ2KLRA += CPLSPrintf("%03d", static_cast<int>(adfBPP.size()));
    5364          70 :             for (size_t i = 0; i < adfBPP.size(); ++i)
    5365             :             {
    5366          66 :                 osJ2KLRA += CPLSPrintf("%03d", static_cast<int>(i));
    5367          66 :                 osJ2KLRA += CPLSPrintf("%09.6f", adfBPP[i]);
    5368             :             }
    5369           4 :             papszFullOptions = CSLAddString(papszFullOptions, osJ2KLRA);
    5370             :         }
    5371             :     }
    5372             : 
    5373         105 :     int nIMIndex = 0;
    5374         105 :     int nImageCount = 0;
    5375         105 :     vsi_l_offset nImageOffset = 0;
    5376         105 :     vsi_l_offset nICOffset = 0;
    5377         105 :     if (!NITFCreateEx(pszFilename, nXSize, nYSize, poSrcDS->GetRasterCount(),
    5378             :                       GDALGetDataTypeSize(eType), pszPVType, papszFullOptions,
    5379             :                       &nIMIndex, &nImageCount, &nImageOffset, &nICOffset))
    5380             :     {
    5381          13 :         CSLDestroy(papszFullOptions);
    5382          13 :         CSLDestroy(papszCgmMD);
    5383          13 :         CSLDestroy(papszTextMD);
    5384          13 :         return nullptr;
    5385             :     }
    5386             : 
    5387             :     /* ==================================================================== */
    5388             :     /*      JPEG2000 case.  We need to write the data through a J2K         */
    5389             :     /*      driver in pixel interleaved form.                               */
    5390             :     /* ==================================================================== */
    5391          92 :     NITFDataset *poDstDS = nullptr;
    5392             : 
    5393          92 :     if (bJPEG2000)
    5394             :     {
    5395          11 :         CPLString osDSName;
    5396             :         osDSName.Printf("/vsisubfile/" CPL_FRMT_GUIB "_%d,%s",
    5397          11 :                         static_cast<GUIntBig>(nImageOffset), -1, pszFilename);
    5398             : 
    5399          11 :         GDALDataset *poJ2KDataset = nullptr;
    5400          11 :         if (EQUAL(poJ2KDriver->GetDescription(), "JP2ECW"))
    5401             :         {
    5402           3 :             char **papszJP2Options = NITFJP2ECWOptions(papszFullOptions);
    5403           3 :             poJ2KDataset = poJ2KDriver->CreateCopy(osDSName, poSrcDS, FALSE,
    5404             :                                                    papszJP2Options, pfnProgress,
    5405             :                                                    pProgressData);
    5406           3 :             CSLDestroy(papszJP2Options);
    5407             :         }
    5408           8 :         else if (EQUAL(poJ2KDriver->GetDescription(), "JP2KAK"))
    5409             :         {
    5410           0 :             char **papszJP2Options = NITFJP2KAKOptions(papszFullOptions, nABPP);
    5411           0 :             poJ2KDataset = poJ2KDriver->CreateCopy(osDSName, poSrcDS, FALSE,
    5412             :                                                    papszJP2Options, pfnProgress,
    5413             :                                                    pProgressData);
    5414           0 :             CSLDestroy(papszJP2Options);
    5415             :         }
    5416           8 :         else if (EQUAL(poJ2KDriver->GetDescription(), "JP2OPENJPEG"))
    5417             :         {
    5418             :             char **papszJP2Options =
    5419           8 :                 NITFJP2OPENJPEGOptions(poJ2KDriver, papszFullOptions, nABPP);
    5420           8 :             poJ2KDataset = poJ2KDriver->CreateCopy(osDSName, poSrcDS, FALSE,
    5421             :                                                    papszJP2Options, pfnProgress,
    5422             :                                                    pProgressData);
    5423           8 :             CSLDestroy(papszJP2Options);
    5424             :         }
    5425             :         else
    5426             :         {
    5427             :             /* Jasper case */
    5428           0 :             const char *apszOptions[] = {"FORMAT=JPC", nullptr};
    5429           0 :             poJ2KDataset = poJ2KDriver->CreateCopy(
    5430             :                 osDSName, poSrcDS, FALSE, const_cast<char **>(apszOptions),
    5431             :                 pfnProgress, pProgressData);
    5432             :         }
    5433          11 :         if (poJ2KDataset == nullptr)
    5434             :         {
    5435           0 :             CSLDestroy(papszCgmMD);
    5436           0 :             CSLDestroy(papszTextMD);
    5437           0 :             CSLDestroy(papszFullOptions);
    5438           0 :             return nullptr;
    5439             :         }
    5440             : 
    5441          11 :         delete poJ2KDataset;
    5442             : 
    5443             :         // Now we need to figure out the actual length of the file
    5444             :         // and correct the image segment size information.
    5445             :         GIntBig nPixelCount =
    5446          11 :             nXSize * ((GIntBig)nYSize) * poSrcDS->GetRasterCount();
    5447             : 
    5448          11 :         bool bOK = NITFPatchImageLength(pszFilename, nIMIndex, nImageOffset,
    5449             :                                         nPixelCount, "C8", nICOffset,
    5450             :                                         papszFullOptions);
    5451          11 :         if (nIMIndex + 1 == nImageCount)
    5452             :         {
    5453          11 :             bOK &= NITFWriteExtraSegments(pszFilename, papszCgmMD, papszTextMD,
    5454          11 :                                           papszFullOptions);
    5455             :         }
    5456          11 :         if (!bOK)
    5457             :         {
    5458           0 :             CSLDestroy(papszCgmMD);
    5459           0 :             CSLDestroy(papszTextMD);
    5460           0 :             CSLDestroy(papszFullOptions);
    5461           0 :             return nullptr;
    5462             :         }
    5463             : 
    5464          11 :         GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
    5465          11 :         poDstDS = OpenInternal(&oOpenInfo, nullptr, true,
    5466          11 :                                nImageCount == 1 ? -1 : nIMIndex);
    5467             : 
    5468          11 :         if (poDstDS == nullptr)
    5469             :         {
    5470           0 :             CSLDestroy(papszCgmMD);
    5471           0 :             CSLDestroy(papszTextMD);
    5472           0 :             CSLDestroy(papszFullOptions);
    5473           0 :             return nullptr;
    5474             :         }
    5475             :     }
    5476             : 
    5477             :     /* ==================================================================== */
    5478             :     /*      Loop copying bands to an uncompressed file.                     */
    5479             :     /* ==================================================================== */
    5480          81 :     else if (bJPEG)
    5481             :     {
    5482             : #ifdef JPEG_SUPPORTED
    5483          10 :         NITFFile *psFile = NITFOpen(pszFilename, TRUE);
    5484          10 :         if (psFile == nullptr)
    5485             :         {
    5486           0 :             CSLDestroy(papszCgmMD);
    5487           0 :             CSLDestroy(papszTextMD);
    5488           0 :             CSLDestroy(papszFullOptions);
    5489           0 :             return nullptr;
    5490             :         }
    5491             : 
    5492             :         const bool bSuccess =
    5493          10 :             NITFWriteJPEGImage(poSrcDS, psFile->fp, nImageOffset,
    5494             :                                papszFullOptions, pfnProgress, pProgressData);
    5495             : 
    5496          10 :         if (!bSuccess)
    5497             :         {
    5498           0 :             NITFClose(psFile);
    5499           0 :             CSLDestroy(papszCgmMD);
    5500           0 :             CSLDestroy(papszTextMD);
    5501           0 :             CSLDestroy(papszFullOptions);
    5502           0 :             return nullptr;
    5503             :         }
    5504             : 
    5505             :         // Now we need to figure out the actual length of the file
    5506             :         // and correct the image segment size information.
    5507             :         GIntBig nPixelCount =
    5508          10 :             nXSize * ((GIntBig)nYSize) * poSrcDS->GetRasterCount();
    5509             : 
    5510          10 :         NITFClose(psFile);
    5511             : 
    5512          10 :         bool bOK = NITFPatchImageLength(pszFilename, nIMIndex, nImageOffset,
    5513             :                                         nPixelCount, pszIC, nICOffset,
    5514             :                                         papszFullOptions);
    5515          10 :         if (nIMIndex + 1 == nImageCount)
    5516             :         {
    5517           8 :             bOK &= NITFWriteExtraSegments(pszFilename, papszCgmMD, papszTextMD,
    5518           8 :                                           papszFullOptions);
    5519             :         }
    5520          10 :         if (!bOK)
    5521             :         {
    5522           0 :             CSLDestroy(papszCgmMD);
    5523           0 :             CSLDestroy(papszTextMD);
    5524           0 :             CSLDestroy(papszFullOptions);
    5525           0 :             return nullptr;
    5526             :         }
    5527             : 
    5528          10 :         GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
    5529          10 :         poDstDS = OpenInternal(&oOpenInfo, nullptr, true,
    5530          10 :                                nImageCount == 1 ? -1 : nIMIndex);
    5531             : 
    5532          10 :         if (poDstDS == nullptr)
    5533             :         {
    5534           0 :             CSLDestroy(papszCgmMD);
    5535           0 :             CSLDestroy(papszTextMD);
    5536           0 :             CSLDestroy(papszFullOptions);
    5537           0 :             return nullptr;
    5538             :         }
    5539             : #endif /* def JPEG_SUPPORTED */
    5540             :     }
    5541             : 
    5542             :     /* ==================================================================== */
    5543             :     /*      Loop copying bands to an uncompressed file.                     */
    5544             :     /* ==================================================================== */
    5545             :     else
    5546             :     {
    5547          71 :         if (nIMIndex + 1 == nImageCount)
    5548             :         {
    5549          68 :             bool bOK = NITFWriteExtraSegments(pszFilename, papszCgmMD,
    5550             :                                               papszTextMD, papszFullOptions);
    5551          68 :             if (!bOK)
    5552             :             {
    5553           0 :                 CSLDestroy(papszCgmMD);
    5554           0 :                 CSLDestroy(papszTextMD);
    5555           0 :                 CSLDestroy(papszFullOptions);
    5556           0 :                 return nullptr;
    5557             :             }
    5558             :         }
    5559             : 
    5560             :         // Save error state to restore it afterwards since some operations
    5561             :         // in Open() might reset it.
    5562          71 :         CPLErr eLastErr = CPLGetLastErrorType();
    5563          71 :         int nLastErrNo = CPLGetLastErrorNo();
    5564          71 :         CPLString osLastErrorMsg = CPLGetLastErrorMsg();
    5565             : 
    5566          71 :         GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
    5567          71 :         poDstDS = OpenInternal(&oOpenInfo, nullptr, true,
    5568          71 :                                nImageCount == 1 ? -1 : nIMIndex);
    5569             : 
    5570          71 :         if (CPLGetLastErrorType() == CE_None && eLastErr != CE_None)
    5571           0 :             CPLErrorSetState(eLastErr, nLastErrNo, osLastErrorMsg.c_str());
    5572             : 
    5573          71 :         if (poDstDS == nullptr)
    5574             :         {
    5575           0 :             CSLDestroy(papszCgmMD);
    5576           0 :             CSLDestroy(papszTextMD);
    5577           0 :             CSLDestroy(papszFullOptions);
    5578           0 :             return nullptr;
    5579             :         }
    5580             : 
    5581          71 :         void *pData = VSIMalloc2(nXSize, GDALGetDataTypeSizeBytes(eType));
    5582          71 :         if (pData == nullptr)
    5583             :         {
    5584           0 :             delete poDstDS;
    5585           0 :             CSLDestroy(papszCgmMD);
    5586           0 :             CSLDestroy(papszTextMD);
    5587           0 :             CSLDestroy(papszFullOptions);
    5588           0 :             return nullptr;
    5589             :         }
    5590             : 
    5591          71 :         CPLErr eErr = CE_None;
    5592             : 
    5593         347 :         for (int iBand = 0; nIMIndex >= 0 && eErr == CE_None &&
    5594         173 :                             iBand < poSrcDS->GetRasterCount();
    5595             :              iBand++)
    5596             :         {
    5597         103 :             GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
    5598         103 :             GDALRasterBand *poDstBand = poDstDS->GetRasterBand(iBand + 1);
    5599             : 
    5600             :             /* --------------------------------------------------------------------
    5601             :              */
    5602             :             /*      Do we need to copy a colortable or other metadata? */
    5603             :             /* --------------------------------------------------------------------
    5604             :              */
    5605         103 :             GDALColorTable *poCT = poSrcBand->GetColorTable();
    5606         103 :             if (poCT != nullptr)
    5607           1 :                 poDstBand->SetColorTable(poCT);
    5608             : 
    5609             :             /* --------------------------------------------------------------------
    5610             :              */
    5611             :             /*      Copy image data. */
    5612             :             /* --------------------------------------------------------------------
    5613             :              */
    5614        4063 :             for (int iLine = 0; iLine < nYSize; iLine++)
    5615             :             {
    5616        3960 :                 eErr = poSrcBand->RasterIO(GF_Read, 0, iLine, nXSize, 1, pData,
    5617             :                                            nXSize, 1, eType, 0, 0, nullptr);
    5618        3960 :                 if (eErr != CE_None)
    5619           0 :                     break;
    5620             : 
    5621        3960 :                 eErr = poDstBand->RasterIO(GF_Write, 0, iLine, nXSize, 1, pData,
    5622             :                                            nXSize, 1, eType, 0, 0, nullptr);
    5623             : 
    5624        3960 :                 if (eErr != CE_None)
    5625           0 :                     break;
    5626             : 
    5627        3960 :                 if (!pfnProgress(
    5628        3960 :                         (iBand + (iLine + 1) / static_cast<double>(nYSize)) /
    5629        3960 :                             static_cast<double>(poSrcDS->GetRasterCount()),
    5630             :                         nullptr, pProgressData))
    5631             :                 {
    5632           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    5633           0 :                     eErr = CE_Failure;
    5634           0 :                     break;
    5635             :                 }
    5636             :             }
    5637             :         }
    5638             : 
    5639          71 :         CPLFree(pData);
    5640             : 
    5641          71 :         if (eErr != CE_None)
    5642             :         {
    5643           0 :             delete poDstDS;
    5644           0 :             CSLDestroy(papszCgmMD);
    5645           0 :             CSLDestroy(papszTextMD);
    5646           0 :             CSLDestroy(papszFullOptions);
    5647           0 :             return nullptr;
    5648             :         }
    5649             :     }
    5650             : 
    5651             :     /* -------------------------------------------------------------------- */
    5652             :     /*      Set the georeferencing.                                         */
    5653             :     /* -------------------------------------------------------------------- */
    5654          92 :     if (poDstDS->psImage == nullptr)
    5655             :     {
    5656             :         // do nothing
    5657             :     }
    5658          91 :     else if (bManualWriteOfIGEOLO)
    5659             :     {
    5660           1 :         if (!NITFWriteIGEOLO(poDstDS->psImage, poDstDS->psImage->chICORDS,
    5661           1 :                              poDstDS->psImage->nZone, dfIGEOLOULX, dfIGEOLOULY,
    5662             :                              dfIGEOLOURX, dfIGEOLOURY, dfIGEOLOLRX, dfIGEOLOLRY,
    5663             :                              dfIGEOLOLLX, dfIGEOLOLLY))
    5664             :         {
    5665           0 :             delete poDstDS;
    5666           0 :             CSLDestroy(papszCgmMD);
    5667           0 :             CSLDestroy(papszTextMD);
    5668           0 :             CSLDestroy(papszFullOptions);
    5669           0 :             return nullptr;
    5670             :         }
    5671             :     }
    5672          90 :     else if (bWriteGeoTransform)
    5673             :     {
    5674          51 :         poDstDS->psImage->nZone = nZone;
    5675          51 :         poDstDS->SetGeoTransform(adfGeoTransform);
    5676             :     }
    5677          39 :     else if (bWriteGCPs)
    5678             :     {
    5679           1 :         poDstDS->psImage->nZone = nZone;
    5680           1 :         poDstDS->SetGCPs(poSrcDS->GetGCPCount(), poSrcDS->GetGCPs(),
    5681           1 :                          poSrcDS->GetGCPSpatialRef());
    5682             :     }
    5683             : 
    5684          92 :     poDstDS->CloneInfo(poSrcDS, nGCIFFlags);
    5685             : 
    5686          92 :     if ((nGCIFFlags & GCIF_METADATA) == 0)
    5687             :     {
    5688           4 :         const int nSavedMOFlags = poDstDS->GetMOFlags();
    5689           4 :         papszSrcMD = poSrcDS->GetMetadata();
    5690           4 :         if (papszSrcMD != nullptr)
    5691             :         {
    5692           1 :             if (!bUseSrcNITFMetadata)
    5693             :             {
    5694           1 :                 char **papszNewMD = CSLDuplicate(poDstDS->GetMetadata());
    5695           1 :                 bool bAdded = false;
    5696          76 :                 for (char **papszIter = papszSrcMD; *papszIter; ++papszIter)
    5697             :                 {
    5698          75 :                     if (!STARTS_WITH(*papszIter, "NITF_"))
    5699             :                     {
    5700           0 :                         bAdded = true;
    5701           0 :                         papszNewMD = CSLAddString(papszNewMD, *papszIter);
    5702             :                     }
    5703             :                 }
    5704           1 :                 if (bAdded)
    5705             :                 {
    5706           0 :                     poDstDS->SetMetadata(papszNewMD);
    5707             :                 }
    5708           1 :                 CSLDestroy(papszNewMD);
    5709             :             }
    5710           0 :             else if (CSLCount(poDstDS->GetMetadata()) != CSLCount(papszSrcMD))
    5711             :             {
    5712           0 :                 poDstDS->SetMetadata(papszSrcMD);
    5713             :             }
    5714             :         }
    5715           4 :         poDstDS->SetMOFlags(nSavedMOFlags);
    5716             :     }
    5717             : 
    5718          92 :     CSLDestroy(papszCgmMD);
    5719          92 :     CSLDestroy(papszTextMD);
    5720          92 :     CSLDestroy(papszFullOptions);
    5721             : 
    5722          92 :     return poDstDS;
    5723             : }
    5724             : 
    5725             : /************************************************************************/
    5726             : /*                        NITFPatchImageLength()                        */
    5727             : /*                                                                      */
    5728             : /*      Fixup various stuff we don't know till we have written the      */
    5729             : /*      imagery.  In particular the file length, image data length      */
    5730             : /*      and the compression ratio achieved.                             */
    5731             : /************************************************************************/
    5732             : 
    5733          22 : static bool NITFPatchImageLength(const char *pszFilename, int nIMIndex,
    5734             :                                  GUIntBig nImageOffset, GIntBig nPixelCount,
    5735             :                                  const char *pszIC, vsi_l_offset nICOffset,
    5736             :                                  CSLConstList papszCreationOptions)
    5737             : 
    5738             : {
    5739          22 :     VSILFILE *fpVSIL = VSIFOpenL(pszFilename, "r+b");
    5740          22 :     if (fpVSIL == nullptr)
    5741           0 :         return false;
    5742             : 
    5743          22 :     CPL_IGNORE_RET_VAL(VSIFSeekL(fpVSIL, 0, SEEK_END));
    5744          22 :     GUIntBig nFileLen = VSIFTellL(fpVSIL);
    5745             : 
    5746             :     /* -------------------------------------------------------------------- */
    5747             :     /*      Update total file length.                                       */
    5748             :     /* -------------------------------------------------------------------- */
    5749          22 :     if (nFileLen >= NITF_MAX_FILE_SIZE)
    5750             :     {
    5751           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5752             :                  "Too big file : " CPL_FRMT_GUIB
    5753             :                  ". Truncating to " CPL_FRMT_GUIB,
    5754             :                  nFileLen, NITF_MAX_FILE_SIZE - 1);
    5755           0 :         nFileLen = NITF_MAX_FILE_SIZE - 1;
    5756             :     }
    5757             :     CPLString osLen =
    5758          44 :         CPLString().Printf("%012" CPL_FRMT_GB_WITHOUT_PREFIX "u", nFileLen);
    5759          44 :     if (VSIFSeekL(fpVSIL, 342, SEEK_SET) != 0 ||
    5760          22 :         VSIFWriteL(reinterpret_cast<const void *>(osLen.c_str()), 12, 1,
    5761             :                    fpVSIL) != 1)
    5762             :     {
    5763           0 :         CPLError(CE_Failure, CPLE_FileIO, "Write error");
    5764           0 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpVSIL));
    5765           0 :         return false;
    5766             :     }
    5767             : 
    5768             :     /* -------------------------------------------------------------------- */
    5769             :     /*      Update the image data length.                                   */
    5770             :     /* -------------------------------------------------------------------- */
    5771          22 :     GUIntBig nImageSize = nFileLen - nImageOffset;
    5772          22 :     if (nImageSize >= 9999999999ULL)
    5773             :     {
    5774           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5775             :                  "Too big image size : " CPL_FRMT_GUIB
    5776             :                  ". Truncating to 9999999998",
    5777             :                  nImageSize);
    5778           0 :         nImageSize = 9999999998ULL;
    5779             :     }
    5780             :     osLen =
    5781          22 :         CPLString().Printf("%010" CPL_FRMT_GB_WITHOUT_PREFIX "u", nImageSize);
    5782          44 :     if (VSIFSeekL(fpVSIL, 369 + 16 * nIMIndex, SEEK_SET) != 0 ||
    5783          22 :         VSIFWriteL(reinterpret_cast<const void *>(osLen.c_str()), 10, 1,
    5784             :                    fpVSIL) != 1)
    5785             :     {
    5786           0 :         CPLError(CE_Failure, CPLE_FileIO, "Write error");
    5787           0 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpVSIL));
    5788           0 :         return false;
    5789             :     }
    5790             : 
    5791             :     /* -------------------------------------------------------------------- */
    5792             :     /*      Update COMRAT, the compression rate variable, and CLEVEL        */
    5793             :     /* -------------------------------------------------------------------- */
    5794             : 
    5795             :     /* Set to IC position */
    5796          22 :     bool bOK = VSIFSeekL(fpVSIL, nICOffset, SEEK_SET) == 0;
    5797             : 
    5798             :     /* Read IC */
    5799             :     char szICBuf[2];
    5800          22 :     bOK &= VSIFReadL(szICBuf, 2, 1, fpVSIL) == 1;
    5801             : 
    5802             :     /* The following line works around a "feature" of *BSD libc (at least
    5803             :      * PC-BSD 7.1) */
    5804             :     /* that makes the position of the file offset unreliable when executing a */
    5805             :     /* "seek, read and write" sequence. After the read(), the file offset seen
    5806             :      * by */
    5807             :     /* the write() is approximately the size of a block further... */
    5808          22 :     bOK &= VSIFSeekL(fpVSIL, VSIFTellL(fpVSIL), SEEK_SET) == 0;
    5809             : 
    5810          22 :     if (!EQUALN(szICBuf, pszIC, 2))
    5811             :     {
    5812           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    5813             :                  "Unable to locate COMRAT to update in NITF header.");
    5814             :     }
    5815             :     else
    5816             :     {
    5817             :         char szCOMRAT[5];
    5818             : 
    5819          22 :         if (EQUAL(pszIC, "C8")) /* jpeg2000 */
    5820             :         {
    5821          12 :             double dfRate = static_cast<GIntBig>(nFileLen - nImageOffset) * 8 /
    5822          12 :                             static_cast<double>(nPixelCount);
    5823             : 
    5824             :             const char *pszProfile =
    5825          12 :                 CSLFetchNameValueDef(papszCreationOptions, "PROFILE", "");
    5826          12 :             if (STARTS_WITH_CI(pszProfile, "NPJE"))
    5827             :             {
    5828           4 :                 dfRate = std::max(0.1, std::min(99.9, dfRate));
    5829             : 
    5830             :                 // We emit in Vxyz or Nxyz format with an implicit decimal place
    5831             :                 // between yz and z as per spec.
    5832           4 :                 snprintf(szCOMRAT, sizeof(szCOMRAT), "%c%03u",
    5833           4 :                          EQUAL(pszProfile, "NPJE_VISUALLY_LOSSLESS") ? 'V'
    5834             :                                                                      : 'N',
    5835             :                          // % 1000 to please -Wformat-truncation
    5836           4 :                          static_cast<unsigned>(dfRate * 10) % 1000);
    5837             :             }
    5838             :             else
    5839             :             {
    5840           8 :                 dfRate = std::max(0.01, std::min(99.99, dfRate));
    5841             : 
    5842             :                 // We emit in wxyz format with an implicit decimal place
    5843             :                 // between wx and yz as per spec for lossy compression.
    5844             :                 // We really should have a special case for lossless
    5845             :                 // compression.
    5846           8 :                 snprintf(szCOMRAT, sizeof(szCOMRAT), "%04u",
    5847             :                          // % 10000 to please -Wformat-truncation
    5848           8 :                          static_cast<unsigned>(dfRate * 100) % 10000);
    5849             :             }
    5850             :         }
    5851          10 :         else if (EQUAL(pszIC, "C3") || EQUAL(pszIC, "M3")) /* jpeg */
    5852             :         {
    5853          10 :             strcpy(szCOMRAT, "00.0");
    5854             :         }
    5855             : 
    5856          22 :         bOK &= VSIFWriteL(szCOMRAT, 4, 1, fpVSIL) == 1;
    5857             : 
    5858             :         /* ---------------------------------------------------------------- */
    5859             :         /*      Update CLEVEL.                                              */
    5860             :         /* ---------------------------------------------------------------- */
    5861             :         // Get existing CLEVEL
    5862          22 :         constexpr int OFFSET_CLEVEL = 9;
    5863          22 :         constexpr int SIZE_CLEVEL = 2;
    5864          22 :         bOK &= VSIFSeekL(fpVSIL, OFFSET_CLEVEL, SEEK_SET) == 0;
    5865          22 :         char szCLEVEL[SIZE_CLEVEL + 1] = {0};
    5866          22 :         bOK &= VSIFReadL(szCLEVEL, 1, SIZE_CLEVEL, fpVSIL) != 0;
    5867          22 :         unsigned int nCLevel = static_cast<unsigned>(atoi(szCLEVEL));
    5868          22 :         if (nCLevel >= 3 && nCLevel <= 7)
    5869             :         {
    5870          22 :             const unsigned int nCLevelOri = nCLevel;
    5871          22 :             if (nFileLen > 2147483647)
    5872             :             {
    5873           0 :                 nCLevel = MAX(nCLevel, 7U);
    5874             :             }
    5875          22 :             else if (nFileLen > 1073741833)
    5876             :             {
    5877           0 :                 nCLevel = MAX(nCLevel, 6U);
    5878             :             }
    5879          22 :             else if (nFileLen > 52428799)
    5880             :             {
    5881           1 :                 nCLevel = MAX(nCLevel, 5U);
    5882             :             }
    5883          22 :             if (nCLevel != nCLevelOri)
    5884             :             {
    5885           0 :                 CPLDebug("NITF", "Updating CLEVEL from %02u to %02u",
    5886             :                          nCLevelOri, nCLevel);
    5887             :                 // %100 to please -Wformat-truncation
    5888           0 :                 snprintf(szCLEVEL, sizeof(szCLEVEL), "%02u", nCLevel % 100);
    5889           0 :                 bOK &= VSIFSeekL(fpVSIL, OFFSET_CLEVEL, SEEK_SET) == 0;
    5890           0 :                 bOK &= VSIFWriteL(szCLEVEL, 1, SIZE_CLEVEL, fpVSIL) != 0;
    5891          22 :             }
    5892             :         }
    5893             :         else
    5894             :         {
    5895           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    5896             :                      "Invalid CLEVEL=%s value found when updating NITF header.",
    5897             :                      szCLEVEL);
    5898             :         }
    5899             :     }
    5900             : 
    5901          22 :     if (VSIFCloseL(fpVSIL) != 0)
    5902           0 :         bOK = false;
    5903             : 
    5904          22 :     if (!bOK)
    5905             :     {
    5906           0 :         CPLError(CE_Failure, CPLE_FileIO, "I/O error");
    5907             :     }
    5908             : 
    5909          22 :     return bOK;
    5910             : }
    5911             : 
    5912             : /************************************************************************/
    5913             : /*                       NITFWriteCGMSegments()                        */
    5914             : /************************************************************************/
    5915         245 : static bool NITFWriteCGMSegments(const char *pszFilename, VSILFILE *&fpVSIL,
    5916             :                                  CSLConstList papszList)
    5917             : {
    5918         245 :     char errorMessage[255] = "";
    5919             : 
    5920             :     // size of each Cgm header entry (LS (4) + LSSH (6))
    5921         245 :     const int nCgmHdrEntrySz = 10;
    5922             : 
    5923         245 :     if (papszList == nullptr)
    5924         233 :         return true;
    5925             : 
    5926          12 :     int nNUMS = 0;
    5927          12 :     const char *pszNUMS = CSLFetchNameValue(papszList, "SEGMENT_COUNT");
    5928          12 :     if (pszNUMS != nullptr)
    5929             :     {
    5930          12 :         nNUMS = atoi(pszNUMS);
    5931             :     }
    5932             : 
    5933             :     /* -------------------------------------------------------------------- */
    5934             :     /*      Open the target file if not already done.                       */
    5935             :     /* -------------------------------------------------------------------- */
    5936          12 :     if (fpVSIL == nullptr)
    5937          12 :         fpVSIL = VSIFOpenL(pszFilename, "r+b");
    5938          12 :     if (fpVSIL == nullptr)
    5939           0 :         return false;
    5940             : 
    5941             :     // Calculates the offset for NUMS so we can update header data
    5942             :     char achNUMI[4];  // 3 digits plus null character
    5943          12 :     achNUMI[3] = '\0';
    5944             : 
    5945             :     // NUMI offset is at a fixed offset 363
    5946          12 :     const int nNumIOffset = 360;
    5947          12 :     bool bOK = VSIFSeekL(fpVSIL, nNumIOffset, SEEK_SET) == 0;
    5948          12 :     bOK &= VSIFReadL(achNUMI, 3, 1, fpVSIL) == 1;
    5949          12 :     const int nIM = atoi(achNUMI);
    5950             : 
    5951             :     // 6 for size of LISH and 10 for size of LI
    5952             :     // NUMS offset is NumI offset plus the size of NumI + size taken up each
    5953             :     // the header data multiply by the number of data
    5954             : 
    5955          12 :     const int nNumSOffset = nNumIOffset + 3 + nIM * (6 + 10);
    5956             : 
    5957             :     /* -------------------------------------------------------------------- */
    5958             :     /*      Confirm that the NUMS in the file header already matches the    */
    5959             :     /*      number of graphic segments we want to write                     */
    5960             :     /* -------------------------------------------------------------------- */
    5961             :     char achNUMS[4];
    5962             : 
    5963          12 :     bOK &= VSIFSeekL(fpVSIL, nNumSOffset, SEEK_SET) == 0;
    5964          12 :     bOK &= VSIFReadL(achNUMS, 3, 1, fpVSIL) == 1;
    5965          12 :     achNUMS[3] = '\0';
    5966             : 
    5967          12 :     if (!bOK || atoi(achNUMS) != nNUMS)
    5968             :     {
    5969           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5970             :                  "It appears an attempt was made to add or update graphic\n"
    5971             :                  "segments on an NITF file with existing segments.  This\n"
    5972             :                  "is not currently supported by the GDAL NITF driver.");
    5973             : 
    5974           0 :         return false;
    5975             :     }
    5976             : 
    5977             :     // allocate space for graphic header.
    5978             :     // Size of LS = 4, size of LSSH = 6, and 1 for null character
    5979             :     char *pachLS =
    5980          12 :         reinterpret_cast<char *>(CPLCalloc(nNUMS * nCgmHdrEntrySz + 1, 1));
    5981             : 
    5982             :     /* -------------------------------------------------------------------- */
    5983             :     /*  Assume no extended data such as SXSHDL, SXSHD                       */
    5984             :     /* -------------------------------------------------------------------- */
    5985             : 
    5986             :     /* ==================================================================== */
    5987             :     /*      Write the Graphics segments at the end of the file.             */
    5988             :     /* ==================================================================== */
    5989             : 
    5990             : #define PLACE(location, name, text) memcpy(location, text, strlen(text))
    5991             : 
    5992          15 :     for (int i = 0; bOK && i < nNUMS; i++)
    5993             :     {
    5994             : 
    5995             :         // Get all the fields for current CGM segment
    5996           3 :         const char *pszSlocRow = CSLFetchNameValue(
    5997           6 :             papszList, CPLString().Printf("SEGMENT_%d_SLOC_ROW", i));
    5998           3 :         const char *pszSlocCol = CSLFetchNameValue(
    5999           6 :             papszList, CPLString().Printf("SEGMENT_%d_SLOC_COL", i));
    6000           3 :         const char *pszSdlvl = CSLFetchNameValue(
    6001           6 :             papszList, CPLString().Printf("SEGMENT_%d_SDLVL", i));
    6002           3 :         const char *pszSalvl = CSLFetchNameValue(
    6003           6 :             papszList, CPLString().Printf("SEGMENT_%d_SALVL", i));
    6004           3 :         const char *pszData = CSLFetchNameValue(
    6005           6 :             papszList, CPLString().Printf("SEGMENT_%d_DATA", i));
    6006             : 
    6007             :         // Error checking
    6008           3 :         if (pszSlocRow == nullptr)
    6009             :         {
    6010           0 :             snprintf(errorMessage, sizeof(errorMessage),
    6011             :                      "NITF graphic segment writing error: SLOC_ROW for segment "
    6012             :                      "%d is not defined",
    6013             :                      i);
    6014           0 :             break;
    6015             :         }
    6016           3 :         if (pszSlocCol == nullptr)
    6017             :         {
    6018           0 :             snprintf(errorMessage, sizeof(errorMessage),
    6019             :                      "NITF graphic segment writing error: SLOC_COL for segment "
    6020             :                      "%d is not defined",
    6021             :                      i);
    6022           0 :             break;
    6023             :         }
    6024           3 :         if (pszSdlvl == nullptr)
    6025             :         {
    6026           0 :             snprintf(errorMessage, sizeof(errorMessage),
    6027             :                      "NITF graphic segment writing error: SDLVL for segment %d "
    6028             :                      "is not defined",
    6029             :                      i);
    6030           0 :             break;
    6031             :         }
    6032           3 :         if (pszSalvl == nullptr)
    6033             :         {
    6034           0 :             snprintf(errorMessage, sizeof(errorMessage),
    6035             :                      "NITF graphic segment writing error: SALVLfor segment %d "
    6036             :                      "is not defined",
    6037             :                      i);
    6038           0 :             break;
    6039             :         }
    6040           3 :         if (pszData == nullptr)
    6041             :         {
    6042           0 :             snprintf(errorMessage, sizeof(errorMessage),
    6043             :                      "NITF graphic segment writing error: DATA for segment %d "
    6044             :                      "is not defined",
    6045             :                      i);
    6046           0 :             break;
    6047             :         }
    6048             : 
    6049           3 :         const int nSlocCol = atoi(pszSlocRow);
    6050           3 :         const int nSlocRow = atoi(pszSlocCol);
    6051           3 :         const int nSdlvl = atoi(pszSdlvl);
    6052           3 :         const int nSalvl = atoi(pszSalvl);
    6053             : 
    6054             :         // Create a buffer for graphics segment header, 258 is the size of
    6055             :         // the header that we will be writing.
    6056             :         char achGSH[258];
    6057             : 
    6058           3 :         memset(achGSH, ' ', sizeof(achGSH));
    6059             : 
    6060           3 :         PLACE(achGSH + 0, SY, "SY");
    6061           3 :         PLACE(achGSH + 2, SID, CPLSPrintf("%010d", i));
    6062           3 :         PLACE(achGSH + 12, SNAME, "DEFAULT NAME        ");
    6063           3 :         PLACE(achGSH + 32, SSCLAS, "U");
    6064           3 :         PLACE(achGSH + 33, SSCLASY, "0");
    6065           3 :         PLACE(achGSH + 199, ENCRYP, "0");
    6066           3 :         PLACE(achGSH + 200, SFMT, "C");
    6067           3 :         PLACE(achGSH + 201, SSTRUCT, "0000000000000");
    6068           3 :         PLACE(achGSH + 214, SDLVL, CPLSPrintf("%03d", nSdlvl));  // size3
    6069           3 :         PLACE(achGSH + 217, SALVL, CPLSPrintf("%03d", nSalvl));  // size3
    6070           3 :         PLACE(achGSH + 220, SLOC,
    6071             :               CPLSPrintf("%05d%05d", nSlocRow, nSlocCol));  // size 10
    6072           3 :         PLACE(achGSH + 230, SBAND1, "0000000000");
    6073           3 :         PLACE(achGSH + 240, SCOLOR, "C");
    6074           3 :         PLACE(achGSH + 241, SBAND2, "0000000000");
    6075           3 :         PLACE(achGSH + 251, SRES2, "00");
    6076           3 :         PLACE(achGSH + 253, SXSHDL, "00000");
    6077             : 
    6078             :         // Move to the end of the file
    6079           3 :         bOK &= VSIFSeekL(fpVSIL, 0, SEEK_END) == 0;
    6080           3 :         bOK &= VSIFWriteL(achGSH, sizeof(achGSH), 1, fpVSIL) == 1;
    6081             : 
    6082             :         /* ------------------------------------------------------------------ */
    6083             :         /*      Prepare and write CGM segment data.                           */
    6084             :         /* ------------------------------------------------------------------ */
    6085           3 :         int nCGMSize = 0;
    6086             :         char *pszCgmToWrite =
    6087           3 :             CPLUnescapeString(pszData, &nCGMSize, CPLES_BackslashQuotable);
    6088             : 
    6089           3 :         if (nCGMSize > 999998)
    6090             :         {
    6091           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    6092             :                      "Length of SEGMENT_%d_DATA is %d, which is greater than "
    6093             :                      "999998. Truncating...",
    6094             :                      i + 1, nCGMSize);
    6095           0 :             nCGMSize = 999998;
    6096             :         }
    6097             : 
    6098           3 :         bOK &= static_cast<int>(
    6099           3 :                    VSIFWriteL(pszCgmToWrite, 1, nCGMSize, fpVSIL)) == nCGMSize;
    6100             : 
    6101             :         /* --------------------------------------------------------------------
    6102             :          */
    6103             :         /*      Update the subheader and data size info in the file header. */
    6104             :         /* --------------------------------------------------------------------
    6105             :          */
    6106           3 :         snprintf(pachLS + nCgmHdrEntrySz * i, nCgmHdrEntrySz + 1, "%04d%06d",
    6107             :                  static_cast<int>(sizeof(achGSH)), nCGMSize);
    6108             : 
    6109           3 :         CPLFree(pszCgmToWrite);
    6110             :     }  // End For
    6111             : 
    6112             :     /* -------------------------------------------------------------------- */
    6113             :     /*      Write out the graphic segment info.                             */
    6114             :     /* -------------------------------------------------------------------- */
    6115             : 
    6116          12 :     bOK &= VSIFSeekL(fpVSIL, nNumSOffset + 3, SEEK_SET) == 0;
    6117          12 :     bOK &= static_cast<int>(VSIFWriteL(pachLS, 1, nNUMS * nCgmHdrEntrySz,
    6118          12 :                                        fpVSIL)) == nNUMS * nCgmHdrEntrySz;
    6119             : 
    6120          12 :     CPLFree(pachLS);
    6121             : 
    6122          12 :     if (strlen(errorMessage) != 0)
    6123             :     {
    6124           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s", errorMessage);
    6125           0 :         bOK = false;
    6126             :     }
    6127             : 
    6128          12 :     return bOK;
    6129             : }
    6130             : 
    6131             : /************************************************************************/
    6132             : /*                       NITFWriteTextSegments()                        */
    6133             : /************************************************************************/
    6134             : 
    6135         245 : static bool NITFWriteTextSegments(const char *pszFilename, VSILFILE *&fpVSIL,
    6136             :                                   CSLConstList papszList)
    6137             : 
    6138             : {
    6139             :     /* -------------------------------------------------------------------- */
    6140             :     /*      Count the number of apparent text segments to write.  There     */
    6141             :     /*      is nothing at all to do if there are none to write.             */
    6142             :     /* -------------------------------------------------------------------- */
    6143         245 :     int nNUMT = 0;
    6144             : 
    6145         253 :     for (int iOpt = 0; papszList != nullptr && papszList[iOpt] != nullptr;
    6146             :          iOpt++)
    6147             :     {
    6148           8 :         if (STARTS_WITH_CI(papszList[iOpt], "DATA_"))
    6149           5 :             nNUMT++;
    6150             :     }
    6151             : 
    6152         245 :     if (nNUMT == 0)
    6153         241 :         return true;
    6154             : 
    6155             :     /* -------------------------------------------------------------------- */
    6156             :     /*      Open the target file if not already done.                       */
    6157             :     /* -------------------------------------------------------------------- */
    6158           4 :     if (fpVSIL == nullptr)
    6159           1 :         fpVSIL = VSIFOpenL(pszFilename, "r+b");
    6160           4 :     if (fpVSIL == nullptr)
    6161           0 :         return false;
    6162             : 
    6163             :     // Get number of text field.  Since there there could be multiple images
    6164             :     // or graphic segment, the  offset need to be calculated dynamically.
    6165             : 
    6166             :     char achNUMI[4];  // 3 digits plus null character
    6167           4 :     achNUMI[3] = '\0';
    6168             :     // NUMI offset is at a fixed offset 363
    6169           4 :     int nNumIOffset = 360;
    6170           4 :     bool bOK = VSIFSeekL(fpVSIL, nNumIOffset, SEEK_SET) == 0;
    6171           4 :     bOK &= VSIFReadL(achNUMI, 3, 1, fpVSIL) == 1;
    6172           4 :     int nIM = atoi(achNUMI);
    6173             : 
    6174             :     char achNUMG[4];  // 3 digits plus null character
    6175           4 :     achNUMG[3] = '\0';
    6176             : 
    6177             :     // 3 for size of NUMI.  6 and 10 are the field size for LISH and LI
    6178           4 :     const int nNumGOffset = nNumIOffset + 3 + nIM * (6 + 10);
    6179           4 :     bOK &= VSIFSeekL(fpVSIL, nNumGOffset, SEEK_SET) == 0;
    6180           4 :     bOK &= VSIFReadL(achNUMG, 3, 1, fpVSIL) == 1;
    6181           4 :     const int nGS = atoi(achNUMG);
    6182             : 
    6183             :     // NUMT offset
    6184             :     // 3 for size of NUMG.  4 and 6 are filed size of LSSH and LS.
    6185             :     // the last + 3 is for NUMX field, which is not used
    6186           4 :     const int nNumTOffset = nNumGOffset + 3 + nGS * (4 + 6) + 3;
    6187             : 
    6188             :     /* -------------------------------------------------------------------- */
    6189             :     /*      Confirm that the NUMT in the file header already matches the    */
    6190             :     /*      number of text segments we want to write, and that the          */
    6191             :     /*      segment header/data size info is blank.                         */
    6192             :     /* -------------------------------------------------------------------- */
    6193             :     char achNUMT[4];
    6194           4 :     char *pachLT = reinterpret_cast<char *>(CPLCalloc(nNUMT * 9 + 1, 1));
    6195             : 
    6196           4 :     bOK &= VSIFSeekL(fpVSIL, nNumTOffset, SEEK_SET) == 0;
    6197           4 :     bOK &= VSIFReadL(achNUMT, 3, 1, fpVSIL) == 1;
    6198           4 :     achNUMT[3] = '\0';
    6199             : 
    6200           4 :     bOK &= VSIFReadL(pachLT, nNUMT * 9, 1, fpVSIL) == 1;
    6201             : 
    6202           4 :     if (!bOK || atoi(achNUMT) != nNUMT)
    6203             :     {
    6204           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6205             :                  "It appears an attempt was made to add or update text\n"
    6206             :                  "segments on an NITF file with existing segments.  This\n"
    6207             :                  "is not currently supported by the GDAL NITF driver.");
    6208             : 
    6209           0 :         CPLFree(pachLT);
    6210           0 :         return false;
    6211             :     }
    6212             : 
    6213           4 :     if (!STARTS_WITH_CI(pachLT, "         "))
    6214             :     {
    6215           0 :         CPLFree(pachLT);
    6216             :         // presumably the text segments are already written, do nothing.
    6217           0 :         return true;
    6218             :     }
    6219             : 
    6220             : /* -------------------------------------------------------------------- */
    6221             : /*      At this point we likely ought to confirm NUMDES, NUMRES,        */
    6222             : /*      UDHDL and XHDL are zero.  Consider adding later...              */
    6223             : /* -------------------------------------------------------------------- */
    6224             : 
    6225             : /* ==================================================================== */
    6226             : /*      Write the text segments at the end of the file.                 */
    6227             : /* ==================================================================== */
    6228             : #define PLACE(location, name, text) memcpy(location, text, strlen(text))
    6229           4 :     int iTextSeg = 0;
    6230             : 
    6231          12 :     for (int iOpt = 0;
    6232          12 :          bOK && papszList != nullptr && papszList[iOpt] != nullptr; iOpt++)
    6233             :     {
    6234           8 :         if (!STARTS_WITH_CI(papszList[iOpt], "DATA_"))
    6235           3 :             continue;
    6236             : 
    6237             :         const char *pszTextToWrite =
    6238           5 :             CPLParseNameValue(papszList[iOpt], nullptr);
    6239           5 :         if (pszTextToWrite == nullptr)
    6240           0 :             continue;
    6241             : 
    6242             :         /* --------------------------------------------------------------------
    6243             :          */
    6244             :         /*      Locate corresponding header data in the buffer */
    6245             :         /* --------------------------------------------------------------------
    6246             :          */
    6247             : 
    6248           5 :         const char *pszHeaderBuffer = nullptr;
    6249          11 :         for (int iOpt2 = 0; papszList[iOpt2] != nullptr; iOpt2++)
    6250             :         {
    6251           9 :             if (!STARTS_WITH_CI(papszList[iOpt2], "HEADER_"))
    6252           6 :                 continue;
    6253             : 
    6254           3 :             char *pszHeaderKey = nullptr;
    6255           3 :             CPLParseNameValue(papszList[iOpt2], &pszHeaderKey);
    6256           3 :             char *pszDataKey = nullptr;
    6257           3 :             CPLParseNameValue(papszList[iOpt], &pszDataKey);
    6258           3 :             if (pszHeaderKey == nullptr || pszDataKey == nullptr)
    6259             :             {
    6260           0 :                 CPLFree(pszHeaderKey);
    6261           0 :                 CPLFree(pszDataKey);
    6262           0 :                 continue;
    6263             :             }
    6264             : 
    6265             :             // Point to header and data number.
    6266           3 :             char *pszHeaderId = pszHeaderKey + 7;
    6267           3 :             char *pszDataId = pszDataKey + 5;
    6268             : 
    6269           3 :             const bool bIsSameId = strcmp(pszHeaderId, pszDataId) == 0;
    6270           3 :             CPLFree(pszHeaderKey);
    6271           3 :             CPLFree(pszDataKey);
    6272             : 
    6273             :             // if ID matches, read the header information and exit the loop
    6274           3 :             if (bIsSameId)
    6275             :             {
    6276           3 :                 pszHeaderBuffer = CPLParseNameValue(papszList[iOpt2], nullptr);
    6277           3 :                 break;
    6278             :             }
    6279             :         }
    6280             : 
    6281             :         /* --------------------------------------------------------------------
    6282             :          */
    6283             :         /*      Prepare and write text header. */
    6284             :         /* --------------------------------------------------------------------
    6285             :          */
    6286             :         char achTSH[282];
    6287           5 :         memset(achTSH, ' ', sizeof(achTSH));
    6288           5 :         bOK &= VSIFSeekL(fpVSIL, 0, SEEK_END) == 0;
    6289             : 
    6290           5 :         if (pszHeaderBuffer != nullptr)
    6291             :         {
    6292           3 :             memcpy(achTSH, pszHeaderBuffer,
    6293           3 :                    std::min(strlen(pszHeaderBuffer), sizeof(achTSH)));
    6294             : 
    6295             :             // Take care NITF2.0 date format changes
    6296           3 :             const char chTimeZone = achTSH[20];
    6297             : 
    6298             :             // Check for Zulu time zone character.  IpachLTf that exist, then
    6299             :             // it is NITF2.0 format.
    6300           3 :             if (chTimeZone == 'Z')
    6301             :             {
    6302           0 :                 char *achOrigDate = achTSH + 12;  // original date string
    6303             : 
    6304             :                 // The date value taken from default NITF file date
    6305             :                 char achYear[3];
    6306             : 
    6307             :                 // Offset to the year
    6308           0 :                 strncpy(achYear, achOrigDate + 12, 2);
    6309           0 :                 achYear[2] = '\0';
    6310           0 :                 const int nYear = atoi(achYear);
    6311             : 
    6312             :                 // Set century.
    6313             :                 // Since NITF2.0 does not track the century, we are going to
    6314             :                 // assume any year number greater then 94 (the year NITF2.0
    6315             :                 // spec published), will be 1900s, otherwise, it is 2000s.
    6316           0 :                 char achNewDate[] = "20021216151629";
    6317           0 :                 if (nYear > 94)
    6318           0 :                     memcpy(achNewDate, "19", 2);
    6319             :                 else
    6320           0 :                     memcpy(achNewDate, "20", 2);
    6321             : 
    6322           0 :                 memcpy(achNewDate + 6, achOrigDate, 8);  // copy cover DDhhmmss
    6323           0 :                 memcpy(achNewDate + 2, achOrigDate + 12, 2);  // copy over years
    6324             : 
    6325             :                 // Perform month conversion
    6326           0 :                 char *pszOrigMonth = achOrigDate + 9;
    6327           0 :                 char *pszNewMonth = achNewDate + 4;
    6328             : 
    6329           0 :                 if (STARTS_WITH(pszOrigMonth, "JAN"))
    6330           0 :                     memcpy(pszNewMonth, "01", 2);
    6331           0 :                 else if (STARTS_WITH(pszOrigMonth, "FEB"))
    6332           0 :                     memcpy(pszNewMonth, "02", 2);
    6333           0 :                 else if (STARTS_WITH(pszOrigMonth, "MAR"))
    6334           0 :                     memcpy(pszNewMonth, "03", 2);
    6335           0 :                 else if (STARTS_WITH(pszOrigMonth, "APR"))
    6336           0 :                     memcpy(pszNewMonth, "04", 2);
    6337           0 :                 else if (STARTS_WITH(pszOrigMonth, "MAY"))
    6338           0 :                     memcpy(pszNewMonth, "05", 2);
    6339           0 :                 else if (STARTS_WITH(pszOrigMonth, "JUN"))
    6340           0 :                     memcpy(pszNewMonth, "07", 2);
    6341           0 :                 else if (STARTS_WITH(pszOrigMonth, "AUG"))
    6342           0 :                     memcpy(pszNewMonth, "08", 2);
    6343           0 :                 else if (STARTS_WITH(pszOrigMonth, "SEP"))
    6344           0 :                     memcpy(pszNewMonth, "09", 2);
    6345           0 :                 else if (STARTS_WITH(pszOrigMonth, "OCT"))
    6346           0 :                     memcpy(pszNewMonth, "10", 2);
    6347           0 :                 else if (STARTS_WITH(pszOrigMonth, "NOV"))
    6348           0 :                     memcpy(pszNewMonth, "11", 2);
    6349           0 :                 else if (STARTS_WITH(pszOrigMonth, "DEC"))
    6350           0 :                     memcpy(pszNewMonth, "12", 2);
    6351             : 
    6352           0 :                 PLACE(achTSH + 12, TXTDT, achNewDate);
    6353             :             }
    6354             :         }
    6355             :         else
    6356             :         {  // Use default value if header information is not found
    6357           2 :             PLACE(achTSH + 0, TE, "TE");
    6358           2 :             PLACE(achTSH + 9, TXTALVL, "000");
    6359           2 :             PLACE(achTSH + 12, TXTDT, "20021216151629");
    6360           2 :             PLACE(achTSH + 106, TSCLAS, "U");
    6361           2 :             PLACE(achTSH + 273, ENCRYP, "0");
    6362           2 :             PLACE(achTSH + 274, TXTFMT, "STA");
    6363           2 :             PLACE(achTSH + 277, TXSHDL, "00000");
    6364             :         }
    6365             : 
    6366           5 :         bOK &= VSIFWriteL(achTSH, sizeof(achTSH), 1, fpVSIL) == 1;
    6367             : 
    6368             :         /* --------------------------------------------------------------------
    6369             :          */
    6370             :         /*      Prepare and write text segment data. */
    6371             :         /* --------------------------------------------------------------------
    6372             :          */
    6373             : 
    6374           5 :         int nTextLength = static_cast<int>(strlen(pszTextToWrite));
    6375           5 :         if (nTextLength > 99998)
    6376             :         {
    6377           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    6378             :                      "Length of DATA_%d is %d, which is greater than 99998. "
    6379             :                      "Truncating...",
    6380             :                      iTextSeg + 1, nTextLength);
    6381           0 :             nTextLength = 99998;
    6382             :         }
    6383             : 
    6384           5 :         bOK &= static_cast<int>(VSIFWriteL(pszTextToWrite, 1, nTextLength,
    6385           5 :                                            fpVSIL)) == nTextLength;
    6386             : 
    6387             :         /* --------------------------------------------------------------------
    6388             :          */
    6389             :         /*      Update the subheader and data size info in the file header. */
    6390             :         /* --------------------------------------------------------------------
    6391             :          */
    6392           5 :         CPLsnprintf(pachLT + 9 * iTextSeg + 0, 9 + 1, "%04d%05d",
    6393             :                     static_cast<int>(sizeof(achTSH)), nTextLength);
    6394             : 
    6395           5 :         iTextSeg++;
    6396             :     }
    6397             : 
    6398             :     /* -------------------------------------------------------------------- */
    6399             :     /*      Write out the text segment info.                                */
    6400             :     /* -------------------------------------------------------------------- */
    6401             : 
    6402           4 :     bOK &= VSIFSeekL(fpVSIL, nNumTOffset + 3, SEEK_SET) == 0;
    6403           4 :     bOK &=
    6404           4 :         static_cast<int>(VSIFWriteL(pachLT, 1, nNUMT * 9, fpVSIL)) == nNUMT * 9;
    6405             : 
    6406           4 :     CPLFree(pachLT);
    6407             : 
    6408           4 :     return bOK;
    6409             : }
    6410             : 
    6411             : /************************************************************************/
    6412             : /*                            NITFWriteDES()                            */
    6413             : /************************************************************************/
    6414             : 
    6415          12 : static bool NITFWriteDES(VSILFILE *&fp, const char *pszFilename,
    6416             :                          vsi_l_offset nOffsetLDSH, int iDES,
    6417             :                          const char *pszDESName, const GByte *pabyDESData,
    6418             :                          int nArrayLen)
    6419             : {
    6420          12 :     constexpr int LEN_DE = 2;
    6421          12 :     constexpr int LEN_DESID = 25;
    6422          12 :     constexpr int LEN_DESOFLW = 6;
    6423          12 :     constexpr int LEN_DESITEM = 3;
    6424          12 :     const int nTotalLen = LEN_DE + LEN_DESID + nArrayLen;
    6425             : 
    6426          12 :     const bool bIsTRE_OVERFLOW = (strcmp(pszDESName, "TRE_OVERFLOW") == 0);
    6427          12 :     const int MIN_LEN_DES_SUBHEADER =
    6428          12 :         200 + (bIsTRE_OVERFLOW ? LEN_DESOFLW + LEN_DESITEM : 0);
    6429             : 
    6430          12 :     if (nTotalLen < MIN_LEN_DES_SUBHEADER)
    6431             :     {
    6432           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6433             :                  "DES does not contain enough data");
    6434           0 :         return false;
    6435             :     }
    6436             : 
    6437          12 :     int nDESITEM = 0;
    6438          12 :     GUIntBig nIXSOFLOffset = 0;
    6439          12 :     if (bIsTRE_OVERFLOW)
    6440             :     {
    6441             :         char szDESITEM[LEN_DESITEM + 1];
    6442           3 :         memcpy(szDESITEM, pabyDESData + 169 + LEN_DESOFLW, LEN_DESITEM);
    6443           3 :         szDESITEM[LEN_DESITEM] = '\0';
    6444           3 :         if (!isdigit(static_cast<unsigned char>(szDESITEM[0])) ||
    6445           3 :             !isdigit(static_cast<unsigned char>(szDESITEM[1])) ||
    6446           3 :             !isdigit(static_cast<unsigned char>(szDESITEM[2])))
    6447             :         {
    6448           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6449             :                      "Invalid value for DESITEM: '%s'", szDESITEM);
    6450           2 :             return false;
    6451             :         }
    6452           3 :         nDESITEM = atoi(szDESITEM);
    6453             : 
    6454             :         char szDESOFLW[LEN_DESOFLW + 1];
    6455           3 :         memcpy(szDESOFLW, pabyDESData + 169, LEN_DESOFLW);
    6456           3 :         szDESOFLW[LEN_DESOFLW] = '\0';
    6457           3 :         if (strcmp(szDESOFLW, "IXSHD ") == 0)
    6458             :         {
    6459           3 :             auto psFile = NITFOpenEx(fp, pszFilename);
    6460           3 :             if (psFile == nullptr)
    6461             :             {
    6462           0 :                 fp = nullptr;
    6463           0 :                 return false;
    6464             :             }
    6465             : 
    6466           3 :             int nImageIdx = 1;
    6467           5 :             for (int iSegment = 0; iSegment < psFile->nSegmentCount; ++iSegment)
    6468             :             {
    6469           4 :                 const auto psSegInfo = psFile->pasSegmentInfo + iSegment;
    6470           4 :                 if (!EQUAL(psSegInfo->szSegmentType, "IM"))
    6471           1 :                     continue;
    6472           3 :                 if (nImageIdx == nDESITEM)
    6473             :                 {
    6474           2 :                     auto psImage = NITFImageAccess(psFile, iSegment);
    6475           2 :                     if (psImage == nullptr)
    6476             :                     {
    6477           0 :                         nImageIdx = -1;
    6478           0 :                         break;
    6479             :                     }
    6480             : 
    6481           2 :                     if (psImage->nIXSOFL == -1)
    6482             :                     {
    6483           1 :                         CPLError(CE_Failure, CPLE_AppDefined,
    6484             :                                  "Missing IXSOFL field in image %d. "
    6485             :                                  "RESERVE_SPACE_FOR_TRE_OVERFLOW=YES creation "
    6486             :                                  "option likely missing.",
    6487             :                                  nImageIdx);
    6488             :                     }
    6489           1 :                     else if (psImage->nIXSOFL != 0)
    6490             :                     {
    6491           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    6492             :                                  "Expected IXSOFL of image %d to be 0. Got %d",
    6493             :                                  nImageIdx, psImage->nIXSOFL);
    6494             :                     }
    6495             :                     else
    6496             :                     {
    6497           1 :                         nIXSOFLOffset = psSegInfo->nSegmentHeaderStart +
    6498           1 :                                         psImage->nIXSOFLOffsetInSubfileHeader;
    6499             :                     }
    6500             : 
    6501           2 :                     NITFImageDeaccess(psImage);
    6502           2 :                     break;
    6503             :                 }
    6504           1 :                 ++nImageIdx;
    6505             :             }
    6506             : 
    6507           3 :             psFile->fp = nullptr;
    6508           3 :             NITFClose(psFile);
    6509             : 
    6510           3 :             if (nImageIdx != nDESITEM)
    6511             :             {
    6512           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6513             :                          "Cannot find image matching DESITEM = %d value",
    6514             :                          nDESITEM);
    6515           0 :                 return false;
    6516             :             }
    6517           3 :             if (nIXSOFLOffset == 0)
    6518             :             {
    6519           2 :                 return false;
    6520             :             }
    6521             :         }
    6522           0 :         else if (strcmp(szDESOFLW, "UDHD  ") == 0 ||
    6523           0 :                  strcmp(szDESOFLW, "UDID  ") == 0 ||
    6524           0 :                  strcmp(szDESOFLW, "XHD   ") == 0 ||
    6525           0 :                  strcmp(szDESOFLW, "SXSHD ") == 0 ||
    6526           0 :                  strcmp(szDESOFLW, "TXSHD ") == 0)
    6527             :         {
    6528           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    6529             :                      "Unhandled value for DESOFLW: '%s'. "
    6530             :                      "Segment subheader fields will not be updated.",
    6531             :                      szDESOFLW);
    6532             :         }
    6533             :         else
    6534             :         {
    6535           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6536             :                      "Invalid value for DESOFLW: '%s'", szDESOFLW);
    6537           0 :             return false;
    6538             :         }
    6539             :     }
    6540             : 
    6541             :     // Extract DESSHL value
    6542          10 :     constexpr int LEN_DESSHL = 4;
    6543             :     char szDESSHL[LEN_DESSHL + 1];
    6544          10 :     const int OFFSET_DESSHL =
    6545          10 :         169 + (bIsTRE_OVERFLOW ? LEN_DESOFLW + LEN_DESITEM : 0);
    6546          10 :     memcpy(szDESSHL, pabyDESData + OFFSET_DESSHL, LEN_DESSHL);
    6547          10 :     szDESSHL[LEN_DESSHL] = '\0';
    6548          10 :     if (!isdigit(static_cast<unsigned char>(szDESSHL[0])) ||
    6549          10 :         !isdigit(static_cast<unsigned char>(szDESSHL[1])) ||
    6550          10 :         !isdigit(static_cast<unsigned char>(szDESSHL[2])) ||
    6551          10 :         !isdigit(static_cast<unsigned char>(szDESSHL[3])))
    6552             :     {
    6553           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for DESSHL: '%s'",
    6554             :                  szDESSHL);
    6555           0 :         return false;
    6556             :     }
    6557          10 :     const int nDESSHL = atoi(szDESSHL);
    6558          10 :     const int nSubHeadLen = nDESSHL + MIN_LEN_DES_SUBHEADER;
    6559          10 :     const int nDataLen =
    6560             :         nTotalLen - nSubHeadLen;  // Length of DESDATA field only
    6561          10 :     if (nDataLen < 0)
    6562             :     {
    6563           0 :         CPLError(
    6564             :             CE_Failure, CPLE_AppDefined,
    6565             :             "Value of DESSHL = '%s' is not consistent with provided DESData",
    6566             :             szDESSHL);
    6567           0 :         return false;
    6568             :     }
    6569             : 
    6570          10 :     if (nSubHeadLen > 9998 || nDataLen > 999999998)
    6571             :     {
    6572           0 :         CPLError(CE_Failure, CPLE_AppDefined, "DES is too big to be written");
    6573           0 :         return false;
    6574             :     }
    6575             : 
    6576          10 :     bool bOK = VSIFSeekL(fp, 0, SEEK_END) == 0;
    6577          10 :     bOK &= VSIFWriteL("DE", 1, 2, fp) == 2;
    6578          10 :     bOK &= VSIFWriteL(CPLSPrintf("%-25s", pszDESName), 1, 25, fp) == 25;
    6579          10 :     bOK &= (int)VSIFWriteL(pabyDESData, 1, nArrayLen, fp) == nArrayLen;
    6580             : 
    6581             :     // Update LDSH and LD in the NITF Header
    6582          10 :     bOK &= VSIFSeekL(fp, nOffsetLDSH + iDES * 13, SEEK_SET) == 0;
    6583          10 :     bOK &= VSIFWriteL(CPLSPrintf("%04d", nSubHeadLen), 1, 4, fp) == 4;
    6584          10 :     bOK &= VSIFWriteL(CPLSPrintf("%09d", nDataLen), 1, 9, fp) == 9;
    6585             : 
    6586          10 :     if (nIXSOFLOffset > 0)
    6587             :     {
    6588           1 :         CPLDebug("NITF", "Patching IXSOFL of image %d to %d", iDES + 1,
    6589             :                  nDESITEM);
    6590           1 :         bOK &= VSIFSeekL(fp, nIXSOFLOffset, SEEK_SET) == 0;
    6591           1 :         bOK &= VSIFWriteL(CPLSPrintf("%03d", nDESITEM), 1, 3, fp) == 3;
    6592             :     }
    6593             : 
    6594          10 :     return bOK;
    6595             : }
    6596             : 
    6597             : /************************************************************************/
    6598             : /*                          NITFWriteDESs()                             */
    6599             : /************************************************************************/
    6600             : 
    6601         245 : static bool NITFWriteDES(const char *pszFilename, VSILFILE *&fpVSIL,
    6602             :                          CSLConstList papszOptions)
    6603             : {
    6604         245 :     if (papszOptions == nullptr)
    6605             :     {
    6606          85 :         return true;
    6607             :     }
    6608             : 
    6609         160 :     int nDESFound = 0;
    6610         591 :     for (int iOption = 0; papszOptions[iOption] != nullptr; iOption++)
    6611             :     {
    6612         431 :         if (EQUALN(papszOptions[iOption], "DES=", 4))
    6613             :         {
    6614          12 :             nDESFound++;
    6615             :         }
    6616             :     }
    6617         160 :     if (nDESFound == 0)
    6618             :     {
    6619         149 :         return true;
    6620             :     }
    6621             : 
    6622             :     /* -------------------------------------------------------------------- */
    6623             :     /*      Open the target file if not already done.                       */
    6624             :     /* -------------------------------------------------------------------- */
    6625          11 :     if (fpVSIL == nullptr)
    6626          11 :         fpVSIL = VSIFOpenL(pszFilename, "r+b");
    6627          11 :     if (fpVSIL == nullptr)
    6628           0 :         return false;
    6629             : 
    6630             :     char achNUMI[4];  // 3 digits plus null character
    6631          11 :     achNUMI[3] = '\0';
    6632             :     // NUMI offset is at a fixed offset 363
    6633          11 :     int nNumIOffset = 360;
    6634          11 :     bool bOK = VSIFSeekL(fpVSIL, nNumIOffset, SEEK_SET) == 0;
    6635          11 :     bOK &= VSIFReadL(achNUMI, 3, 1, fpVSIL) == 1;
    6636          11 :     int nIM = atoi(achNUMI);
    6637             : 
    6638             :     char achNUMG[4];  // 3 digits plus null character
    6639          11 :     achNUMG[3] = '\0';
    6640             : 
    6641             :     // 3 for size of NUMI.  6 and 10 are the field size for LISH and LI
    6642          11 :     const int nNumGOffset = nNumIOffset + 3 + nIM * (6 + 10);
    6643          11 :     bOK &= VSIFSeekL(fpVSIL, nNumGOffset, SEEK_SET) == 0;
    6644          11 :     bOK &= VSIFReadL(achNUMG, 3, 1, fpVSIL) == 1;
    6645          11 :     const int nGS = atoi(achNUMG);
    6646             : 
    6647             :     // NUMT offset
    6648             :     // 3 for size of NUMG.  4 and 6 are the field size of LSSH and LS.
    6649             :     // the last + 3 is for NUMX field, which is not used
    6650          11 :     const int nNumTOffset = nNumGOffset + 3 + nGS * (4 + 6) + 3;
    6651             :     char achNUMT[4];
    6652          11 :     bOK &= VSIFSeekL(fpVSIL, nNumTOffset, SEEK_SET) == 0;
    6653          11 :     bOK &= VSIFReadL(achNUMT, 3, 1, fpVSIL) == 1;
    6654          11 :     achNUMT[3] = '\0';
    6655          11 :     const int nNUMT = atoi(achNUMT);
    6656             : 
    6657             :     // NUMDES offset
    6658             :     // 3 for size of NUMT. 4 and 5 are the field size of LTSH and LT.
    6659          11 :     const int nNumDESOffset = nNumTOffset + 3 + (4 + 5) * nNUMT;
    6660             :     char achNUMDES[4];
    6661          11 :     bOK &= VSIFSeekL(fpVSIL, nNumDESOffset, SEEK_SET) == 0;
    6662          11 :     bOK &= VSIFReadL(achNUMDES, 3, 1, fpVSIL) == 1;
    6663          11 :     achNUMDES[3] = '\0';
    6664             : 
    6665          11 :     if (!bOK || atoi(achNUMDES) != nDESFound)
    6666             :     {
    6667           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6668             :                  "It appears an attempt was made to add or update DE\n"
    6669             :                  "segments on an NITF file with existing segments.  This\n"
    6670             :                  "is not currently supported by the GDAL NITF driver.");
    6671           0 :         return false;
    6672             :     }
    6673             : 
    6674          11 :     int iDES = 0;
    6675          31 :     for (int iOption = 0; papszOptions[iOption] != nullptr; iOption++)
    6676             :     {
    6677          22 :         if (!EQUALN(papszOptions[iOption], "DES=", 4))
    6678             :         {
    6679          10 :             continue;
    6680             :         }
    6681             : 
    6682             :         /* We don't use CPLParseNameValue() as it removes leading spaces */
    6683             :         /* from the value (see #3088) */
    6684          12 :         const char *pszDelim = strchr(papszOptions[iOption] + 4, '=');
    6685          12 :         if (pszDelim == nullptr)
    6686             :         {
    6687           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6688             :                      "Could not parse creation options %s",
    6689           0 :                      papszOptions[iOption] + 4);
    6690           2 :             return false;
    6691             :         }
    6692             : 
    6693          12 :         const size_t nNameLength =
    6694          12 :             strlen(papszOptions[iOption] + 4) - strlen(pszDelim);
    6695          12 :         if (nNameLength > 25)
    6696             :         {
    6697           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6698             :                      "Specified DESID is too long %s",
    6699           0 :                      papszOptions[iOption] + 4);
    6700           0 :             return false;
    6701             :         }
    6702             : 
    6703          12 :         char *pszDESName = (char *)CPLMalloc(nNameLength + 1);
    6704          12 :         memcpy(pszDESName, papszOptions[iOption] + 4, nNameLength);
    6705          12 :         pszDESName[nNameLength] = '\0';
    6706             : 
    6707          12 :         const char *pszEscapedContents = pszDelim + 1;
    6708             : 
    6709          12 :         int nContentLength = 0;
    6710          12 :         GByte *pabyUnescapedContents = (GByte *)CPLUnescapeString(
    6711             :             pszEscapedContents, &nContentLength, CPLES_BackslashQuotable);
    6712             : 
    6713          12 :         if (!NITFWriteDES(fpVSIL, pszFilename, nNumDESOffset + 3, iDES,
    6714             :                           pszDESName, pabyUnescapedContents, nContentLength))
    6715             :         {
    6716           2 :             CPLFree(pszDESName);
    6717           2 :             CPLFree(pabyUnescapedContents);
    6718           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Could not write DES %d",
    6719             :                      iDES);
    6720           2 :             return false;
    6721             :         }
    6722             : 
    6723          10 :         CPLFree(pszDESName);
    6724          10 :         CPLFree(pabyUnescapedContents);
    6725             : 
    6726          10 :         iDES++;
    6727             :     }
    6728             : 
    6729           9 :     return bOK;
    6730             : }
    6731             : 
    6732             : /************************************************************************/
    6733             : /*                         UpdateFileLength()                           */
    6734             : /************************************************************************/
    6735             : 
    6736          24 : static bool UpdateFileLength(VSILFILE *fp)
    6737             : {
    6738             : 
    6739             :     /* -------------------------------------------------------------------- */
    6740             :     /*      Update total file length.                                       */
    6741             :     /* -------------------------------------------------------------------- */
    6742          24 :     bool bOK = VSIFSeekL(fp, 0, SEEK_END) == 0;
    6743          24 :     GUIntBig nFileLen = VSIFTellL(fp);
    6744             :     // Offset to file length entry
    6745          24 :     bOK &= VSIFSeekL(fp, 342, SEEK_SET) == 0;
    6746          24 :     if (nFileLen >= NITF_MAX_FILE_SIZE)
    6747             :     {
    6748           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6749             :                  "Too big file : " CPL_FRMT_GUIB
    6750             :                  ". Truncating to " CPL_FRMT_GUIB,
    6751             :                  nFileLen, NITF_MAX_FILE_SIZE - 1);
    6752           0 :         nFileLen = NITF_MAX_FILE_SIZE - 1;
    6753             :     }
    6754             :     CPLString osLen =
    6755          24 :         CPLString().Printf("%012" CPL_FRMT_GB_WITHOUT_PREFIX "u", nFileLen);
    6756          24 :     bOK &= VSIFWriteL(reinterpret_cast<const void *>(osLen.c_str()), 12, 1,
    6757          24 :                       fp) == 1;
    6758          48 :     return bOK;
    6759             : }
    6760             : 
    6761             : /************************************************************************/
    6762             : /*                       NITFWriteExtraSegments()                       */
    6763             : /************************************************************************/
    6764             : 
    6765         245 : static bool NITFWriteExtraSegments(const char *pszFilename,
    6766             :                                    CSLConstList papszCgmMD,
    6767             :                                    CSLConstList papszTextMD,
    6768             :                                    CSLConstList papszOptions)
    6769             : {
    6770         245 :     VSILFILE *fp = nullptr;
    6771         245 :     bool bOK = NITFWriteCGMSegments(pszFilename, fp, papszCgmMD);
    6772         245 :     bOK &= NITFWriteTextSegments(pszFilename, fp, papszTextMD);
    6773         245 :     bOK &= NITFWriteDES(pszFilename, fp, papszOptions);
    6774         245 :     if (fp)
    6775             :     {
    6776          24 :         bOK &= UpdateFileLength(fp);
    6777             : 
    6778          24 :         if (VSIFCloseL(fp) != 0)
    6779           0 :             bOK = false;
    6780             : 
    6781          24 :         if (!bOK)
    6782             :         {
    6783           2 :             CPLError(CE_Failure, CPLE_FileIO, "I/O error");
    6784             :         }
    6785             :     }
    6786         245 :     return bOK;
    6787             : }
    6788             : 
    6789             : /************************************************************************/
    6790             : /*                         NITFWriteJPEGImage()                         */
    6791             : /************************************************************************/
    6792             : 
    6793             : #ifdef JPEG_SUPPORTED
    6794             : 
    6795             : int NITFWriteJPEGBlock(GDALDataset *poSrcDS, VSILFILE *fp, int nBlockXOff,
    6796             :                        int nBlockYOff, int nBlockXSize, int nBlockYSize,
    6797             :                        int bProgressive, int nQuality, const GByte *pabyAPP6,
    6798             :                        int nRestartInterval, GDALProgressFunc pfnProgress,
    6799             :                        void *pProgressData);
    6800             : 
    6801          10 : static bool NITFWriteJPEGImage(GDALDataset *poSrcDS, VSILFILE *fp,
    6802             :                                vsi_l_offset nStartOffset, char **papszOptions,
    6803             :                                GDALProgressFunc pfnProgress,
    6804             :                                void *pProgressData)
    6805             : {
    6806          10 :     if (!pfnProgress(0.0, nullptr, pProgressData))
    6807           0 :         return false;
    6808             : 
    6809             :     /* -------------------------------------------------------------------- */
    6810             :     /*      Some some rudimentary checks                                    */
    6811             :     /* -------------------------------------------------------------------- */
    6812          10 :     const int nBands = poSrcDS->GetRasterCount();
    6813          10 :     if (nBands != 1 && nBands != 3)
    6814             :     {
    6815           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    6816             :                  "JPEG driver doesn't support %d bands.  Must be 1 (grey) "
    6817             :                  "or 3 (RGB) bands.\n",
    6818             :                  nBands);
    6819             : 
    6820           0 :         return false;
    6821             :     }
    6822             : 
    6823          10 :     GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6824             : 
    6825             : #if defined(JPEG_LIB_MK1) || defined(JPEG_DUAL_MODE_8_12)
    6826          10 :     if (eDT != GDT_Byte && eDT != GDT_UInt16)
    6827             :     {
    6828           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    6829             :                  "JPEG driver doesn't support data type %s. "
    6830             :                  "Only eight and twelve bit bands supported (Mk1 libjpeg).\n",
    6831             :                  GDALGetDataTypeName(
    6832             :                      poSrcDS->GetRasterBand(1)->GetRasterDataType()));
    6833             : 
    6834           0 :         return false;
    6835             :     }
    6836             : 
    6837          10 :     if (eDT == GDT_UInt16 || eDT == GDT_Int16)
    6838           2 :         eDT = GDT_UInt16;
    6839             :     else
    6840           8 :         eDT = GDT_Byte;
    6841             : 
    6842             : #else
    6843             :     if (eDT != GDT_Byte)
    6844             :     {
    6845             :         CPLError(CE_Failure, CPLE_NotSupported,
    6846             :                  "JPEG driver doesn't support data type %s. "
    6847             :                  "Only eight bit byte bands supported.\n",
    6848             :                  GDALGetDataTypeName(
    6849             :                      poSrcDS->GetRasterBand(1)->GetRasterDataType()));
    6850             : 
    6851             :         return false;
    6852             :     }
    6853             : 
    6854             :     eDT = GDT_Byte;  // force to 8bit.
    6855             : #endif
    6856             : 
    6857             :     /* -------------------------------------------------------------------- */
    6858             :     /*      What options has the user selected?                             */
    6859             :     /* -------------------------------------------------------------------- */
    6860          10 :     int nQuality = 75;
    6861          10 :     if (CSLFetchNameValue(papszOptions, "QUALITY") != nullptr)
    6862             :     {
    6863           2 :         nQuality = atoi(CSLFetchNameValue(papszOptions, "QUALITY"));
    6864           2 :         if (nQuality < 10 || nQuality > 100)
    6865             :         {
    6866           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    6867             :                      "QUALITY=%s is not a legal value in the range 10-100.",
    6868             :                      CSLFetchNameValue(papszOptions, "QUALITY"));
    6869           0 :             return false;
    6870             :         }
    6871             :     }
    6872             : 
    6873          10 :     int nRestartInterval = -1;
    6874          10 :     if (CSLFetchNameValue(papszOptions, "RESTART_INTERVAL") != nullptr)
    6875             :     {
    6876             :         nRestartInterval =
    6877           0 :             atoi(CSLFetchNameValue(papszOptions, "RESTART_INTERVAL"));
    6878             :     }
    6879             : 
    6880          10 :     const bool bProgressive = CPLFetchBool(papszOptions, "PROGRESSIVE", false);
    6881             : 
    6882             :     /* -------------------------------------------------------------------- */
    6883             :     /*      Compute blocking factors                                        */
    6884             :     /* -------------------------------------------------------------------- */
    6885          10 :     const int nXSize = poSrcDS->GetRasterXSize();
    6886          10 :     const int nYSize = poSrcDS->GetRasterYSize();
    6887          10 :     int nNPPBH = nXSize;
    6888          10 :     int nNPPBV = nYSize;
    6889             : 
    6890          10 :     if (CSLFetchNameValue(papszOptions, "BLOCKXSIZE") != nullptr)
    6891           3 :         nNPPBH = atoi(CSLFetchNameValue(papszOptions, "BLOCKXSIZE"));
    6892             : 
    6893          10 :     if (CSLFetchNameValue(papszOptions, "BLOCKYSIZE") != nullptr)
    6894           3 :         nNPPBV = atoi(CSLFetchNameValue(papszOptions, "BLOCKYSIZE"));
    6895             : 
    6896          10 :     if (CSLFetchNameValue(papszOptions, "NPPBH") != nullptr)
    6897           0 :         nNPPBH = atoi(CSLFetchNameValue(papszOptions, "NPPBH"));
    6898             : 
    6899          10 :     if (CSLFetchNameValue(papszOptions, "NPPBV") != nullptr)
    6900           0 :         nNPPBV = atoi(CSLFetchNameValue(papszOptions, "NPPBV"));
    6901             : 
    6902          10 :     if (nNPPBH <= 0 || nNPPBV <= 0 || nNPPBH > 9999 || nNPPBV > 9999)
    6903             :     {
    6904           1 :         nNPPBH = 256;
    6905           1 :         nNPPBV = 256;
    6906             :     }
    6907             : 
    6908          10 :     const int nNBPR = (nXSize + nNPPBH - 1) / nNPPBH;
    6909          10 :     const int nNBPC = (nYSize + nNPPBV - 1) / nNPPBV;
    6910             : 
    6911             :     /* -------------------------------------------------------------------- */
    6912             :     /*  Creates APP6 NITF application segment (required by MIL-STD-188-198) */
    6913             :     /*  see #3345                                                           */
    6914             :     /* -------------------------------------------------------------------- */
    6915             :     GByte abyAPP6[23];
    6916          10 :     memcpy(abyAPP6, "NITF", 4);
    6917          10 :     abyAPP6[4] = 0;
    6918          10 :     int nOffset = 5;
    6919             : 
    6920             :     /* Version : 2.0 */
    6921          10 :     GUInt16 nUInt16 = 0x0200;
    6922          10 :     CPL_MSBPTR16(&nUInt16);
    6923          10 :     memcpy(abyAPP6 + nOffset, &nUInt16, sizeof(nUInt16));
    6924          10 :     nOffset += sizeof(nUInt16);
    6925             : 
    6926             :     /* IMODE */
    6927          10 :     abyAPP6[nOffset] = (nBands == 1) ? 'B' : 'P';
    6928          10 :     nOffset++;
    6929             : 
    6930             :     /* Number of image blocks per row */
    6931          10 :     nUInt16 = (GUInt16)nNBPR;
    6932          10 :     CPL_MSBPTR16(&nUInt16);
    6933          10 :     memcpy(abyAPP6 + nOffset, &nUInt16, sizeof(nUInt16));
    6934          10 :     nOffset += sizeof(nUInt16);
    6935             : 
    6936             :     /* Number of image blocks per column */
    6937          10 :     nUInt16 = (GUInt16)nNBPC;
    6938          10 :     CPL_MSBPTR16(&nUInt16);
    6939          10 :     memcpy(abyAPP6 + nOffset, &nUInt16, sizeof(nUInt16));
    6940          10 :     nOffset += sizeof(nUInt16);
    6941             : 
    6942             :     /* Image color */
    6943          10 :     abyAPP6[nOffset] = (nBands == 1) ? 0 : 1;
    6944          10 :     nOffset++;
    6945             : 
    6946             :     /* Original sample precision */
    6947             :     /* coverity[dead_error_line] */
    6948          10 :     abyAPP6[nOffset] = (eDT == GDT_UInt16) ? 12 : 8;
    6949          10 :     nOffset++;
    6950             : 
    6951             :     /* Image class */
    6952          10 :     abyAPP6[nOffset] = 0;
    6953          10 :     nOffset++;
    6954             : 
    6955             :     /* JPEG coding process */
    6956             :     /* coverity[dead_error_line] */
    6957          10 :     abyAPP6[nOffset] = (eDT == GDT_UInt16) ? 4 : 1;
    6958          10 :     nOffset++;
    6959             : 
    6960             :     /* Quality */
    6961          10 :     abyAPP6[nOffset] = 0;
    6962          10 :     nOffset++;
    6963             : 
    6964             :     /* Stream color */
    6965          10 :     abyAPP6[nOffset] = (nBands == 1) ? 0 /* Monochrome */ : 2 /* YCbCr*/;
    6966          10 :     nOffset++;
    6967             : 
    6968             :     /* Stream bits */
    6969             :     /* coverity[dead_error_line] */
    6970          10 :     abyAPP6[nOffset] = (eDT == GDT_UInt16) ? 12 : 8;
    6971          10 :     nOffset++;
    6972             : 
    6973             :     /* Horizontal filtering */
    6974          10 :     abyAPP6[nOffset] = 1;
    6975          10 :     nOffset++;
    6976             : 
    6977             :     /* Vertical filtering */
    6978          10 :     abyAPP6[nOffset] = 1;
    6979          10 :     nOffset++;
    6980             : 
    6981             :     /* Reserved */
    6982          10 :     abyAPP6[nOffset] = 0;
    6983          10 :     nOffset++;
    6984          10 :     abyAPP6[nOffset] = 0;
    6985          10 :     nOffset++;
    6986             :     (void)nOffset;
    6987             : 
    6988          10 :     CPLAssert(nOffset == sizeof(abyAPP6));
    6989             : 
    6990             :     /* -------------------------------------------------------------------- */
    6991             :     /*      Prepare block map if necessary                                  */
    6992             :     /* -------------------------------------------------------------------- */
    6993             : 
    6994          10 :     bool bOK = VSIFSeekL(fp, nStartOffset, SEEK_SET) == 0;
    6995             : 
    6996          10 :     const char *pszIC = CSLFetchNameValue(papszOptions, "IC");
    6997          10 :     GUInt32 nIMDATOFF = 0;
    6998          10 :     constexpr GUInt32 BLOCKMAP_HEADER_SIZE = 4 + 2 + 2 + 2;
    6999          10 :     if (EQUAL(pszIC, "M3"))
    7000             :     {
    7001             :         /* Prepare the block map */
    7002           1 :         GUInt32 nIMDATOFF_MSB = BLOCKMAP_HEADER_SIZE + nNBPC * nNBPR * 4;
    7003           1 :         nIMDATOFF = nIMDATOFF_MSB;
    7004           1 :         GUInt16 nBMRLNTH = 4;
    7005           1 :         GUInt16 nTMRLNTH = 0;
    7006           1 :         GUInt16 nTPXCDLNTH = 0;
    7007             : 
    7008           1 :         CPL_MSBPTR32(&nIMDATOFF_MSB);
    7009           1 :         CPL_MSBPTR16(&nBMRLNTH);
    7010           1 :         CPL_MSBPTR16(&nTMRLNTH);
    7011           1 :         CPL_MSBPTR16(&nTPXCDLNTH);
    7012             : 
    7013           1 :         bOK &= VSIFWriteL(&nIMDATOFF_MSB, 4, 1, fp) == 1;
    7014           1 :         bOK &= VSIFWriteL(&nBMRLNTH, 2, 1, fp) == 1;
    7015           1 :         bOK &= VSIFWriteL(&nTMRLNTH, 2, 1, fp) == 1;
    7016           1 :         bOK &= VSIFWriteL(&nTPXCDLNTH, 2, 1, fp) == 1;
    7017             : 
    7018             :         /* Reserve space for the table itself */
    7019           1 :         bOK &= VSIFSeekL(fp, static_cast<vsi_l_offset>(nNBPC) * nNBPR * 4,
    7020           1 :                          SEEK_CUR) == 0;
    7021             :     }
    7022             : 
    7023             :     /* -------------------------------------------------------------------- */
    7024             :     /*      Copy each block                                                 */
    7025             :     /* -------------------------------------------------------------------- */
    7026          22 :     for (int nBlockYOff = 0; bOK && nBlockYOff < nNBPC; nBlockYOff++)
    7027             :     {
    7028          67 :         for (int nBlockXOff = 0; bOK && nBlockXOff < nNBPR; nBlockXOff++)
    7029             :         {
    7030             : #ifdef DEBUG_VERBOSE
    7031             :             CPLDebug("NITF", "nBlockXOff=%d/%d, nBlockYOff=%d/%d", nBlockXOff,
    7032             :                      nNBPR, nBlockYOff, nNBPC);
    7033             : #endif
    7034          55 :             if (EQUAL(pszIC, "M3"))
    7035             :             {
    7036             :                 /* Write block offset for current block */
    7037             : 
    7038           4 :                 const GUIntBig nCurPos = VSIFTellL(fp);
    7039           8 :                 bOK &= VSIFSeekL(fp,
    7040           4 :                                  nStartOffset + BLOCKMAP_HEADER_SIZE +
    7041           4 :                                      4 * (nBlockYOff * nNBPR + nBlockXOff),
    7042           4 :                                  SEEK_SET) == 0;
    7043           4 :                 const GUIntBig nBlockOffset =
    7044           4 :                     nCurPos - nStartOffset - nIMDATOFF;
    7045           4 :                 if (nBlockOffset <= UINT_MAX)
    7046             :                 {
    7047           4 :                     GUInt32 nBlockOffset32 = (GUInt32)nBlockOffset;
    7048           4 :                     CPL_MSBPTR32(&nBlockOffset32);
    7049           4 :                     bOK &= VSIFWriteL(&nBlockOffset32, 4, 1, fp) == 1;
    7050             :                 }
    7051             :                 else
    7052             :                 {
    7053           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    7054             :                              "Offset for block (%d, %d) = " CPL_FRMT_GUIB
    7055             :                              ". Cannot fit into 32 bits...",
    7056             :                              nBlockXOff, nBlockYOff, nBlockOffset);
    7057             : 
    7058           0 :                     GUInt32 nBlockOffset32 = UINT_MAX;
    7059           0 :                     for (int i = nBlockYOff * nNBPR + nBlockXOff;
    7060           0 :                          bOK && i < nNBPC * nNBPR; i++)
    7061             :                     {
    7062           0 :                         bOK &= VSIFWriteL(&nBlockOffset32, 4, 1, fp) == 1;
    7063             :                     }
    7064           0 :                     if (!bOK)
    7065             :                     {
    7066           0 :                         CPLError(CE_Failure, CPLE_FileIO, "I/O error");
    7067             :                     }
    7068           0 :                     return bOK;
    7069             :                 }
    7070           4 :                 bOK &= VSIFSeekL(fp, nCurPos, SEEK_SET) == 0;
    7071             :             }
    7072             : 
    7073         110 :             if (bOK &&
    7074          67 :                 !NITFWriteJPEGBlock(
    7075             :                     poSrcDS, fp, nBlockXOff, nBlockYOff, nNPPBH, nNPPBV,
    7076             :                     bProgressive, nQuality,
    7077          12 :                     (nBlockXOff == 0 && nBlockYOff == 0) ? abyAPP6 : nullptr,
    7078             :                     nRestartInterval, pfnProgress, pProgressData))
    7079             :             {
    7080           0 :                 return false;
    7081             :             }
    7082             :         }
    7083             :     }
    7084          10 :     if (!bOK)
    7085             :     {
    7086           0 :         CPLError(CE_Failure, CPLE_FileIO, "I/O error");
    7087             :     }
    7088          10 :     return true;
    7089             : }
    7090             : 
    7091             : #endif /* def JPEG_SUPPORTED */
    7092             : 
    7093             : /************************************************************************/
    7094             : /*                          GDALRegister_NITF()                         */
    7095             : /************************************************************************/
    7096             : 
    7097             : typedef struct
    7098             : {
    7099             :     int nMaxLen;
    7100             :     const char *pszName;
    7101             :     const char *pszDescription;
    7102             : } NITFFieldDescription;
    7103             : 
    7104             : /* Keep in sync with NITFCreate */
    7105             : static const NITFFieldDescription asFieldDescription[] = {
    7106             :     {2, "CLEVEL", "Complexity level"},
    7107             :     {10, "OSTAID", "Originating Station ID"},
    7108             :     {14, "FDT", "File Date and Time"},
    7109             :     {80, "FTITLE", "File Title"},
    7110             :     {1, "FSCLAS", "File Security Classification"},
    7111             :     {2, "FSCLSY", "File Classification Security System"},
    7112             :     {11, "FSCODE", "File Codewords"},
    7113             :     {2, "FSCTLH", "File Control and Handling"},
    7114             :     {20, "FSREL", "File Releasing Instructions"},
    7115             :     {2, "FSDCTP", "File Declassification Type"},
    7116             :     {8, "FSDCDT", "File Declassification Date"},
    7117             :     {4, "FSDCXM", "File Declassification Exemption"},
    7118             :     {1, "FSDG", "File Downgrade"},
    7119             :     {8, "FSDGDT", "File Downgrade Date"},
    7120             :     {43, "FSCLTX", "File Classification Text"},
    7121             :     {1, "FSCATP", "File Classification Authority Type"},
    7122             :     {40, "FSCAUT", "File Classification Authority"},
    7123             :     {1, "FSCRSN", "File Classification Reason"},
    7124             :     {8, "FSSRDT", "File Security Source Date"},
    7125             :     {15, "FSCTLN", "File Security Control Number"},
    7126             :     {5, "FSCOP", "File Copy Number"},
    7127             :     {5, "FSCPYS", "File Number of Copies"},
    7128             :     {24, "ONAME", "Originator Name"},
    7129             :     {18, "OPHONE", "Originator Phone Number"},
    7130             :     {10, "IID1", "Image Identifier 1"},
    7131             :     {14, "IDATIM", "Image Date and Time"},
    7132             :     {17, "TGTID", "Target Identifier"},
    7133             :     {80, "IID2", "Image Identifier 2"},
    7134             :     {1, "ISCLAS", "Image Security Classification"},
    7135             :     {2, "ISCLSY", "Image Classification Security System"},
    7136             :     {11, "ISCODE", "Image Codewords"},
    7137             :     {2, "ISCTLH", "Image Control and Handling"},
    7138             :     {20, "ISREL", "Image Releasing Instructions"},
    7139             :     {2, "ISDCTP", "Image Declassification Type"},
    7140             :     {8, "ISDCDT", "Image Declassification Date"},
    7141             :     {4, "ISDCXM", "Image Declassification Exemption"},
    7142             :     {1, "ISDG", "Image Downgrade"},
    7143             :     {8, "ISDGDT", "Image Downgrade Date"},
    7144             :     {43, "ISCLTX", "Image Classification Text"},
    7145             :     {1, "ISCATP", "Image Classification Authority Type"},
    7146             :     {40, "ISCAUT", "Image Classification Authority"},
    7147             :     {1, "ISCRSN", "Image Classification Reason"},
    7148             :     {8, "ISSRDT", "Image Security Source Date"},
    7149             :     {15, "ISCTLN", "Image Security Control Number"},
    7150             :     {42, "ISORCE", "Image Source"},
    7151             :     {8, "ICAT", "Image Category"},
    7152             :     {2, "ABPP", "Actual Bits-Per-Pixel Per Band"},
    7153             :     {1, "PJUST", "Pixel Justification"},
    7154             :     {720, "ICOM", "Image Comments (up to 9x80 characters)"},
    7155             :     {3, "IDLVL", "Image Display Level"},
    7156             :     {3, "IALVL", "Image Attachment Level"},
    7157             :     {5, "ILOCROW", "Image Location Row"},
    7158             :     {5, "ILOCCOL", "Image Location Column"},
    7159             : };
    7160             : 
    7161             : /* Keep in sync with NITFWriteBLOCKA */
    7162             : static const char *const apszFieldsBLOCKA[] = {
    7163             :     "BLOCK_INSTANCE", "0",     "2",    "N_GRAY",        "2",  "5",
    7164             :     "L_LINES",        "7",     "5",    "LAYOVER_ANGLE", "12", "3",
    7165             :     "SHADOW_ANGLE",   "15",    "3",    "BLANKS",        "18", "16",
    7166             :     "FRLC_LOC",       "34",    "21",   "LRLC_LOC",      "55", "21",
    7167             :     "LRFC_LOC",       "76",    "21",   "FRFC_LOC",      "97", "21",
    7168             :     nullptr,          nullptr, nullptr};
    7169             : 
    7170             : /************************************************************************/
    7171             : /*                              NITFDriver                              */
    7172             : /************************************************************************/
    7173             : 
    7174             : class NITFDriver final : public GDALDriver
    7175             : {
    7176             :     bool m_bCreationOptionListInitialized = false;
    7177             :     void InitCreationOptionList();
    7178             : 
    7179             :   public:
    7180       64155 :     const char *GetMetadataItem(const char *pszName,
    7181             :                                 const char *pszDomain) override
    7182             :     {
    7183       64155 :         if (EQUAL(pszName, GDAL_DMD_CREATIONOPTIONLIST))
    7184             :         {
    7185         307 :             InitCreationOptionList();
    7186             :         }
    7187       64155 :         return GDALDriver::GetMetadataItem(pszName, pszDomain);
    7188             :     }
    7189             : 
    7190          28 :     char **GetMetadata(const char *pszDomain) override
    7191             :     {
    7192          28 :         InitCreationOptionList();
    7193          28 :         return GDALDriver::GetMetadata(pszDomain);
    7194             :     }
    7195             : };
    7196             : 
    7197             : /************************************************************************/
    7198             : /*                         InitCreationOptionList()                     */
    7199             : /************************************************************************/
    7200             : 
    7201         335 : void NITFDriver::InitCreationOptionList()
    7202             : {
    7203         335 :     if (m_bCreationOptionListInitialized)
    7204         326 :         return;
    7205           9 :     m_bCreationOptionListInitialized = true;
    7206             : 
    7207           9 :     const bool bHasJP2ECW = GDALGetDriverByName("JP2ECW") != nullptr;
    7208           9 :     const bool bHasJP2KAK = GDALGetDriverByName("JP2KAK") != nullptr;
    7209           9 :     const bool bHasJP2OPENJPEG = GDALGetDriverByName("JP2OPENJPEG") != nullptr;
    7210           9 :     const bool bHasJPEG2000Drivers =
    7211           9 :         bHasJP2ECW || bHasJP2KAK || bHasJP2OPENJPEG;
    7212             : 
    7213             :     CPLString osCreationOptions =
    7214             :         "<CreationOptionList>"
    7215             :         "   <Option name='IC' type='string-select' default='NC' "
    7216             :         "description='Compression mode. NC=no compression. "
    7217             : #ifdef JPEG_SUPPORTED
    7218          18 :         "C3/M3=JPEG compression. "
    7219             : #endif
    7220             :         ;
    7221             : 
    7222           9 :     if (bHasJPEG2000Drivers)
    7223             :         osCreationOptions +=
    7224           9 :             "C8=JP2 compression through the JPEG2000 write capable drivers";
    7225             : 
    7226             :     osCreationOptions += "'>"
    7227             :                          "       <Value>NC</Value>"
    7228             : #ifdef JPEG_SUPPORTED
    7229             :                          "       <Value>C3</Value>"
    7230           9 :                          "       <Value>M3</Value>"
    7231             : #endif
    7232             :         ;
    7233             : 
    7234           9 :     if (bHasJPEG2000Drivers)
    7235           9 :         osCreationOptions += "       <Value>C8</Value>";
    7236             : 
    7237           9 :     osCreationOptions += "   </Option>";
    7238             : 
    7239             : #if !defined(JPEG_SUPPORTED)
    7240             :     if (bHasJPEG2000Drivers)
    7241             : #endif
    7242             :     {
    7243             :         osCreationOptions +=
    7244             :             "   <Option name='QUALITY' type='string' "
    7245             :             "description='JPEG (10-100) or JPEG2000 quality, possibly as a"
    7246             :             "separated list of values for JPEG2000_DRIVER=JP2OPENJPEG' "
    7247           9 :             "default='75'/>";
    7248             :     }
    7249             : 
    7250             : #ifdef JPEG_SUPPORTED
    7251             :     osCreationOptions +=
    7252             :         "   <Option name='PROGRESSIVE' type='boolean' description='JPEG "
    7253             :         "progressive mode'/>"
    7254             :         "   <Option name='RESTART_INTERVAL' type='int' description='Restart "
    7255             :         "interval (in MCUs). -1 for auto, 0 for none, > 0 for user specified' "
    7256             :         "default='-1'/>"
    7257             : #endif
    7258             :         "   <Option name='NUMI' type='int' default='1' description='Number of "
    7259             :         "images to create (1-999). Only works with IC=NC if "
    7260             :         "WRITE_ONLY_FIRST_IMAGE=NO'/>"
    7261             :         "   <Option name='WRITE_ONLY_FIRST_IMAGE' type='boolean' default='NO' "
    7262             :         "description='To be used with NUMI. If YES, only write first image. "
    7263           9 :         "Subsequent one must be written with APPEND_SUBDATASET=YES'/>";
    7264             : 
    7265           9 :     if (bHasJPEG2000Drivers)
    7266             :     {
    7267             :         osCreationOptions +=
    7268             :             "   <Option name='TARGET' type='float' description='For JP2 only. "
    7269             :             "Compression Percentage'/>"
    7270             :             "   <Option name='PROFILE' type='string-select' description='For "
    7271           9 :             "JP2 only.'>";
    7272             : 
    7273           9 :         if (bHasJP2ECW)
    7274             :         {
    7275           9 :             osCreationOptions += "       <Value>BASELINE_0</Value>";
    7276             :         }
    7277           9 :         if (bHasJP2ECW || bHasJP2OPENJPEG)
    7278             :         {
    7279             :             osCreationOptions +=
    7280             :                 "       <Value>BASELINE_1</Value>"
    7281             :                 "       <Value>BASELINE_2</Value>"
    7282             :                 "       <Value>NPJE</Value>"
    7283             :                 "       <Value>NPJE_VISUALLY_LOSSLESS</Value>"
    7284           9 :                 "       <Value>NPJE_NUMERICALLY_LOSSLESS</Value>";
    7285             :         }
    7286           9 :         if (bHasJP2ECW)
    7287             :         {
    7288           9 :             osCreationOptions += "       <Value>EPJE</Value>";
    7289             :         }
    7290             :         osCreationOptions +=
    7291             :             "   </Option>"
    7292             :             "   <Option name='JPEG2000_DRIVER' type='string-select' "
    7293           9 :             "description='Short name of the JPEG2000 driver'>";
    7294           9 :         if (bHasJP2OPENJPEG)
    7295           9 :             osCreationOptions += "       <Value>JP2OPENJPEG</Value>";
    7296           9 :         if (bHasJP2ECW)
    7297           9 :             osCreationOptions += "       <Value>JP2ECW</Value>";
    7298           9 :         if (bHasJP2KAK)
    7299           0 :             osCreationOptions += "       <Value>JP2KAK</Value>";
    7300             :         osCreationOptions += "   </Option>"
    7301             :                              "   <Option name='J2KLRA' type='boolean' "
    7302           9 :                              "description='Write J2KLRA TRE'/>";
    7303             :     }
    7304             : 
    7305             :     osCreationOptions +=
    7306             :         "   <Option name='ICORDS' type='string-select' description='To ensure "
    7307             :         "that space will be reserved for geographic corner coordinates in DMS "
    7308             :         "(G), in decimal degrees (D), UTM North (N) or UTM South (S)'>"
    7309             :         "       <Value>G</Value>"
    7310             :         "       <Value>D</Value>"
    7311             :         "       <Value>N</Value>"
    7312             :         "       <Value>S</Value>"
    7313             :         "   </Option>"
    7314             :         "   <Option name='IGEOLO' type='string' description='Image corner "
    7315             :         "coordinates. "
    7316             :         "Normally automatically set. If specified, ICORDS must also be "
    7317             :         "specified'/>"
    7318             :         "   <Option name='FHDR' type='string-select' description='File "
    7319             :         "version' default='NITF02.10'>"
    7320             :         "       <Value>NITF02.10</Value>"
    7321             :         "       <Value>NSIF01.00</Value>"
    7322             :         "   </Option>"
    7323             :         "   <Option name='IREP' type='string' description='Set to RGB/LUT to "
    7324             :         "reserve space for a color table for each output band. (Only needed "
    7325             :         "for Create() method, not CreateCopy())'/>"
    7326             :         "   <Option name='IREPBAND' type='string' description='Comma separated "
    7327             :         "list of band IREPBANDs in band order'/>"
    7328             :         "   <Option name='ISUBCAT' type='string' description='Comma separated "
    7329             :         "list of band ISUBCATs in band order'/>"
    7330             :         "   <Option name='LUT_SIZE' type='integer' description='Set to control "
    7331             :         "the size of pseudocolor tables for RGB/LUT bands' default='256'/>"
    7332             :         "   <Option name='BLOCKXSIZE' type='int' description='Set the block "
    7333             :         "width'/>"
    7334             :         "   <Option name='BLOCKYSIZE' type='int' description='Set the block "
    7335             :         "height'/>"
    7336             :         "   <Option name='BLOCKSIZE' type='int' description='Set the block "
    7337             :         "with and height. Overridden by BLOCKXSIZE and BLOCKYSIZE'/>"
    7338             :         "   <Option name='TEXT' type='string' description='TEXT options as "
    7339             :         "text-option-name=text-option-content'/>"
    7340             :         "   <Option name='CGM' type='string' description='CGM options in "
    7341           9 :         "cgm-option-name=cgm-option-content'/>";
    7342             : 
    7343         486 :     for (unsigned int i = 0;
    7344         486 :          i < sizeof(asFieldDescription) / sizeof(asFieldDescription[0]); i++)
    7345             :     {
    7346         477 :         if (EQUAL(asFieldDescription[i].pszName, "ABPP"))
    7347             :         {
    7348             :             osCreationOptions +=
    7349          18 :                 CPLString().Printf("   <Option name='%s' alias='NBITS' "
    7350             :                                    "type='string' description='%s' "
    7351             :                                    "maxsize='%d'/>",
    7352           9 :                                    asFieldDescription[i].pszName,
    7353           9 :                                    asFieldDescription[i].pszDescription,
    7354           9 :                                    asFieldDescription[i].nMaxLen);
    7355             :         }
    7356             :         else
    7357             :         {
    7358         936 :             osCreationOptions += CPLString().Printf(
    7359             :                 "   <Option name='%s' type='string' description='%s' "
    7360             :                 "maxsize='%d'/>",
    7361         468 :                 asFieldDescription[i].pszName,
    7362         468 :                 asFieldDescription[i].pszDescription,
    7363         468 :                 asFieldDescription[i].nMaxLen);
    7364             :         }
    7365             :     }
    7366             : 
    7367             :     osCreationOptions +=
    7368             :         "   <Option name='TRE' type='string' description='Under the format "
    7369             :         "TRE=tre-name,tre-contents'/>"
    7370             :         "   <Option name='FILE_TRE' type='string' description='Under the "
    7371             :         "format FILE_TRE=tre-name,tre-contents'/>"
    7372             :         "   <Option name='RESERVE_SPACE_FOR_TRE_OVERFLOW' type='boolean' "
    7373             :         "description='Set to true to reserve space for IXSOFL when writing a "
    7374             :         "TRE_OVERFLOW DES'/>"
    7375             :         "   <Option name='BLOCKA_BLOCK_COUNT' type='int'/>"
    7376             :         "   <Option name='DES' type='string' description='Under the format "
    7377             :         "DES=des-name=des-contents'/>"
    7378             :         "   <Option name='NUMDES' type='int' default='0' description='Number "
    7379           9 :         "of DES segments. Only to be used on first image segment'/>";
    7380          99 :     for (unsigned int i = 0; apszFieldsBLOCKA[i] != nullptr; i += 3)
    7381             :     {
    7382             :         char szFieldDescription[128];
    7383          90 :         snprintf(szFieldDescription, sizeof(szFieldDescription),
    7384             :                  "   <Option name='BLOCKA_%s_*' type='string' maxsize='%d'/>",
    7385          90 :                  apszFieldsBLOCKA[i], atoi(apszFieldsBLOCKA[i + 2]));
    7386          90 :         osCreationOptions += szFieldDescription;
    7387             :     }
    7388             :     osCreationOptions +=
    7389             :         "   <Option name='SDE_TRE' type='boolean' description='Write GEOLOB "
    7390             :         "and GEOPSB TREs (only geographic SRS for now)' default='NO'/>"
    7391             :         "   <Option name='RPC00B' type='boolean' description='Write RPC00B TRE "
    7392             :         "(either from source TRE, or from RPC metadata)' default='YES'/>"
    7393             :         "   <Option name='RPCTXT' type='boolean' description='Write out "
    7394             :         "_RPC.TXT file' default='NO'/>"
    7395             :         "   <Option name='USE_SRC_NITF_METADATA' type='boolean' "
    7396             :         "description='Whether to use NITF source metadata in NITF-to-NITF "
    7397           9 :         "conversions' default='YES'/>";
    7398           9 :     osCreationOptions += "</CreationOptionList>";
    7399             : 
    7400           9 :     SetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST, osCreationOptions);
    7401             : }
    7402             : 
    7403        1595 : void GDALRegister_NITF()
    7404             : 
    7405             : {
    7406        1595 :     if (GDALGetDriverByName(NITF_DRIVER_NAME) != nullptr)
    7407         302 :         return;
    7408             : 
    7409        1293 :     GDALDriver *poDriver = new NITFDriver();
    7410        1293 :     NITFDriverSetCommonMetadata(poDriver);
    7411             : 
    7412        1293 :     poDriver->pfnOpen = NITFDataset::Open;
    7413        1293 :     poDriver->pfnCreate = NITFDataset::NITFDatasetCreate;
    7414        1293 :     poDriver->pfnCreateCopy = NITFDataset::NITFCreateCopy;
    7415             : 
    7416        1293 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    7417             : 
    7418             : #ifdef NITF_PLUGIN
    7419             :     GDALRegister_RPFTOC();
    7420             :     GDALRegister_ECRGTOC();
    7421             : #endif
    7422             : }

Generated by: LCOV version 1.14