LCOV - code coverage report
Current view: top level - frmts/nitf - nitfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2532 3091 81.9 %
Date: 2026-03-05 10:33:42 Functions: 58 60 96.7 %

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

Generated by: LCOV version 1.14