LCOV - code coverage report
Current view: top level - frmts/nitf - nitfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2428 3010 80.7 %
Date: 2025-10-22 21:46:17 Functions: 57 58 98.3 %

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

Generated by: LCOV version 1.14