LCOV - code coverage report
Current view: top level - frmts/grib - gribdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1222 1431 85.4 %
Date: 2025-02-20 10:14:44 Functions: 59 63 93.7 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GRIB Driver
       4             :  * Purpose:  GDALDataset driver for GRIB translator for read support
       5             :  * Author:   Bas Retsios, retsios@itc.nl
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2007, ITC
       9             :  * Copyright (c) 2008-2017, Even Rouault <even dot rouault at spatialys dot com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ******************************************************************************
      13             :  *
      14             :  */
      15             : 
      16             : #include "cpl_port.h"
      17             : #include "gribdataset.h"
      18             : #include "gribdrivercore.h"
      19             : 
      20             : #include <cerrno>
      21             : #include <cmath>
      22             : #include <cstddef>
      23             : #include <cstdio>
      24             : #include <cstdlib>
      25             : #include <cstring>
      26             : #if HAVE_FCNTL_H
      27             : #include <fcntl.h>
      28             : #endif
      29             : 
      30             : #include <algorithm>
      31             : #include <set>
      32             : #include <string>
      33             : #include <vector>
      34             : 
      35             : #include "cpl_conv.h"
      36             : #include "cpl_error.h"
      37             : #include "cpl_multiproc.h"
      38             : #include "cpl_string.h"
      39             : #include "cpl_vsi.h"
      40             : #include "cpl_time.h"
      41             : #include "degrib/degrib/degrib2.h"
      42             : #include "degrib/degrib/inventory.h"
      43             : #include "degrib/degrib/meta.h"
      44             : #include "degrib/degrib/metaname.h"
      45             : #include "degrib/degrib/myerror.h"
      46             : #include "degrib/degrib/type.h"
      47             : CPL_C_START
      48             : #include "degrib/g2clib/grib2.h"
      49             : #include "degrib/g2clib/pdstemplates.h"
      50             : CPL_C_END
      51             : #include "gdal.h"
      52             : #include "gdal_frmts.h"
      53             : #include "gdal_pam.h"
      54             : #include "gdal_priv.h"
      55             : #include "ogr_spatialref.h"
      56             : #include "memdataset.h"
      57             : 
      58             : static CPLMutex *hGRIBMutex = nullptr;
      59             : 
      60             : /************************************************************************/
      61             : /*                         ConvertUnitInText()                          */
      62             : /************************************************************************/
      63             : 
      64         918 : static CPLString ConvertUnitInText(bool bMetricUnits, const char *pszTxt)
      65             : {
      66         918 :     if (pszTxt == nullptr)
      67           0 :         return CPLString();
      68         918 :     if (!bMetricUnits)
      69           4 :         return pszTxt;
      70             : 
      71        1828 :     CPLString osRes(pszTxt);
      72         914 :     size_t iPos = osRes.find("[K]");
      73         914 :     if (iPos != std::string::npos)
      74          96 :         osRes = osRes.substr(0, iPos) + "[C]" + osRes.substr(iPos + 3);
      75         914 :     return osRes;
      76             : }
      77             : 
      78             : /************************************************************************/
      79             : /*                         Lon360to180()                               */
      80             : /************************************************************************/
      81             : 
      82         385 : static inline double Lon360to180(double lon)
      83             : {
      84         385 :     if (lon == 180)
      85           0 :         return 180;
      86         385 :     return fmod(lon + 180, 360) - 180;
      87             : }
      88             : 
      89             : /************************************************************************/
      90             : /*                           GRIBRasterBand()                            */
      91             : /************************************************************************/
      92             : 
      93         442 : GRIBRasterBand::GRIBRasterBand(GRIBDataset *poDSIn, int nBandIn,
      94         442 :                                inventoryType *psInv)
      95         442 :     : start(psInv->start), subgNum(psInv->subgNum),
      96         884 :       longFstLevel(CPLStrdup(psInv->longFstLevel)), m_Grib_Data(nullptr),
      97         442 :       m_Grib_MetaData(nullptr), nGribDataXSize(poDSIn->nRasterXSize),
      98         442 :       nGribDataYSize(poDSIn->nRasterYSize), m_nGribVersion(psInv->GribVersion),
      99         442 :       m_bHasLookedForNoData(false), m_dfNoData(0.0), m_bHasNoData(false)
     100             : 
     101             : {
     102         442 :     poDS = poDSIn;
     103         442 :     nBand = nBandIn;
     104             : 
     105             :     // Let user do -ot Float32 if needed for saving space, GRIB contains
     106             :     // Float64 (though not fully utilized most of the time).
     107         442 :     eDataType = GDT_Float64;
     108             : 
     109         442 :     nBlockXSize = poDSIn->nRasterXSize;
     110         442 :     nBlockYSize = 1;
     111             : 
     112         442 :     if (psInv->unitName != nullptr && psInv->comment != nullptr &&
     113         410 :         psInv->element != nullptr)
     114             :     {
     115         410 :         bLoadedMetadata = true;
     116             :         const char *pszGribNormalizeUnits =
     117         410 :             CPLGetConfigOption("GRIB_NORMALIZE_UNITS", "YES");
     118         410 :         bool bMetricUnits = CPLTestBool(pszGribNormalizeUnits);
     119             : 
     120         410 :         SetMetadataItem("GRIB_UNIT",
     121         820 :                         ConvertUnitInText(bMetricUnits, psInv->unitName));
     122         410 :         SetMetadataItem("GRIB_COMMENT",
     123         820 :                         ConvertUnitInText(bMetricUnits, psInv->comment));
     124         410 :         SetMetadataItem("GRIB_ELEMENT", psInv->element);
     125         410 :         SetMetadataItem("GRIB_SHORT_NAME", psInv->shortFstLevel);
     126         410 :         SetMetadataItem("GRIB_REF_TIME",
     127         820 :                         CPLString().Printf("%.0f", psInv->refTime));
     128         410 :         SetMetadataItem("GRIB_VALID_TIME",
     129         820 :                         CPLString().Printf("%.0f", psInv->validTime));
     130         410 :         SetMetadataItem("GRIB_FORECAST_SECONDS",
     131         820 :                         CPLString().Printf("%.0f", psInv->foreSec));
     132             :     }
     133         442 : }
     134             : 
     135             : /************************************************************************/
     136             : /*                           FindMetaData()                             */
     137             : /************************************************************************/
     138             : 
     139         775 : void GRIBRasterBand::FindMetaData()
     140             : {
     141         775 :     if (bLoadedMetadata)
     142         749 :         return;
     143          26 :     if (m_Grib_MetaData == nullptr)
     144             :     {
     145             :         grib_MetaData *metaData;
     146           5 :         GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     147           5 :         GRIBRasterBand::ReadGribData(poGDS->fp, start, subgNum, nullptr,
     148             :                                      &metaData);
     149           5 :         if (metaData == nullptr)
     150           0 :             return;
     151           5 :         m_Grib_MetaData = metaData;
     152             :     }
     153          26 :     bLoadedMetadata = true;
     154          26 :     m_nGribVersion = m_Grib_MetaData->GribVersion;
     155             : 
     156             :     const char *pszGribNormalizeUnits =
     157          26 :         CPLGetConfigOption("GRIB_NORMALIZE_UNITS", "YES");
     158          26 :     bool bMetricUnits = CPLTestBool(pszGribNormalizeUnits);
     159             : 
     160          26 :     GDALRasterBand::SetMetadataItem(
     161             :         "GRIB_UNIT",
     162          52 :         ConvertUnitInText(bMetricUnits, m_Grib_MetaData->unitName));
     163          26 :     GDALRasterBand::SetMetadataItem(
     164             :         "GRIB_COMMENT",
     165          52 :         ConvertUnitInText(bMetricUnits, m_Grib_MetaData->comment));
     166             : 
     167          26 :     GDALRasterBand::SetMetadataItem("GRIB_ELEMENT", m_Grib_MetaData->element);
     168          26 :     GDALRasterBand::SetMetadataItem("GRIB_SHORT_NAME",
     169          26 :                                     m_Grib_MetaData->shortFstLevel);
     170             : 
     171          26 :     if (m_nGribVersion == 2)
     172             :     {
     173          14 :         GDALRasterBand::SetMetadataItem(
     174             :             "GRIB_REF_TIME",
     175          28 :             CPLString().Printf("%.0f", m_Grib_MetaData->pds2.refTime));
     176          14 :         GDALRasterBand::SetMetadataItem(
     177             :             "GRIB_VALID_TIME",
     178          28 :             CPLString().Printf("%.0f", m_Grib_MetaData->pds2.sect4.validTime));
     179             :     }
     180          12 :     else if (m_nGribVersion == 1)
     181             :     {
     182          12 :         GDALRasterBand::SetMetadataItem(
     183             :             "GRIB_REF_TIME",
     184          24 :             CPLString().Printf("%.0f", m_Grib_MetaData->pds1.refTime));
     185          12 :         GDALRasterBand::SetMetadataItem(
     186             :             "GRIB_VALID_TIME",
     187          24 :             CPLString().Printf("%.0f", m_Grib_MetaData->pds1.validTime));
     188             :     }
     189             : 
     190          26 :     GDALRasterBand::SetMetadataItem(
     191             :         "GRIB_FORECAST_SECONDS",
     192          52 :         CPLString().Printf("%d", m_Grib_MetaData->deltTime));
     193             : }
     194             : 
     195             : /************************************************************************/
     196             : /*                          FindTrueStart()                             */
     197             : /*                                                                      */
     198             : /*      Scan after the official start of the message to find its        */
     199             : /*      true starting offset.                                           */
     200             : /************************************************************************/
     201         862 : vsi_l_offset GRIBRasterBand::FindTrueStart(VSILFILE *fp, vsi_l_offset start)
     202             : {
     203             :     // GRIB messages can be preceded by "garbage". GRIB2Inventory()
     204             :     // does not return the offset to the real start of the message
     205             :     char szHeader[1024 + 1];
     206         862 :     VSIFSeekL(fp, start, SEEK_SET);
     207             :     const int nRead =
     208         862 :         static_cast<int>(VSIFReadL(szHeader, 1, sizeof(szHeader) - 1, fp));
     209         862 :     szHeader[nRead] = 0;
     210             :     // Find the real offset of the fist message
     211         862 :     int nOffsetFirstMessage = 0;
     212        2544 :     for (int j = 0; j + 3 < nRead; j++)
     213             :     {
     214        2544 :         if (STARTS_WITH_CI(szHeader + j, "GRIB")
     215             : #ifdef ENABLE_TDLP
     216             :             || STARTS_WITH_CI(szHeader + j, "TDLP")
     217             : #endif
     218             :         )
     219             :         {
     220         862 :             nOffsetFirstMessage = j;
     221         862 :             break;
     222             :         }
     223             :     }
     224         862 :     return start + nOffsetFirstMessage;
     225             : }
     226             : 
     227             : /************************************************************************/
     228             : /*                      FindPDSTemplateGRIB2()                          */
     229             : /*                                                                      */
     230             : /*      Scan the file for the PDS template info and represent it as     */
     231             : /*      metadata.                                                       */
     232             : /************************************************************************/
     233             : 
     234         884 : void GRIBRasterBand::FindPDSTemplateGRIB2()
     235             : 
     236             : {
     237         884 :     CPLAssert(m_nGribVersion == 2);
     238             : 
     239         884 :     if (bLoadedPDS)
     240         558 :         return;
     241         326 :     bLoadedPDS = true;
     242             : 
     243         326 :     GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     244         326 :     start = FindTrueStart(poGDS->fp, start);
     245             : 
     246             :     // Read section 0
     247             :     GByte abySection0[16];
     248         652 :     if (VSIFSeekL(poGDS->fp, start, SEEK_SET) != 0 ||
     249         326 :         VSIFReadL(abySection0, 16, 1, poGDS->fp) != 1)
     250             :     {
     251           0 :         CPLDebug("GRIB", "Cannot read leading bytes of section 0");
     252           0 :         return;
     253             :     }
     254         326 :     GByte nDiscipline = abySection0[7 - 1];
     255         326 :     CPLString osDiscipline;
     256         326 :     osDiscipline = CPLString().Printf("%d", nDiscipline);
     257             :     static const char *const table00[] = {"Meteorological",
     258             :                                           "Hydrological",
     259             :                                           "Land Surface",
     260             :                                           "Space products",
     261             :                                           "Space products",
     262             :                                           "Reserved",
     263             :                                           "Reserved",
     264             :                                           "Reserved",
     265             :                                           "Reserved",
     266             :                                           "Reserved",
     267             :                                           "Oceanographic Products"};
     268         326 :     m_nDisciplineCode = nDiscipline;
     269         326 :     if (nDiscipline < CPL_ARRAYSIZE(table00))
     270             :     {
     271         325 :         m_osDisciplineName = table00[nDiscipline];
     272         650 :         osDiscipline += CPLString("(") +
     273        1300 :                         CPLString(table00[nDiscipline]).replaceAll(' ', '_') +
     274         325 :                         ")";
     275             :     }
     276             : 
     277         326 :     GDALRasterBand::SetMetadataItem("GRIB_DISCIPLINE", osDiscipline.c_str());
     278             : 
     279         326 :     GByte abyHead[5] = {0};
     280             : 
     281         326 :     if (VSIFReadL(abyHead, 5, 1, poGDS->fp) != 1)
     282             :     {
     283           0 :         CPLDebug("GRIB", "Cannot read 5 leading bytes past section 0");
     284           0 :         return;
     285             :     }
     286             : 
     287         326 :     GUInt32 nSectSize = 0;
     288         326 :     if (abyHead[4] == 1)
     289             :     {
     290         326 :         memcpy(&nSectSize, abyHead, 4);
     291         326 :         CPL_MSBPTR32(&nSectSize);
     292         326 :         if (nSectSize >= 21 && nSectSize <= 100000 /* arbitrary upper limit */)
     293             :         {
     294         326 :             GByte *pabyBody = static_cast<GByte *>(CPLMalloc(nSectSize));
     295         326 :             memcpy(pabyBody, abyHead, 5);
     296         326 :             VSIFReadL(pabyBody + 5, 1, nSectSize - 5, poGDS->fp);
     297             : 
     298         652 :             CPLString osIDS;
     299         326 :             unsigned short nCenter = static_cast<unsigned short>(
     300         326 :                 pabyBody[6 - 1] * 256 + pabyBody[7 - 1]);
     301         326 :             if (nCenter != GRIB2MISSING_u1 && nCenter != GRIB2MISSING_u2)
     302             :             {
     303          93 :                 osIDS += "CENTER=";
     304          93 :                 m_nCenter = nCenter;
     305          93 :                 osIDS += CPLSPrintf("%d", nCenter);
     306          93 :                 const char *pszCenter = centerLookup(nCenter);
     307          93 :                 if (pszCenter)
     308             :                 {
     309          93 :                     m_osCenterName = pszCenter;
     310          93 :                     osIDS += CPLString("(") + pszCenter + ")";
     311             :                 }
     312             :             }
     313             : 
     314         326 :             unsigned short nSubCenter = static_cast<unsigned short>(
     315         326 :                 pabyBody[8 - 1] * 256 + pabyBody[9 - 1]);
     316         326 :             if (nSubCenter != GRIB2MISSING_u2)
     317             :             {
     318         119 :                 if (!osIDS.empty())
     319          78 :                     osIDS += " ";
     320         119 :                 osIDS += "SUBCENTER=";
     321         119 :                 osIDS += CPLSPrintf("%d", nSubCenter);
     322         119 :                 m_nSubCenter = nSubCenter;
     323         119 :                 const char *pszSubCenter = subCenterLookup(nCenter, nSubCenter);
     324         119 :                 if (pszSubCenter)
     325             :                 {
     326           3 :                     m_osSubCenterName = pszSubCenter;
     327           3 :                     osIDS += CPLString("(") + pszSubCenter + ")";
     328             :                 }
     329             :             }
     330             : 
     331         326 :             if (!osIDS.empty())
     332         134 :                 osIDS += " ";
     333         326 :             osIDS += "MASTER_TABLE=";
     334         326 :             osIDS += CPLSPrintf("%d", pabyBody[10 - 1]);
     335         326 :             osIDS += " ";
     336         326 :             osIDS += "LOCAL_TABLE=";
     337         326 :             osIDS += CPLSPrintf("%d", pabyBody[11 - 1]);
     338         326 :             osIDS += " ";
     339         326 :             osIDS += "SIGNF_REF_TIME=";
     340         326 :             unsigned nSignRefTime = pabyBody[12 - 1];
     341         326 :             osIDS += CPLSPrintf("%d", nSignRefTime);
     342             :             static const char *const table12[] = {
     343             :                 "Analysis", "Start of Forecast", "Verifying time of forecast",
     344             :                 "Observation time"};
     345         326 :             if (nSignRefTime < CPL_ARRAYSIZE(table12))
     346             :             {
     347         326 :                 m_osSignRefTimeName = table12[nSignRefTime];
     348         652 :                 osIDS += CPLString("(") +
     349        1304 :                          CPLString(table12[nSignRefTime]).replaceAll(' ', '_') +
     350         326 :                          ")";
     351             :             }
     352         326 :             osIDS += " ";
     353         326 :             osIDS += "REF_TIME=";
     354             :             m_osRefTime =
     355             :                 CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02dZ",
     356         326 :                            pabyBody[13 - 1] * 256 + pabyBody[14 - 1],
     357         326 :                            pabyBody[15 - 1], pabyBody[16 - 1], pabyBody[17 - 1],
     358         326 :                            pabyBody[18 - 1], pabyBody[19 - 1]);
     359         326 :             osIDS += m_osRefTime;
     360         326 :             osIDS += " ";
     361         326 :             osIDS += "PROD_STATUS=";
     362         326 :             unsigned nProdStatus = pabyBody[20 - 1];
     363         326 :             osIDS += CPLSPrintf("%d", nProdStatus);
     364             :             static const char *const table13[] = {
     365             :                 "Operational",     "Operational test",
     366             :                 "Research",        "Re-analysis",
     367             :                 "TIGGE",           "TIGGE test",
     368             :                 "S2S operational", "S2S test",
     369             :                 "UERRA",           "UERRA test"};
     370         326 :             if (nProdStatus < CPL_ARRAYSIZE(table13))
     371             :             {
     372         133 :                 m_osProductionStatus = table13[nProdStatus];
     373         266 :                 osIDS += CPLString("(") +
     374         532 :                          CPLString(table13[nProdStatus]).replaceAll(' ', '_') +
     375         133 :                          ")";
     376             :             }
     377         326 :             osIDS += " ";
     378         326 :             osIDS += "TYPE=";
     379         326 :             unsigned nType = pabyBody[21 - 1];
     380         326 :             osIDS += CPLSPrintf("%d", nType);
     381             :             static const char *const table14[] = {
     382             :                 "Analysis",
     383             :                 "Forecast",
     384             :                 "Analysis and forecast",
     385             :                 "Control forecast",
     386             :                 "Perturbed forecast",
     387             :                 "Control and perturbed forecast",
     388             :                 "Processed satellite observations",
     389             :                 "Processed radar observations",
     390             :                 "Event Probability"};
     391         326 :             if (nType < CPL_ARRAYSIZE(table14))
     392             :             {
     393         133 :                 m_osType = table14[nType];
     394         266 :                 osIDS += CPLString("(") +
     395         399 :                          CPLString(table14[nType]).replaceAll(' ', '_') + ")";
     396             :             }
     397             : 
     398         326 :             GDALRasterBand::SetMetadataItem("GRIB_IDS", osIDS);
     399             : 
     400         326 :             CPLFree(pabyBody);
     401             :         }
     402             : 
     403         326 :         if (VSIFReadL(abyHead, 5, 1, poGDS->fp) != 1)
     404             :         {
     405           0 :             CPLDebug("GRIB", "Cannot read 5 leading bytes past section 1");
     406           0 :             return;
     407             :         }
     408             :     }
     409             : 
     410         326 :     if (subgNum > 0)
     411             :     {
     412             :         // If we are a subgrid, then iterate over all preceding subgrids
     413          14 :         for (int iSubMessage = 0; iSubMessage < subgNum;)
     414             :         {
     415          12 :             memcpy(&nSectSize, abyHead, 4);
     416          12 :             CPL_MSBPTR32(&nSectSize);
     417          12 :             if (nSectSize < 5)
     418             :             {
     419           0 :                 CPLDebug("GRIB", "Invalid section size for iSubMessage = %d",
     420             :                          iSubMessage);
     421           0 :                 return;
     422             :             }
     423          12 :             if (VSIFSeekL(poGDS->fp, nSectSize - 5, SEEK_CUR) != 0)
     424             :             {
     425           0 :                 CPLDebug("GRIB",
     426             :                          "Cannot read past section for iSubMessage = %d",
     427             :                          iSubMessage);
     428           0 :                 return;
     429             :             }
     430          12 :             if (abyHead[4] < 2 || abyHead[4] > 7)
     431             :             {
     432           0 :                 CPLDebug("GRIB", "Invalid section number for iSubMessage = %d",
     433             :                          iSubMessage);
     434           0 :                 return;
     435             :             }
     436          12 :             if (abyHead[4] == 7)
     437             :             {
     438           2 :                 ++iSubMessage;
     439             :             }
     440          12 :             if (VSIFReadL(abyHead, 5, 1, poGDS->fp) != 1)
     441             :             {
     442           0 :                 CPLDebug("GRIB",
     443             :                          "Cannot read 5 leading bytes for iSubMessage = %d",
     444             :                          iSubMessage);
     445           0 :                 return;
     446             :             }
     447             :         }
     448             :     }
     449             : 
     450             :     // Skip to section 4
     451         951 :     while (abyHead[4] != 4)
     452             :     {
     453         625 :         memcpy(&nSectSize, abyHead, 4);
     454         625 :         CPL_MSBPTR32(&nSectSize);
     455             : 
     456         625 :         const int nCurSection = abyHead[4];
     457         625 :         if (nSectSize < 5)
     458             :         {
     459           0 :             CPLDebug("GRIB", "Invalid section size for section %d",
     460             :                      nCurSection);
     461           0 :             return;
     462             :         }
     463        1250 :         if (VSIFSeekL(poGDS->fp, nSectSize - 5, SEEK_CUR) != 0 ||
     464         625 :             VSIFReadL(abyHead, 5, 1, poGDS->fp) != 1)
     465             :         {
     466           0 :             CPLDebug("GRIB", "Cannot read section %d", nCurSection);
     467           0 :             return;
     468             :         }
     469             :     }
     470             : 
     471             :     // Collect section 4 octet information.  We read the file
     472             :     // ourselves since the GRIB API does not appear to preserve all
     473             :     // this for us.
     474             :     // if( abyHead[4] == 4 )
     475             :     {
     476         326 :         memcpy(&nSectSize, abyHead, 4);
     477         326 :         CPL_MSBPTR32(&nSectSize);
     478         326 :         if (nSectSize >= 9 && nSectSize <= 100000 /* arbitrary upper limit */)
     479             :         {
     480         326 :             GByte *pabyBody = static_cast<GByte *>(CPLMalloc(nSectSize));
     481         326 :             memcpy(pabyBody, abyHead, 5);
     482         326 :             if (VSIFReadL(pabyBody + 5, 1, nSectSize - 5, poGDS->fp) !=
     483         326 :                 nSectSize - 5)
     484             :             {
     485           0 :                 CPLDebug("GRIB", "Cannot read section 4");
     486           0 :                 CPLFree(pabyBody);
     487           0 :                 return;
     488             :             }
     489             : 
     490         326 :             GUInt16 nCoordCount = 0;
     491         326 :             memcpy(&nCoordCount, pabyBody + 6 - 1, 2);
     492         326 :             CPL_MSBPTR16(&nCoordCount);
     493             : 
     494         326 :             GUInt16 nPDTN = 0;
     495         326 :             memcpy(&nPDTN, pabyBody + 8 - 1, 2);
     496         326 :             CPL_MSBPTR16(&nPDTN);
     497             : 
     498         326 :             GDALRasterBand::SetMetadataItem("GRIB_PDS_PDTN",
     499         652 :                                             CPLString().Printf("%d", nPDTN));
     500         326 :             m_nPDTN = nPDTN;
     501             : 
     502         652 :             CPLString osOctet;
     503         326 :             const int nTemplateFoundByteCount =
     504         326 :                 nSectSize - 9U >= nCoordCount * 4U
     505         326 :                     ? static_cast<int>(nSectSize - 9 - nCoordCount * 4)
     506             :                     : 0;
     507        9222 :             for (int i = 0; i < nTemplateFoundByteCount; i++)
     508             :             {
     509        8896 :                 char szByte[10] = {'\0'};
     510             : 
     511        8896 :                 if (i == 0)
     512         326 :                     snprintf(szByte, sizeof(szByte), "%d", pabyBody[i + 9]);
     513             :                 else
     514        8570 :                     snprintf(szByte, sizeof(szByte), " %d", pabyBody[i + 9]);
     515        8896 :                 osOctet += szByte;
     516             :             }
     517             : 
     518         326 :             GDALRasterBand::SetMetadataItem("GRIB_PDS_TEMPLATE_NUMBERS",
     519             :                                             osOctet);
     520             : 
     521         326 :             g2int iofst = 0;
     522         326 :             g2int pdsnum = 0;
     523         326 :             g2int *pdstempl = nullptr;
     524         326 :             g2int mappdslen = 0;
     525         326 :             g2float *coordlist = nullptr;
     526         326 :             g2int numcoord = 0;
     527         326 :             if (getpdsindex(nPDTN) < 0)
     528             :             {
     529           3 :                 CPLError(CE_Warning, CPLE_NotSupported,
     530             :                          "Template 4.%d is not recognized currently", nPDTN);
     531             :             }
     532         323 :             else if (g2_unpack4(pabyBody, nSectSize, &iofst, &pdsnum, &pdstempl,
     533         323 :                                 &mappdslen, &coordlist, &numcoord) == 0)
     534             :             {
     535         323 :                 gtemplate *mappds = extpdstemplate(pdsnum, pdstempl);
     536         323 :                 if (mappds)
     537             :                 {
     538         323 :                     int nTemplateByteCount = 0;
     539        5560 :                     for (int i = 0; i < mappds->maplen; i++)
     540        5237 :                         nTemplateByteCount += abs(mappds->map[i]);
     541         388 :                     for (int i = 0; i < mappds->extlen; i++)
     542          65 :                         nTemplateByteCount += abs(mappds->ext[i]);
     543         323 :                     if (nTemplateByteCount == nTemplateFoundByteCount)
     544             :                     {
     545         642 :                         CPLString osValues;
     546        5591 :                         for (g2int i = 0; i < mappds->maplen + mappds->extlen;
     547             :                              i++)
     548             :                         {
     549        5270 :                             if (i > 0)
     550        4949 :                                 osValues += " ";
     551        5270 :                             const int nEltSize =
     552        5270 :                                 (i < mappds->maplen)
     553        5270 :                                     ? mappds->map[i]
     554          65 :                                     : mappds->ext[i - mappds->maplen];
     555        5270 :                             if (nEltSize == 4)
     556             :                             {
     557          88 :                                 m_anPDSTemplateAssembledValues.push_back(
     558          88 :                                     static_cast<GUInt32>(pdstempl[i]));
     559             :                                 osValues += CPLSPrintf(
     560          88 :                                     "%u", static_cast<GUInt32>(pdstempl[i]));
     561             :                             }
     562             :                             else
     563             :                             {
     564        5182 :                                 m_anPDSTemplateAssembledValues.push_back(
     565        5182 :                                     pdstempl[i]);
     566        5182 :                                 osValues += CPLSPrintf("%d", pdstempl[i]);
     567             :                             }
     568             :                         }
     569         321 :                         GDALRasterBand::SetMetadataItem(
     570             :                             "GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES", osValues);
     571             :                     }
     572             :                     else
     573             :                     {
     574           2 :                         CPLDebug(
     575             :                             "GRIB",
     576             :                             "Cannot expose GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES "
     577             :                             "as we would expect %d bytes from the "
     578             :                             "tables, but %d are available",
     579             :                             nTemplateByteCount, nTemplateFoundByteCount);
     580             :                     }
     581             : 
     582         323 :                     free(mappds->ext);
     583         323 :                     free(mappds);
     584             :                 }
     585             :             }
     586         326 :             free(pdstempl);
     587         326 :             free(coordlist);
     588             : 
     589         326 :             CPLFree(pabyBody);
     590             : 
     591         652 :             FindNoDataGrib2(false);
     592             :         }
     593             :         else
     594             :         {
     595           0 :             CPLDebug("GRIB", "Invalid section size for section %d", 4);
     596             :         }
     597             :     }
     598             : }
     599             : 
     600             : /************************************************************************/
     601             : /*                        FindNoDataGrib2()                             */
     602             : /************************************************************************/
     603             : 
     604         326 : void GRIBRasterBand::FindNoDataGrib2(bool bSeekToStart)
     605             : {
     606             :     // There is no easy way in the degrib API to retrieve the nodata value
     607             :     // without decompressing the data point section (which is slow), so
     608             :     // retrieve nodata value by parsing section 5 (Data Representation Section)
     609             :     // We also check section 6 to see if there is a bitmap
     610         326 :     GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     611         326 :     CPLAssert(m_nGribVersion == 2);
     612             : 
     613         326 :     if (m_bHasLookedForNoData)
     614           0 :         return;
     615         326 :     m_bHasLookedForNoData = true;
     616             : 
     617         326 :     if (bSeekToStart)
     618             :     {
     619             :         // Skip over section 0
     620           0 :         VSIFSeekL(poGDS->fp, start + 16, SEEK_SET);
     621             :     }
     622             : 
     623         326 :     GByte abyHead[5] = {0};
     624         326 :     VSIFReadL(abyHead, 5, 1, poGDS->fp);
     625             : 
     626             :     // Skip to section 5
     627         326 :     GUInt32 nSectSize = 0;
     628         326 :     while (abyHead[4] != 5)
     629             :     {
     630           0 :         memcpy(&nSectSize, abyHead, 4);
     631           0 :         CPL_MSBPTR32(&nSectSize);
     632             : 
     633           0 :         if (nSectSize < 5 ||
     634           0 :             VSIFSeekL(poGDS->fp, nSectSize - 5, SEEK_CUR) != 0 ||
     635           0 :             VSIFReadL(abyHead, 5, 1, poGDS->fp) != 1)
     636           0 :             break;
     637             :     }
     638             : 
     639             :     // See http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_sect5.shtml
     640         326 :     if (abyHead[4] == 5)
     641             :     {
     642         326 :         memcpy(&nSectSize, abyHead, 4);
     643         326 :         CPL_MSBPTR32(&nSectSize);
     644         326 :         if (nSectSize >= 11 && nSectSize <= 100000 /* arbitrary upper limit */)
     645             :         {
     646         326 :             GByte *pabyBody = static_cast<GByte *>(CPLMalloc(nSectSize));
     647         326 :             memcpy(pabyBody, abyHead, 5);
     648         326 :             VSIFReadL(pabyBody + 5, 1, nSectSize - 5, poGDS->fp);
     649             : 
     650         326 :             GUInt16 nDRTN = 0;
     651         326 :             memcpy(&nDRTN, pabyBody + 10 - 1, 2);
     652         326 :             CPL_MSBPTR16(&nDRTN);
     653             : 
     654         326 :             GDALRasterBand::SetMetadataItem("DRS_DRTN", CPLSPrintf("%d", nDRTN),
     655             :                                             "GRIB");
     656         326 :             if ((nDRTN == GS5_SIMPLE || nDRTN == GS5_CMPLX ||
     657         182 :                  nDRTN == GS5_CMPLXSEC || nDRTN == GS5_JPEG2000 ||
     658         126 :                  nDRTN == GS5_PNG) &&
     659         230 :                 nSectSize >= 20)
     660             :             {
     661             :                 float fRef;
     662         230 :                 memcpy(&fRef, pabyBody + 12 - 1, 4);
     663         230 :                 CPL_MSBPTR32(&fRef);
     664         230 :                 GDALRasterBand::SetMetadataItem(
     665             :                     "DRS_REF_VALUE", CPLSPrintf("%.10f", fRef), "GRIB");
     666             : 
     667             :                 GUInt16 nBinaryScaleFactorUnsigned;
     668         230 :                 memcpy(&nBinaryScaleFactorUnsigned, pabyBody + 16 - 1, 2);
     669         230 :                 CPL_MSBPTR16(&nBinaryScaleFactorUnsigned);
     670         230 :                 const int nBSF =
     671             :                     (nBinaryScaleFactorUnsigned & 0x8000)
     672          25 :                         ? -static_cast<int>(nBinaryScaleFactorUnsigned & 0x7FFF)
     673         230 :                         : static_cast<int>(nBinaryScaleFactorUnsigned);
     674         230 :                 GDALRasterBand::SetMetadataItem("DRS_BINARY_SCALE_FACTOR",
     675             :                                                 CPLSPrintf("%d", nBSF), "GRIB");
     676             : 
     677             :                 GUInt16 nDecimalScaleFactorUnsigned;
     678         230 :                 memcpy(&nDecimalScaleFactorUnsigned, pabyBody + 18 - 1, 2);
     679         230 :                 CPL_MSBPTR16(&nDecimalScaleFactorUnsigned);
     680         230 :                 const int nDSF =
     681             :                     (nDecimalScaleFactorUnsigned & 0x8000)
     682          19 :                         ? -static_cast<int>(nDecimalScaleFactorUnsigned &
     683             :                                             0x7FFF)
     684         230 :                         : static_cast<int>(nDecimalScaleFactorUnsigned);
     685         230 :                 GDALRasterBand::SetMetadataItem("DRS_DECIMAL_SCALE_FACTOR",
     686             :                                                 CPLSPrintf("%d", nDSF), "GRIB");
     687             : 
     688         230 :                 const int nBits = pabyBody[20 - 1];
     689         230 :                 GDALRasterBand::SetMetadataItem(
     690             :                     "DRS_NBITS", CPLSPrintf("%d", nBits), "GRIB");
     691             :             }
     692             : 
     693             :             // 2 = Grid Point Data - Complex Packing
     694             :             // 3 = Grid Point Data - Complex Packing and Spatial Differencing
     695         326 :             if ((nDRTN == GS5_CMPLX || nDRTN == GS5_CMPLXSEC) &&
     696          54 :                 nSectSize >= 31)
     697             :             {
     698          54 :                 const int nMiss = pabyBody[23 - 1];
     699          54 :                 if (nMiss == 1 || nMiss == 2)
     700             :                 {
     701          35 :                     const int original_field_type = pabyBody[21 - 1];
     702          35 :                     if (original_field_type == 0)  // Floating Point
     703             :                     {
     704             :                         float fTemp;
     705          27 :                         memcpy(&fTemp, &pabyBody[24 - 1], 4);
     706          27 :                         CPL_MSBPTR32(&fTemp);
     707          27 :                         m_dfNoData = fTemp;
     708          27 :                         m_bHasNoData = true;
     709          27 :                         if (nMiss == 2)
     710             :                         {
     711           0 :                             memcpy(&fTemp, &pabyBody[28 - 1], 4);
     712           0 :                             CPL_MSBPTR32(&fTemp);
     713           0 :                             CPLDebug("GRIB",
     714             :                                      "Secondary missing value also set for "
     715             :                                      "band %d : %f",
     716             :                                      nBand, fTemp);
     717             :                         }
     718             :                     }
     719           8 :                     else if (original_field_type == 1)  // Integer
     720             :                     {
     721             :                         int iTemp;
     722           8 :                         memcpy(&iTemp, &pabyBody[24 - 1], 4);
     723           8 :                         CPL_MSBPTR32(&iTemp);
     724           8 :                         m_dfNoData = iTemp;
     725           8 :                         m_bHasNoData = true;
     726           8 :                         if (nMiss == 2)
     727             :                         {
     728           0 :                             memcpy(&iTemp, &pabyBody[28 - 1], 4);
     729           0 :                             CPL_MSBPTR32(&iTemp);
     730           0 :                             CPLDebug("GRIB",
     731             :                                      "Secondary missing value also set for "
     732             :                                      "band %d : %d",
     733             :                                      nBand, iTemp);
     734             :                         }
     735             :                     }
     736             :                     else
     737             :                     {
     738             :                         // FIXME What to do? Blindly convert to float?
     739           0 :                         CPLDebug("GRIB",
     740             :                                  "Complex Packing - Type of Original Field "
     741             :                                  "Values for band %d:  %u",
     742             :                                  nBand, original_field_type);
     743             :                     }
     744             :                 }
     745             :             }
     746             : 
     747         326 :             if (nDRTN == GS5_CMPLXSEC && nSectSize >= 48)
     748             :             {
     749          21 :                 const int nOrder = pabyBody[48 - 1];
     750          21 :                 GDALRasterBand::SetMetadataItem(
     751             :                     "DRS_SPATIAL_DIFFERENCING_ORDER", CPLSPrintf("%d", nOrder),
     752             :                     "GRIB");
     753             :             }
     754             : 
     755         326 :             CPLFree(pabyBody);
     756             :         }
     757           0 :         else if (nSectSize > 5)
     758             :         {
     759           0 :             VSIFSeekL(poGDS->fp, nSectSize - 5, SEEK_CUR);
     760             :         }
     761             :     }
     762             : 
     763         326 :     if (!m_bHasNoData)
     764             :     {
     765             :         // Check bitmap section
     766         291 :         GByte abySection6[6] = {0};
     767         291 :         VSIFReadL(abySection6, 6, 1, poGDS->fp);
     768             :         // Is there a bitmap ?
     769         291 :         if (abySection6[4] == 6 && abySection6[5] == 0)
     770             :         {
     771           6 :             m_dfNoData = 9999.0;  // Same value as in metaparse.cpp:ParseGrid()
     772           6 :             m_bHasNoData = true;
     773             :         }
     774             :     }
     775             : }
     776             : 
     777             : /************************************************************************/
     778             : /*                         GetDescription()                             */
     779             : /************************************************************************/
     780             : 
     781          29 : const char *GRIBRasterBand::GetDescription() const
     782             : {
     783          29 :     if (longFstLevel == nullptr)
     784           0 :         return GDALPamRasterBand::GetDescription();
     785             : 
     786          29 :     return longFstLevel;
     787             : }
     788             : 
     789             : /************************************************************************/
     790             : /*                             LoadData()                               */
     791             : /************************************************************************/
     792             : 
     793        9152 : CPLErr GRIBRasterBand::LoadData()
     794             : 
     795             : {
     796        9152 :     if (!m_Grib_Data)
     797             :     {
     798         184 :         GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     799             : 
     800         184 :         if (poGDS->bCacheOnlyOneBand)
     801             :         {
     802             :             // In "one-band-at-a-time" strategy, if the last recently used
     803             :             // band is not that one, uncache it. We could use a smarter strategy
     804             :             // based on a LRU, but that's a bit overkill for now.
     805           0 :             poGDS->poLastUsedBand->UncacheData();
     806           0 :             poGDS->nCachedBytes = 0;
     807             :         }
     808             :         else
     809             :         {
     810             :             // Once we have cached more than nCachedBytesThreshold bytes, we
     811             :             // will switch to "one-band-at-a-time" strategy, instead of caching
     812             :             // all bands that have been accessed.
     813         184 :             if (poGDS->nCachedBytes > poGDS->nCachedBytesThreshold)
     814             :             {
     815             :                 GUIntBig nMinCacheSize =
     816           0 :                     1 + static_cast<GUIntBig>(poGDS->nRasterXSize) *
     817           0 :                             poGDS->nRasterYSize * poGDS->nBands *
     818           0 :                             GDALGetDataTypeSizeBytes(eDataType) / 1024 / 1024;
     819           0 :                 CPLDebug("GRIB",
     820             :                          "Maximum band cache size reached for this dataset. "
     821             :                          "Caching only one band at a time from now, which can "
     822             :                          "negatively affect performance. Consider "
     823             :                          "increasing GRIB_CACHEMAX to a higher value (in MB), "
     824             :                          "at least " CPL_FRMT_GUIB " in that instance",
     825             :                          nMinCacheSize);
     826           0 :                 for (int i = 0; i < poGDS->nBands; i++)
     827             :                 {
     828             :                     reinterpret_cast<GRIBRasterBand *>(
     829           0 :                         poGDS->GetRasterBand(i + 1))
     830           0 :                         ->UncacheData();
     831             :                 }
     832           0 :                 poGDS->nCachedBytes = 0;
     833           0 :                 poGDS->bCacheOnlyOneBand = TRUE;
     834             :             }
     835             :         }
     836             : 
     837             :         // we don't seem to have any way to detect errors in this!
     838         184 :         if (m_Grib_MetaData != nullptr)
     839             :         {
     840         137 :             MetaFree(m_Grib_MetaData);
     841         137 :             delete m_Grib_MetaData;
     842         137 :             m_Grib_MetaData = nullptr;
     843             :         }
     844         184 :         ReadGribData(poGDS->fp, start, subgNum, &m_Grib_Data, &m_Grib_MetaData);
     845         184 :         if (!m_Grib_Data)
     846             :         {
     847           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Out of memory.");
     848           0 :             if (m_Grib_MetaData != nullptr)
     849             :             {
     850           0 :                 MetaFree(m_Grib_MetaData);
     851           0 :                 delete m_Grib_MetaData;
     852           0 :                 m_Grib_MetaData = nullptr;
     853             :             }
     854           0 :             return CE_Failure;
     855             :         }
     856             : 
     857             :         // Check the band matches the dataset as a whole, size wise. (#3246)
     858         184 :         nGribDataXSize = m_Grib_MetaData->gds.Nx;
     859         184 :         nGribDataYSize = m_Grib_MetaData->gds.Ny;
     860         184 :         if (nGribDataXSize <= 0 || nGribDataYSize <= 0)
     861             :         {
     862           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     863             :                      "Band %d of GRIB dataset is %dx%d.", nBand, nGribDataXSize,
     864             :                      nGribDataYSize);
     865           0 :             MetaFree(m_Grib_MetaData);
     866           0 :             delete m_Grib_MetaData;
     867           0 :             m_Grib_MetaData = nullptr;
     868           0 :             return CE_Failure;
     869             :         }
     870             : 
     871         184 :         poGDS->nCachedBytes += static_cast<GIntBig>(nGribDataXSize) *
     872         184 :                                nGribDataYSize * sizeof(double);
     873         184 :         poGDS->poLastUsedBand = this;
     874             : 
     875         184 :         if (nGribDataXSize != nRasterXSize || nGribDataYSize != nRasterYSize)
     876             :         {
     877          24 :             CPLError(CE_Warning, CPLE_AppDefined,
     878             :                      "Band %d of GRIB dataset is %dx%d, while the first band "
     879             :                      "and dataset is %dx%d.  Georeferencing of band %d may "
     880             :                      "be incorrect, and data access may be incomplete.",
     881             :                      nBand, nGribDataXSize, nGribDataYSize, nRasterXSize,
     882             :                      nRasterYSize, nBand);
     883             :         }
     884             :     }
     885             : 
     886        9152 :     return CE_None;
     887             : }
     888             : 
     889             : /************************************************************************/
     890             : /*                       IsGdalinfoInteractive()                        */
     891             : /************************************************************************/
     892             : 
     893             : #ifdef BUILD_APPS
     894           0 : static bool IsGdalinfoInteractive()
     895             : {
     896           0 :     static const bool bIsGdalinfoInteractive = []()
     897             :     {
     898           0 :         if (CPLIsInteractive(stdout))
     899             :         {
     900           0 :             std::string osPath;
     901           0 :             osPath.resize(1024);
     902           0 :             if (CPLGetExecPath(&osPath[0], static_cast<int>(osPath.size())))
     903             :             {
     904           0 :                 osPath = CPLGetBasenameSafe(osPath.c_str());
     905             :             }
     906           0 :             return osPath == "gdalinfo";
     907             :         }
     908           0 :         return false;
     909           0 :     }();
     910           0 :     return bIsGdalinfoInteractive;
     911             : }
     912             : #endif
     913             : 
     914             : /************************************************************************/
     915             : /*                             GetMetaData()                            */
     916             : /************************************************************************/
     917          87 : char **GRIBRasterBand::GetMetadata(const char *pszDomain)
     918             : {
     919          87 :     FindMetaData();
     920         138 :     if ((pszDomain == nullptr || pszDomain[0] == 0) && m_nGribVersion == 2 &&
     921          51 :         CPLTestBool(CPLGetConfigOption("GRIB_PDS_ALL_BANDS", "ON")))
     922             :     {
     923             : #ifdef BUILD_APPS
     924             :         // Detect slow execution of e.g.
     925             :         // "gdalinfo /vsis3/noaa-hrrr-bdp-pds/hrrr.20220804/conus/hrrr.t00z.wrfsfcf01.grib2"
     926          51 :         GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     927          11 :         if (poGDS->m_bSideCarIdxUsed && !poGDS->m_bWarnedGdalinfoNomd &&
     928          11 :             poGDS->GetRasterCount() > 10 &&
     929          62 :             !VSIIsLocal(poGDS->GetDescription()) && IsGdalinfoInteractive())
     930             :         {
     931           0 :             if (poGDS->m_nFirstMetadataQueriedTimeStamp)
     932             :             {
     933           0 :                 if (time(nullptr) - poGDS->m_nFirstMetadataQueriedTimeStamp > 2)
     934             :                 {
     935           0 :                     poGDS->m_bWarnedGdalinfoNomd = true;
     936             : 
     937           0 :                     CPLError(
     938             :                         CE_Warning, CPLE_AppDefined,
     939             :                         "If metadata does not matter, faster result could be "
     940             :                         "obtained by adding the -nomd switch to gdalinfo");
     941             :                 }
     942             :             }
     943             :             else
     944             :             {
     945           0 :                 poGDS->m_nFirstMetadataQueriedTimeStamp = time(nullptr);
     946             :             }
     947             :         }
     948             : #endif
     949             : 
     950          51 :         FindPDSTemplateGRIB2();
     951             :     }
     952          87 :     return GDALPamRasterBand::GetMetadata(pszDomain);
     953             : }
     954             : 
     955             : /************************************************************************/
     956             : /*                             GetMetaDataItem()                        */
     957             : /************************************************************************/
     958         693 : const char *GRIBRasterBand::GetMetadataItem(const char *pszName,
     959             :                                             const char *pszDomain)
     960             : {
     961         693 :     if (!((!pszDomain || pszDomain[0] == 0) &&
     962         681 :           (EQUAL(pszName, "STATISTICS_MINIMUM") ||
     963         677 :            EQUAL(pszName, "STATISTICS_MAXIMUM"))))
     964             :     {
     965         688 :         FindMetaData();
     966        1221 :         if (m_nGribVersion == 2 &&
     967         533 :             CPLTestBool(CPLGetConfigOption("GRIB_PDS_ALL_BANDS", "ON")))
     968             :         {
     969         532 :             FindPDSTemplateGRIB2();
     970             :         }
     971             :     }
     972         693 :     return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
     973             : }
     974             : 
     975             : /************************************************************************/
     976             : /*                             IReadBlock()                             */
     977             : /************************************************************************/
     978             : 
     979        9152 : CPLErr GRIBRasterBand::IReadBlock(int /* nBlockXOff */, int nBlockYOff,
     980             :                                   void *pImage)
     981             : 
     982             : {
     983        9152 :     CPLErr eErr = LoadData();
     984        9152 :     if (eErr != CE_None)
     985           0 :         return eErr;
     986             : 
     987        9152 :     GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
     988             : 
     989             :     // The image as read is always upside down to our normal
     990             :     // orientation so we need to effectively flip it at this
     991             :     // point.  We also need to deal with bands that are a different
     992             :     // size than the dataset as a whole.
     993             : 
     994        9152 :     if (nGribDataXSize == nRasterXSize && nGribDataYSize == nRasterYSize &&
     995        8660 :         poGDS->nSplitAndSwapColumn == 0)
     996             :     {
     997             :         // Simple 1:1 case.
     998        7001 :         memcpy(pImage,
     999        7001 :                m_Grib_Data + static_cast<size_t>(nRasterXSize) *
    1000        7001 :                                  (nRasterYSize - nBlockYOff - 1),
    1001        7001 :                nRasterXSize * sizeof(double));
    1002             : 
    1003        7001 :         return CE_None;
    1004             :     }
    1005             : 
    1006        2151 :     memset(pImage, 0, sizeof(double) * nRasterXSize);
    1007             : 
    1008        2151 :     if (nBlockYOff >= nGribDataYSize)  // Off image?
    1009          57 :         return CE_None;
    1010             : 
    1011        2094 :     int nSplitAndSwapColumn = poGDS->nSplitAndSwapColumn;
    1012        2094 :     if (nRasterXSize != nGribDataXSize)
    1013         435 :         nSplitAndSwapColumn = 0;
    1014             : 
    1015        2094 :     const int nCopyWords = std::min(nRasterXSize, nGribDataXSize);
    1016             : 
    1017        2094 :     memcpy(pImage,
    1018        2094 :            m_Grib_Data +
    1019        2094 :                static_cast<size_t>(nGribDataXSize) *
    1020        2094 :                    (nGribDataYSize - nBlockYOff - 1) +
    1021             :                nSplitAndSwapColumn,
    1022        2094 :            (nCopyWords - nSplitAndSwapColumn) * sizeof(double));
    1023             : 
    1024        2094 :     if (nSplitAndSwapColumn > 0)
    1025        1659 :         memcpy(reinterpret_cast<void *>(reinterpret_cast<double *>(pImage) +
    1026        1659 :                                         nCopyWords - nSplitAndSwapColumn),
    1027        1659 :                m_Grib_Data + static_cast<size_t>(nGribDataXSize) *
    1028        1659 :                                  (nGribDataYSize - nBlockYOff - 1),
    1029        1659 :                nSplitAndSwapColumn * sizeof(double));
    1030             : 
    1031        2094 :     return CE_None;
    1032             : }
    1033             : 
    1034             : /************************************************************************/
    1035             : /*                           GetNoDataValue()                           */
    1036             : /************************************************************************/
    1037             : 
    1038         125 : double GRIBRasterBand::GetNoDataValue(int *pbSuccess)
    1039             : {
    1040         125 :     if (m_bHasLookedForNoData)
    1041             :     {
    1042         105 :         if (pbSuccess)
    1043         105 :             *pbSuccess = m_bHasNoData;
    1044         105 :         return m_dfNoData;
    1045             :     }
    1046             : 
    1047          20 :     m_bHasLookedForNoData = true;
    1048          20 :     if (m_Grib_MetaData == nullptr)
    1049             :     {
    1050          18 :         GRIBDataset *poGDS = static_cast<GRIBDataset *>(poDS);
    1051             : 
    1052             : #ifdef BUILD_APPS
    1053             :         // Detect slow execution of e.g.
    1054             :         // "gdalinfo /vsis3/noaa-hrrr-bdp-pds/hrrr.20220804/conus/hrrr.t00z.wrfsfcf01.grib2"
    1055             : 
    1056           0 :         if (poGDS->m_bSideCarIdxUsed && !poGDS->m_bWarnedGdalinfoNonodata &&
    1057           0 :             poGDS->GetRasterCount() > 10 &&
    1058          18 :             !VSIIsLocal(poGDS->GetDescription()) && IsGdalinfoInteractive())
    1059             :         {
    1060           0 :             if (poGDS->m_nFirstNodataQueriedTimeStamp)
    1061             :             {
    1062           0 :                 if (time(nullptr) - poGDS->m_nFirstNodataQueriedTimeStamp > 2)
    1063             :                 {
    1064           0 :                     poGDS->m_bWarnedGdalinfoNonodata = true;
    1065             : 
    1066           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1067             :                              "If nodata value does not matter, faster result "
    1068             :                              "could be obtained by adding the -nonodata switch "
    1069             :                              "to gdalinfo");
    1070             :                 }
    1071             :             }
    1072             :             else
    1073             :             {
    1074           0 :                 poGDS->m_nFirstNodataQueriedTimeStamp = time(nullptr);
    1075             :             }
    1076             :         }
    1077             : #endif
    1078             : 
    1079          18 :         ReadGribData(poGDS->fp, start, subgNum, nullptr, &m_Grib_MetaData);
    1080          18 :         if (m_Grib_MetaData == nullptr)
    1081             :         {
    1082           0 :             m_bHasNoData = false;
    1083           0 :             m_dfNoData = 0;
    1084           0 :             if (pbSuccess)
    1085           0 :                 *pbSuccess = m_bHasNoData;
    1086           0 :             return m_dfNoData;
    1087             :         }
    1088             :     }
    1089             : 
    1090          20 :     if (m_Grib_MetaData->gridAttrib.f_miss == 0)
    1091             :     {
    1092           4 :         m_bHasNoData = false;
    1093           4 :         m_dfNoData = 0;
    1094           4 :         if (pbSuccess)
    1095           4 :             *pbSuccess = m_bHasNoData;
    1096           4 :         return m_dfNoData;
    1097             :     }
    1098             : 
    1099          16 :     if (m_Grib_MetaData->gridAttrib.f_miss == 2)
    1100             :     {
    1101             :         // What TODO?
    1102           0 :         CPLDebug("GRIB", "Secondary missing value also set for band %d : %f",
    1103           0 :                  nBand, m_Grib_MetaData->gridAttrib.missSec);
    1104             :     }
    1105             : 
    1106          16 :     m_bHasNoData = true;
    1107          16 :     m_dfNoData = m_Grib_MetaData->gridAttrib.missPri;
    1108          16 :     if (pbSuccess)
    1109          16 :         *pbSuccess = m_bHasNoData;
    1110          16 :     return m_dfNoData;
    1111             : }
    1112             : 
    1113             : /************************************************************************/
    1114             : /*                            ReadGribData()                            */
    1115             : /************************************************************************/
    1116             : 
    1117         536 : void GRIBRasterBand::ReadGribData(VSILFILE *fp, vsi_l_offset start, int subgNum,
    1118             :                                   double **data, grib_MetaData **metaData)
    1119             : {
    1120             :     // Initialization, for calling the ReadGrib2Record function.
    1121         536 :     sInt4 f_endMsg = 1;  // 1 if we read the last grid in a GRIB message, or we
    1122             :                          // haven't read any messages.
    1123             :     // int subgNum = 0; // The subgrid in the message that we are interested in.
    1124         536 :     sChar f_unit = 2;       // None = 0, English = 1, Metric = 2
    1125         536 :     double majEarth = 0.0;  // -radEarth if < 6000 ignore, otherwise use this
    1126             :                             // to override the radEarth in the GRIB1 or GRIB2
    1127             :                             // message.  Needed because NCEP uses 6371.2 but
    1128             :                             // GRIB1 could only state 6367.47.
    1129         536 :     double minEarth = 0.0;  // -minEarth if < 6000 ignore, otherwise use this
    1130             :                             // to override the minEarth in the GRIB1 or GRIB2
    1131             :                             // message.
    1132         536 :     sChar f_SimpleVer = 4;  // Which version of the simple NDFD Weather table
    1133             :                             // to use. (1 is 6/2003) (2 is 1/2004) (3 is
    1134             :                             // 2/2004) (4 is 11/2004) (default 4)
    1135             :     LatLon lwlf;            // Lower left corner (cookie slicing) -lwlf
    1136             :     LatLon uprt;            // Upper right corner (cookie slicing) -uprt
    1137             :     IS_dataType is;  // Un-parsed meta data for this GRIB2 message. As well
    1138             :                      // as some memory used by the unpacker.
    1139             : 
    1140         536 :     lwlf.lat = -100;  // lat == -100 instructs the GRIB decoder that we don't
    1141             :                       // want a subgrid
    1142             : 
    1143         536 :     IS_Init(&is);
    1144             : 
    1145             :     const char *pszGribNormalizeUnits =
    1146         536 :         CPLGetConfigOption("GRIB_NORMALIZE_UNITS", "YES");
    1147         536 :     if (!CPLTestBool(pszGribNormalizeUnits))
    1148           2 :         f_unit = 0;  // Do not normalize units to metric.
    1149             : 
    1150         536 :     start = FindTrueStart(fp, start);
    1151             :     // Read GRIB message from file position "start".
    1152         536 :     VSIFSeekL(fp, start, SEEK_SET);
    1153         536 :     uInt4 grib_DataLen = 0;  // Size of Grib_Data.
    1154         536 :     *metaData = new grib_MetaData();
    1155         536 :     MetaInit(*metaData);
    1156         536 :     const int simpWWA = 0;  // seem to be unused in degrib
    1157         536 :     ReadGrib2Record(fp, f_unit, data, &grib_DataLen, *metaData, &is, subgNum,
    1158             :                     majEarth, minEarth, f_SimpleVer, simpWWA, &f_endMsg, &lwlf,
    1159             :                     &uprt);
    1160             : 
    1161             :     // No intention to show errors, just swallow it and free the memory.
    1162         536 :     char *errMsg = errSprintf(nullptr);
    1163         536 :     if (errMsg != nullptr)
    1164         339 :         CPLDebug("GRIB", "%s", errMsg);
    1165         536 :     free(errMsg);
    1166         536 :     IS_Free(&is);
    1167         536 : }
    1168             : 
    1169             : /************************************************************************/
    1170             : /*                            UncacheData()                             */
    1171             : /************************************************************************/
    1172             : 
    1173         442 : void GRIBRasterBand::UncacheData()
    1174             : {
    1175         442 :     if (m_Grib_Data)
    1176         184 :         free(m_Grib_Data);
    1177         442 :     m_Grib_Data = nullptr;
    1178         442 :     if (m_Grib_MetaData)
    1179             :     {
    1180         371 :         MetaFree(m_Grib_MetaData);
    1181         371 :         delete m_Grib_MetaData;
    1182             :     }
    1183         442 :     m_Grib_MetaData = nullptr;
    1184         442 : }
    1185             : 
    1186             : /************************************************************************/
    1187             : /*                           ~GRIBRasterBand()                          */
    1188             : /************************************************************************/
    1189             : 
    1190         861 : GRIBRasterBand::~GRIBRasterBand()
    1191             : {
    1192         442 :     if (longFstLevel != nullptr)
    1193         442 :         CPLFree(longFstLevel);
    1194         442 :     UncacheData();
    1195         861 : }
    1196             : 
    1197             : /************************************************************************/
    1198             : /*                           InventoryWrapperGrib                       */
    1199             : /************************************************************************/
    1200             : class InventoryWrapperGrib : public gdal::grib::InventoryWrapper
    1201             : {
    1202             :   public:
    1203         308 :     explicit InventoryWrapperGrib(VSILFILE *fp) : gdal::grib::InventoryWrapper()
    1204             :     {
    1205         308 :         result_ = GRIB2Inventory(fp, &inv_, &inv_len_, 0 /* all messages */,
    1206             :                                  &num_messages_);
    1207         308 :     }
    1208             : 
    1209         616 :     ~InventoryWrapperGrib() override
    1210         308 :     {
    1211         308 :         if (inv_ == nullptr)
    1212           0 :             return;
    1213         728 :         for (uInt4 i = 0; i < inv_len_; i++)
    1214             :         {
    1215         420 :             GRIB2InventoryFree(inv_ + i);
    1216             :         }
    1217         308 :         free(inv_);
    1218         616 :     }
    1219             : };
    1220             : 
    1221             : /************************************************************************/
    1222             : /*                           InventoryWrapperSidecar                    */
    1223             : /************************************************************************/
    1224             : 
    1225             : class InventoryWrapperSidecar : public gdal::grib::InventoryWrapper
    1226             : {
    1227             :   public:
    1228           6 :     explicit InventoryWrapperSidecar(VSILFILE *fp, uint64_t nStartOffset,
    1229             :                                      int64_t nSize)
    1230           6 :         : gdal::grib::InventoryWrapper()
    1231             :     {
    1232           6 :         result_ = -1;
    1233           6 :         VSIFSeekL(fp, 0, SEEK_END);
    1234           6 :         size_t length = static_cast<size_t>(VSIFTellL(fp));
    1235           6 :         if (length > 4 * 1024 * 1024)
    1236           0 :             return;
    1237           6 :         std::string osSidecar;
    1238           6 :         osSidecar.resize(length);
    1239           6 :         VSIFSeekL(fp, 0, SEEK_SET);
    1240           6 :         if (VSIFReadL(&osSidecar[0], length, 1, fp) != 1)
    1241           0 :             return;
    1242             : 
    1243             :         const CPLStringList aosMsgs(
    1244             :             CSLTokenizeString2(osSidecar.c_str(), "\n",
    1245           6 :                                CSLT_PRESERVEQUOTES | CSLT_STRIPLEADSPACES));
    1246           6 :         inv_ = static_cast<inventoryType *>(
    1247           6 :             CPLCalloc(aosMsgs.size(), sizeof(inventoryType)));
    1248             : 
    1249          42 :         for (const char *pszMsg : aosMsgs)
    1250             :         {
    1251             :             // We are parsing
    1252             :             // "msgNum[.subgNum]:start:dontcare:name1:name2:name3" For NOMADS:
    1253             :             // "msgNum[.subgNum]:start:reftime:var:level:time"
    1254             :             const CPLStringList aosTokens(CSLTokenizeString2(
    1255          38 :                 pszMsg, ":", CSLT_PRESERVEQUOTES | CSLT_ALLOWEMPTYTOKENS));
    1256          38 :             CPLStringList aosNum;
    1257             : 
    1258          38 :             if (aosTokens.size() < 6)
    1259           0 :                 goto err_sidecar;
    1260             : 
    1261          38 :             aosNum = CPLStringList(CSLTokenizeString2(aosTokens[0], ".", 0));
    1262          38 :             if (aosNum.size() < 1)
    1263           0 :                 goto err_sidecar;
    1264             : 
    1265             :             // FindMetaData will retrieve the correct version number
    1266             :             char *endptr;
    1267          38 :             strtol(aosNum[0], &endptr, 10);
    1268          38 :             if (*endptr != 0)
    1269           0 :                 goto err_sidecar;
    1270             : 
    1271          38 :             if (aosNum.size() < 2)
    1272          36 :                 inv_[inv_len_].subgNum = 0;
    1273             :             else
    1274             :             {
    1275           2 :                 auto subgNum = strtol(aosNum[1], &endptr, 10);
    1276           2 :                 if (*endptr != 0)
    1277           0 :                     goto err_sidecar;
    1278           2 :                 if (subgNum <= 0 || subgNum > 65536)
    1279           0 :                     goto err_sidecar;
    1280             :                 // .idx file use a 1-based indexing, whereas DEGRIB uses a
    1281             :                 // 0-based one
    1282           2 :                 subgNum--;
    1283           2 :                 inv_[inv_len_].subgNum = static_cast<unsigned short>(subgNum);
    1284             :             }
    1285             : 
    1286          38 :             inv_[inv_len_].start = strtoll(aosTokens[1], &endptr, 10);
    1287          38 :             if (*endptr != 0)
    1288           0 :                 goto err_sidecar;
    1289             : 
    1290          38 :             if (inv_[inv_len_].start < nStartOffset)
    1291           4 :                 continue;
    1292          34 :             if (nSize > 0 && inv_[inv_len_].start >= nStartOffset + nSize)
    1293           2 :                 break;
    1294             : 
    1295          32 :             inv_[inv_len_].start -= nStartOffset;
    1296             : 
    1297          32 :             inv_[inv_len_].unitName = nullptr;
    1298          32 :             inv_[inv_len_].comment = nullptr;
    1299          32 :             inv_[inv_len_].element = nullptr;
    1300          32 :             inv_[inv_len_].shortFstLevel = nullptr;
    1301             :             // This is going into the description field ->
    1302             :             // the only one available before loading the metadata
    1303          32 :             inv_[inv_len_].longFstLevel = VSIStrdup(CPLSPrintf(
    1304             :                 "%s:%s:%s", aosTokens[3], aosTokens[4], aosTokens[5]));
    1305          32 :             ++inv_len_;
    1306             : 
    1307          32 :             continue;
    1308             : 
    1309           0 :         err_sidecar:
    1310           0 :             CPLDebug("GRIB",
    1311             :                      "Failed parsing sidecar entry '%s', "
    1312             :                      "falling back to constructing an inventory",
    1313             :                      pszMsg);
    1314           0 :             return;
    1315             :         }
    1316             : 
    1317           6 :         result_ = inv_len_;
    1318             :     }
    1319             : 
    1320          12 :     ~InventoryWrapperSidecar() override
    1321           6 :     {
    1322           6 :         if (inv_ == nullptr)
    1323           0 :             return;
    1324             : 
    1325          38 :         for (unsigned i = 0; i < inv_len_; i++)
    1326          32 :             VSIFree(inv_[i].longFstLevel);
    1327             : 
    1328           6 :         VSIFree(inv_);
    1329          12 :     }
    1330             : };
    1331             : 
    1332             : /************************************************************************/
    1333             : /* ==================================================================== */
    1334             : /*                              GRIBDataset                             */
    1335             : /* ==================================================================== */
    1336             : /************************************************************************/
    1337             : 
    1338         314 : GRIBDataset::GRIBDataset()
    1339             :     : fp(nullptr), nCachedBytes(0),
    1340             :       // Switch caching strategy once 100 MB threshold is reached.
    1341             :       // Why 100 MB? --> Why not.
    1342         628 :       nCachedBytesThreshold(static_cast<GIntBig>(atoi(
    1343             :                                 CPLGetConfigOption("GRIB_CACHEMAX", "100"))) *
    1344         314 :                             1024 * 1024),
    1345         314 :       bCacheOnlyOneBand(FALSE), nSplitAndSwapColumn(0), poLastUsedBand(nullptr)
    1346             : {
    1347         314 :     adfGeoTransform[0] = 0.0;
    1348         314 :     adfGeoTransform[1] = 1.0;
    1349         314 :     adfGeoTransform[2] = 0.0;
    1350         314 :     adfGeoTransform[3] = 0.0;
    1351         314 :     adfGeoTransform[4] = 0.0;
    1352         314 :     adfGeoTransform[5] = 1.0;
    1353         314 : }
    1354             : 
    1355             : /************************************************************************/
    1356             : /*                            ~GRIBDataset()                             */
    1357             : /************************************************************************/
    1358             : 
    1359         628 : GRIBDataset::~GRIBDataset()
    1360             : 
    1361             : {
    1362         314 :     FlushCache(true);
    1363         314 :     if (fp != nullptr)
    1364         310 :         VSIFCloseL(fp);
    1365         628 : }
    1366             : 
    1367             : /************************************************************************/
    1368             : /*                          GetGeoTransform()                           */
    1369             : /************************************************************************/
    1370             : 
    1371         135 : CPLErr GRIBDataset::GetGeoTransform(double *padfTransform)
    1372             : 
    1373             : {
    1374         135 :     memcpy(padfTransform, adfGeoTransform, sizeof(double) * 6);
    1375         135 :     return CE_None;
    1376             : }
    1377             : 
    1378             : /************************************************************************/
    1379             : /*                                Inventory()                           */
    1380             : /************************************************************************/
    1381             : 
    1382             : std::unique_ptr<gdal::grib::InventoryWrapper>
    1383         310 : GRIBDataset::Inventory(GDALOpenInfo *poOpenInfo)
    1384             : {
    1385         310 :     std::unique_ptr<gdal::grib::InventoryWrapper> pInventories;
    1386             : 
    1387         310 :     VSIFSeekL(fp, 0, SEEK_SET);
    1388         620 :     std::string osSideCarFilename(poOpenInfo->pszFilename);
    1389         310 :     uint64_t nStartOffset = 0;
    1390         310 :     int64_t nSize = -1;
    1391         310 :     if (STARTS_WITH(poOpenInfo->pszFilename, "/vsisubfile/"))
    1392             :     {
    1393           5 :         const char *pszPtr = poOpenInfo->pszFilename + strlen("/vsisubfile/");
    1394           5 :         const char *pszComma = strchr(pszPtr, ',');
    1395           5 :         if (pszComma)
    1396             :         {
    1397             :             const CPLStringList aosTokens(CSLTokenizeString2(
    1398          15 :                 std::string(pszPtr, pszComma - pszPtr).c_str(), "_", 0));
    1399           5 :             if (aosTokens.size() == 2)
    1400             :             {
    1401           5 :                 nStartOffset = std::strtoull(aosTokens[0], nullptr, 10);
    1402           5 :                 nSize = std::strtoll(aosTokens[1], nullptr, 10);
    1403           5 :                 osSideCarFilename = pszComma + 1;
    1404             :             }
    1405             :         }
    1406             :     }
    1407         310 :     osSideCarFilename += ".idx";
    1408         310 :     VSILFILE *fpSideCar = nullptr;
    1409         310 :     if (CPLTestBool(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
    1410         615 :                                          "USE_IDX", "YES")) &&
    1411         305 :         ((fpSideCar = VSIFOpenL(osSideCarFilename.c_str(), "rb")) != nullptr))
    1412             :     {
    1413           6 :         CPLDebug("GRIB", "Reading inventories from sidecar file %s",
    1414             :                  osSideCarFilename.c_str());
    1415             :         // Contains an GRIB2 message inventory of the file.
    1416          12 :         pInventories = std::make_unique<InventoryWrapperSidecar>(
    1417           6 :             fpSideCar, nStartOffset, nSize);
    1418           6 :         if (pInventories->result() <= 0 || pInventories->length() == 0)
    1419           0 :             pInventories = nullptr;
    1420           6 :         VSIFCloseL(fpSideCar);
    1421             : #ifdef BUILD_APPS
    1422           6 :         m_bSideCarIdxUsed = true;
    1423             : #endif
    1424             :     }
    1425             :     else
    1426         304 :         CPLDebug("GRIB", "Failed opening sidecar %s",
    1427             :                  osSideCarFilename.c_str());
    1428             : 
    1429         310 :     if (pInventories == nullptr)
    1430             :     {
    1431         304 :         CPLDebug("GRIB", "Reading inventories from GRIB file %s",
    1432             :                  poOpenInfo->pszFilename);
    1433             :         // Contains an GRIB2 message inventory of the file.
    1434         304 :         pInventories = std::make_unique<InventoryWrapperGrib>(fp);
    1435             :     }
    1436             : 
    1437         620 :     return pInventories;
    1438             : }
    1439             : 
    1440             : /************************************************************************/
    1441             : /*                                Open()                                */
    1442             : /************************************************************************/
    1443             : 
    1444         316 : GDALDataset *GRIBDataset::Open(GDALOpenInfo *poOpenInfo)
    1445             : 
    1446             : {
    1447             : #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    1448             :     // During fuzzing, do not use Identify to reject crazy content.
    1449         316 :     if (!GRIBDriverIdentify(poOpenInfo))
    1450           2 :         return nullptr;
    1451             : #endif
    1452         314 :     if (poOpenInfo->fpL == nullptr)
    1453           0 :         return nullptr;
    1454             : 
    1455             :     // A fast "probe" on the header that is partially read in memory.
    1456         314 :     char *buff = nullptr;
    1457         314 :     uInt4 buffLen = 0;
    1458         314 :     sInt4 sect0[SECT0LEN_WORD] = {0};
    1459         314 :     uInt4 gribLen = 0;
    1460         314 :     int version = 0;
    1461             : 
    1462             :     // grib is not thread safe, make sure not to cause problems
    1463             :     // for other thread safe formats
    1464         628 :     CPLMutexHolderD(&hGRIBMutex);
    1465             : 
    1466         628 :     VSILFILE *memfp = VSIFileFromMemBuffer(nullptr, poOpenInfo->pabyHeader,
    1467         314 :                                            poOpenInfo->nHeaderBytes, FALSE);
    1468         628 :     if (memfp == nullptr ||
    1469         314 :         ReadSECT0(memfp, &buff, &buffLen, -1, sect0, &gribLen, &version) < 0)
    1470             :     {
    1471           0 :         if (memfp != nullptr)
    1472             :         {
    1473           0 :             VSIFCloseL(memfp);
    1474             :         }
    1475           0 :         free(buff);
    1476           0 :         char *errMsg = errSprintf(nullptr);
    1477           0 :         if (errMsg != nullptr && strstr(errMsg, "Ran out of file") == nullptr)
    1478           0 :             CPLDebug("GRIB", "%s", errMsg);
    1479           0 :         free(errMsg);
    1480           0 :         return nullptr;
    1481             :     }
    1482         314 :     VSIFCloseL(memfp);
    1483         314 :     free(buff);
    1484             : 
    1485             :     // Confirm the requested access is supported.
    1486         314 :     if (poOpenInfo->eAccess == GA_Update)
    1487             :     {
    1488           0 :         ReportUpdateNotSupportedByDriver("GRIB");
    1489           0 :         return nullptr;
    1490             :     }
    1491             : 
    1492         314 :     if (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER)
    1493             :     {
    1494           4 :         return OpenMultiDim(poOpenInfo);
    1495             :     }
    1496             : 
    1497             :     // Create a corresponding GDALDataset.
    1498         310 :     GRIBDataset *poDS = new GRIBDataset();
    1499             : 
    1500         310 :     poDS->fp = poOpenInfo->fpL;
    1501         310 :     poOpenInfo->fpL = nullptr;
    1502             : 
    1503             :     // Make an inventory of the GRIB file.
    1504             :     // The inventory does not contain all the information needed for
    1505             :     // creating the RasterBands (especially the x and y size), therefore
    1506             :     // the first GRIB band is also read for some additional metadata.
    1507             :     // The band-data that is read is stored into the first RasterBand,
    1508             :     // simply so that the same portion of the file is not read twice.
    1509             : 
    1510         620 :     auto pInventories = poDS->Inventory(poOpenInfo);
    1511         310 :     if (pInventories->result() <= 0)
    1512             :     {
    1513           9 :         char *errMsg = errSprintf(nullptr);
    1514           9 :         if (errMsg != nullptr)
    1515           8 :             CPLDebug("GRIB", "%s", errMsg);
    1516           9 :         free(errMsg);
    1517             : 
    1518           9 :         CPLError(CE_Failure, CPLE_OpenFailed,
    1519             :                  "%s is a grib file, "
    1520             :                  "but no raster dataset was successfully identified.",
    1521             :                  poOpenInfo->pszFilename);
    1522             :         // Release hGRIBMutex otherwise we'll deadlock with GDALDataset own
    1523             :         // hGRIBMutex.
    1524           9 :         CPLReleaseMutex(hGRIBMutex);
    1525           9 :         delete poDS;
    1526           9 :         CPLAcquireMutex(hGRIBMutex, 1000.0);
    1527           9 :         return nullptr;
    1528             :     }
    1529             : 
    1530             :     // Create band objects.
    1531         720 :     for (uInt4 i = 0; i < pInventories->length(); ++i)
    1532             :     {
    1533         419 :         inventoryType *psInv = pInventories->get(i);
    1534         419 :         GRIBRasterBand *gribBand = nullptr;
    1535         419 :         uInt4 bandNr = i + 1;
    1536             : 
    1537         419 :         if (bandNr == 1)
    1538             :         {
    1539             :             // Important: set DataSet extents before creating first RasterBand
    1540             :             // in it.
    1541         301 :             grib_MetaData *metaData = nullptr;
    1542         301 :             GRIBRasterBand::ReadGribData(poDS->fp, 0, psInv->subgNum, nullptr,
    1543             :                                          &metaData);
    1544         301 :             if (metaData == nullptr || metaData->gds.Nx < 1 ||
    1545         301 :                 metaData->gds.Ny < 1)
    1546             :             {
    1547           0 :                 CPLError(CE_Failure, CPLE_OpenFailed,
    1548             :                          "%s is a grib file, "
    1549             :                          "but no raster dataset was successfully identified.",
    1550             :                          poOpenInfo->pszFilename);
    1551             :                 // Release hGRIBMutex otherwise we'll deadlock with GDALDataset
    1552             :                 // own hGRIBMutex.
    1553           0 :                 CPLReleaseMutex(hGRIBMutex);
    1554           0 :                 delete poDS;
    1555           0 :                 CPLAcquireMutex(hGRIBMutex, 1000.0);
    1556           0 :                 if (metaData != nullptr)
    1557             :                 {
    1558           0 :                     MetaFree(metaData);
    1559           0 :                     delete metaData;
    1560             :                 }
    1561           0 :                 return nullptr;
    1562             :             }
    1563         301 :             psInv->GribVersion = metaData->GribVersion;
    1564             : 
    1565             :             // Set the DataSet's x,y size, georeference and projection from
    1566             :             // the first GRIB band.
    1567         301 :             poDS->SetGribMetaData(metaData);
    1568         301 :             gribBand = new GRIBRasterBand(poDS, bandNr, psInv);
    1569             : 
    1570         301 :             if (psInv->GribVersion == 2)
    1571         294 :                 gribBand->FindPDSTemplateGRIB2();
    1572             : 
    1573         301 :             gribBand->m_Grib_MetaData = metaData;
    1574             :         }
    1575             :         else
    1576             :         {
    1577         118 :             gribBand = new GRIBRasterBand(poDS, bandNr, psInv);
    1578             :         }
    1579         419 :         poDS->SetBand(bandNr, gribBand);
    1580             :     }
    1581             : 
    1582             :     // Initialize any PAM information.
    1583         301 :     poDS->SetDescription(poOpenInfo->pszFilename);
    1584             : 
    1585             :     // Release hGRIBMutex otherwise we'll deadlock with GDALDataset own
    1586             :     // hGRIBMutex.
    1587         301 :     CPLReleaseMutex(hGRIBMutex);
    1588         301 :     poDS->TryLoadXML(poOpenInfo->GetSiblingFiles());
    1589             : 
    1590             :     // Check for external overviews.
    1591         301 :     poDS->oOvManager.Initialize(poDS, poOpenInfo);
    1592         301 :     CPLAcquireMutex(hGRIBMutex, 1000.0);
    1593             : 
    1594         301 :     return poDS;
    1595             : }
    1596             : 
    1597             : /************************************************************************/
    1598             : /*                          GRIBSharedResource                          */
    1599             : /************************************************************************/
    1600             : 
    1601             : struct GRIBSharedResource
    1602             : {
    1603             :     VSILFILE *m_fp = nullptr;
    1604             :     vsi_l_offset m_nOffsetCurData = static_cast<vsi_l_offset>(-1);
    1605             :     std::vector<double> m_adfCurData{};
    1606             :     std::string m_osFilename;
    1607             :     std::shared_ptr<GDALPamMultiDim> m_poPAM{};
    1608             : 
    1609             :     GRIBSharedResource(const std::string &osFilename, VSILFILE *fp);
    1610             :     ~GRIBSharedResource();
    1611             : 
    1612             :     const std::vector<double> &LoadData(vsi_l_offset nOffset, int subgNum);
    1613             : 
    1614          23 :     const std::shared_ptr<GDALPamMultiDim> &GetPAM()
    1615             :     {
    1616          23 :         return m_poPAM;
    1617             :     }
    1618             : };
    1619             : 
    1620           4 : GRIBSharedResource::GRIBSharedResource(const std::string &osFilename,
    1621           4 :                                        VSILFILE *fp)
    1622             :     : m_fp(fp), m_osFilename(osFilename),
    1623           4 :       m_poPAM(std::make_shared<GDALPamMultiDim>(osFilename))
    1624             : {
    1625           4 : }
    1626             : 
    1627           4 : GRIBSharedResource::~GRIBSharedResource()
    1628             : {
    1629           4 :     if (m_fp)
    1630           4 :         VSIFCloseL(m_fp);
    1631           4 : }
    1632             : 
    1633             : /************************************************************************/
    1634             : /*                                GRIBGroup                             */
    1635             : /************************************************************************/
    1636             : 
    1637             : class GRIBArray;
    1638             : 
    1639             : class GRIBGroup final : public GDALGroup
    1640             : {
    1641             :     friend class GRIBArray;
    1642             :     std::shared_ptr<GRIBSharedResource> m_poShared{};
    1643             :     std::vector<std::shared_ptr<GDALMDArray>> m_poArrays{};
    1644             :     std::vector<std::shared_ptr<GDALDimension>> m_dims{};
    1645             :     std::map<std::string, std::shared_ptr<GDALDimension>> m_oMapDims{};
    1646             :     int m_nHorizDimCounter = 0;
    1647             :     std::shared_ptr<GDALGroup> m_memRootGroup{};
    1648             : 
    1649             :   public:
    1650           4 :     explicit GRIBGroup(const std::shared_ptr<GRIBSharedResource> &poShared)
    1651           4 :         : GDALGroup(std::string(), "/"), m_poShared(poShared)
    1652             :     {
    1653             :         std::unique_ptr<GDALDataset> poTmpDS(
    1654           4 :             MEMDataset::CreateMultiDimensional("", nullptr, nullptr));
    1655           4 :         m_memRootGroup = poTmpDS->GetRootGroup();
    1656           4 :     }
    1657             : 
    1658          36 :     void AddArray(const std::shared_ptr<GDALMDArray> &array)
    1659             :     {
    1660          36 :         m_poArrays.emplace_back(array);
    1661          36 :     }
    1662             : 
    1663             :     std::vector<std::string>
    1664             :     GetMDArrayNames(CSLConstList papszOptions) const override;
    1665             :     std::shared_ptr<GDALMDArray>
    1666             :     OpenMDArray(const std::string &osName,
    1667             :                 CSLConstList papszOptions) const override;
    1668             : 
    1669             :     std::vector<std::shared_ptr<GDALDimension>>
    1670           3 :     GetDimensions(CSLConstList) const override
    1671             :     {
    1672           3 :         return m_dims;
    1673             :     }
    1674             : };
    1675             : 
    1676             : /************************************************************************/
    1677             : /*                                GRIBArray                             */
    1678             : /************************************************************************/
    1679             : 
    1680             : class GRIBArray final : public GDALPamMDArray
    1681             : {
    1682             :     std::shared_ptr<GRIBSharedResource> m_poShared;
    1683             :     std::vector<std::shared_ptr<GDALDimension>> m_dims{};
    1684             :     GDALExtendedDataType m_dt = GDALExtendedDataType::Create(GDT_Float64);
    1685             :     std::shared_ptr<OGRSpatialReference> m_poSRS{};
    1686             :     std::vector<vsi_l_offset> m_anOffsets{};
    1687             :     std::vector<int> m_anSubgNums{};
    1688             :     std::vector<double> m_adfTimes{};
    1689             :     std::vector<std::shared_ptr<GDALAttribute>> m_attributes{};
    1690             :     std::string m_osUnit{};
    1691             :     std::vector<GByte> m_abyNoData{};
    1692             : 
    1693             :     GRIBArray(const std::string &osName,
    1694             :               const std::shared_ptr<GRIBSharedResource> &poShared);
    1695             : 
    1696             :   protected:
    1697             :     bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
    1698             :                const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
    1699             :                const GDALExtendedDataType &bufferDataType,
    1700             :                void *pDstBuffer) const override;
    1701             : 
    1702             :   public:
    1703             :     static std::shared_ptr<GRIBArray>
    1704          23 :     Create(const std::string &osName,
    1705             :            const std::shared_ptr<GRIBSharedResource> &poShared)
    1706             :     {
    1707          23 :         auto ar(std::shared_ptr<GRIBArray>(new GRIBArray(osName, poShared)));
    1708          23 :         ar->SetSelf(ar);
    1709          23 :         return ar;
    1710             :     }
    1711             : 
    1712             :     void Init(GRIBGroup *poGroup, GRIBDataset *poDS, GRIBRasterBand *poBand,
    1713             :               inventoryType *psInv);
    1714             :     void ExtendTimeDim(vsi_l_offset nOffset, int subgNum, double dfValidTime);
    1715             :     void Finalize(GRIBGroup *poGroup, inventoryType *psInv);
    1716             : 
    1717           0 :     bool IsWritable() const override
    1718             :     {
    1719           0 :         return false;
    1720             :     }
    1721             : 
    1722           4 :     const std::string &GetFilename() const override
    1723             :     {
    1724           4 :         return m_poShared->m_osFilename;
    1725             :     }
    1726             : 
    1727             :     const std::vector<std::shared_ptr<GDALDimension>> &
    1728          30 :     GetDimensions() const override
    1729             :     {
    1730          30 :         return m_dims;
    1731             :     }
    1732             : 
    1733          11 :     const GDALExtendedDataType &GetDataType() const override
    1734             :     {
    1735          11 :         return m_dt;
    1736             :     }
    1737             : 
    1738           1 :     std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
    1739             :     {
    1740           1 :         return m_poSRS;
    1741             :     }
    1742             : 
    1743             :     std::vector<std::shared_ptr<GDALAttribute>>
    1744          14 :     GetAttributes(CSLConstList) const override
    1745             :     {
    1746          14 :         return m_attributes;
    1747             :     }
    1748             : 
    1749           1 :     const std::string &GetUnit() const override
    1750             :     {
    1751           1 :         return m_osUnit;
    1752             :     }
    1753             : 
    1754           1 :     const void *GetRawNoDataValue() const override
    1755             :     {
    1756           1 :         return m_abyNoData.empty() ? nullptr : m_abyNoData.data();
    1757             :     }
    1758             : };
    1759             : 
    1760             : /************************************************************************/
    1761             : /*                          GetMDArrayNames()                           */
    1762             : /************************************************************************/
    1763             : 
    1764           3 : std::vector<std::string> GRIBGroup::GetMDArrayNames(CSLConstList) const
    1765             : {
    1766           3 :     std::vector<std::string> ret;
    1767          31 :     for (const auto &array : m_poArrays)
    1768             :     {
    1769          28 :         ret.push_back(array->GetName());
    1770             :     }
    1771           3 :     return ret;
    1772             : }
    1773             : 
    1774             : /************************************************************************/
    1775             : /*                            OpenMDArray()                             */
    1776             : /************************************************************************/
    1777             : 
    1778           3 : std::shared_ptr<GDALMDArray> GRIBGroup::OpenMDArray(const std::string &osName,
    1779             :                                                     CSLConstList) const
    1780             : {
    1781          12 :     for (const auto &array : m_poArrays)
    1782             :     {
    1783          11 :         if (array->GetName() == osName)
    1784           2 :             return array;
    1785             :     }
    1786           1 :     return nullptr;
    1787             : }
    1788             : 
    1789             : /************************************************************************/
    1790             : /*                             GRIBArray()                              */
    1791             : /************************************************************************/
    1792             : 
    1793          23 : GRIBArray::GRIBArray(const std::string &osName,
    1794          23 :                      const std::shared_ptr<GRIBSharedResource> &poShared)
    1795             :     : GDALAbstractMDArray("/", osName),
    1796          23 :       GDALPamMDArray("/", osName, poShared->GetPAM()), m_poShared(poShared)
    1797             : {
    1798          23 : }
    1799             : 
    1800             : /************************************************************************/
    1801             : /*                                Init()                                */
    1802             : /************************************************************************/
    1803             : 
    1804          23 : void GRIBArray::Init(GRIBGroup *poGroup, GRIBDataset *poDS,
    1805             :                      GRIBRasterBand *poBand, inventoryType *psInv)
    1806             : {
    1807          23 :     std::shared_ptr<GDALDimension> poDimX;
    1808          23 :     std::shared_ptr<GDALDimension> poDimY;
    1809             : 
    1810             :     double adfGT[6];
    1811          23 :     poDS->GetGeoTransform(adfGT);
    1812             : 
    1813          40 :     for (int i = 1; i <= poGroup->m_nHorizDimCounter; i++)
    1814             :     {
    1815          34 :         std::string osXLookup("X");
    1816          34 :         std::string osYLookup("Y");
    1817          34 :         if (i > 1)
    1818             :         {
    1819          15 :             osXLookup += CPLSPrintf("%d", i);
    1820          15 :             osYLookup += CPLSPrintf("%d", i);
    1821             :         }
    1822          34 :         auto oIterX = poGroup->m_oMapDims.find(osXLookup);
    1823          34 :         auto oIterY = poGroup->m_oMapDims.find(osYLookup);
    1824          34 :         CPLAssert(oIterX != poGroup->m_oMapDims.end());
    1825          34 :         CPLAssert(oIterY != poGroup->m_oMapDims.end());
    1826          34 :         if (oIterX->second->GetSize() ==
    1827          51 :                 static_cast<size_t>(poDS->GetRasterXSize()) &&
    1828          17 :             oIterY->second->GetSize() ==
    1829          17 :                 static_cast<size_t>(poDS->GetRasterYSize()))
    1830             :         {
    1831          17 :             bool bOK = true;
    1832          17 :             auto poVar = oIterX->second->GetIndexingVariable();
    1833          17 :             constexpr double EPSILON = 1e-10;
    1834          17 :             if (poVar)
    1835             :             {
    1836          17 :                 GUInt64 nStart = 0;
    1837          17 :                 size_t nCount = 1;
    1838          17 :                 double dfVal = 0;
    1839          17 :                 poVar->Read(&nStart, &nCount, nullptr, nullptr, m_dt, &dfVal);
    1840          17 :                 if (std::fabs(dfVal - (adfGT[0] + 0.5 * adfGT[1])) >
    1841          17 :                     EPSILON * std::fabs(dfVal))
    1842             :                 {
    1843           0 :                     bOK = false;
    1844             :                 }
    1845             :             }
    1846          17 :             if (bOK)
    1847             :             {
    1848          17 :                 poVar = oIterY->second->GetIndexingVariable();
    1849          17 :                 if (poVar)
    1850             :                 {
    1851          17 :                     GUInt64 nStart = 0;
    1852          17 :                     size_t nCount = 1;
    1853          17 :                     double dfVal = 0;
    1854          17 :                     poVar->Read(&nStart, &nCount, nullptr, nullptr, m_dt,
    1855             :                                 &dfVal);
    1856          17 :                     if (std::fabs(dfVal -
    1857          17 :                                   (adfGT[3] + poDS->nRasterYSize * adfGT[5] -
    1858          17 :                                    0.5 * adfGT[5])) >
    1859          17 :                         EPSILON * std::fabs(dfVal))
    1860             :                     {
    1861           0 :                         bOK = false;
    1862             :                     }
    1863             :                 }
    1864             :             }
    1865          17 :             if (bOK)
    1866             :             {
    1867          17 :                 poDimX = oIterX->second;
    1868          17 :                 poDimY = oIterY->second;
    1869          17 :                 break;
    1870             :             }
    1871             :         }
    1872             :     }
    1873             : 
    1874          23 :     if (!poDimX || !poDimY)
    1875             :     {
    1876           6 :         poGroup->m_nHorizDimCounter++;
    1877             :         {
    1878          12 :             std::string osName("Y");
    1879           6 :             if (poGroup->m_nHorizDimCounter >= 2)
    1880             :             {
    1881           2 :                 osName = CPLSPrintf("Y%d", poGroup->m_nHorizDimCounter);
    1882             :             }
    1883             : 
    1884          12 :             poDimY = std::make_shared<GDALDimensionWeakIndexingVar>(
    1885           6 :                 poGroup->GetFullName(), osName, GDAL_DIM_TYPE_HORIZONTAL_Y,
    1886          18 :                 std::string(), poDS->GetRasterYSize());
    1887           6 :             poGroup->m_oMapDims[osName] = poDimY;
    1888           6 :             poGroup->m_dims.emplace_back(poDimY);
    1889             : 
    1890             :             auto var = GDALMDArrayRegularlySpaced::Create(
    1891             :                 "/", poDimY->GetName(), poDimY,
    1892          12 :                 adfGT[3] + poDS->GetRasterYSize() * adfGT[5], -adfGT[5], 0.5);
    1893           6 :             poDimY->SetIndexingVariable(var);
    1894           6 :             poGroup->AddArray(var);
    1895             :         }
    1896             : 
    1897             :         {
    1898          12 :             std::string osName("X");
    1899           6 :             if (poGroup->m_nHorizDimCounter >= 2)
    1900             :             {
    1901           2 :                 osName = CPLSPrintf("X%d", poGroup->m_nHorizDimCounter);
    1902             :             }
    1903             : 
    1904          12 :             poDimX = std::make_shared<GDALDimensionWeakIndexingVar>(
    1905           6 :                 poGroup->GetFullName(), osName, GDAL_DIM_TYPE_HORIZONTAL_X,
    1906          18 :                 std::string(), poDS->GetRasterXSize());
    1907           6 :             poGroup->m_oMapDims[osName] = poDimX;
    1908           6 :             poGroup->m_dims.emplace_back(poDimX);
    1909             : 
    1910             :             auto var = GDALMDArrayRegularlySpaced::Create(
    1911          12 :                 "/", poDimX->GetName(), poDimX, adfGT[0], adfGT[1], 0.5);
    1912           6 :             poDimX->SetIndexingVariable(var);
    1913           6 :             poGroup->AddArray(var);
    1914             :         }
    1915             :     }
    1916             : 
    1917          23 :     m_dims.emplace_back(poDimY);
    1918          23 :     m_dims.emplace_back(poDimX);
    1919          23 :     if (poDS->m_poSRS.get())
    1920             :     {
    1921          23 :         m_poSRS.reset(poDS->m_poSRS->Clone());
    1922          23 :         if (poDS->m_poSRS->GetDataAxisToSRSAxisMapping() ==
    1923          46 :             std::vector<int>{2, 1})
    1924          22 :             m_poSRS->SetDataAxisToSRSAxisMapping({1, 2});
    1925             :         else
    1926           1 :             m_poSRS->SetDataAxisToSRSAxisMapping({2, 1});
    1927             :     }
    1928             : 
    1929             :     const char *pszGribNormalizeUnits =
    1930          23 :         CPLGetConfigOption("GRIB_NORMALIZE_UNITS", "YES");
    1931          23 :     const bool bMetricUnits = CPLTestBool(pszGribNormalizeUnits);
    1932             : 
    1933          46 :     m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1934          46 :         GetFullName(), "name", psInv->element));
    1935          46 :     m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1936          23 :         GetFullName(), "long_name",
    1937          69 :         ConvertUnitInText(bMetricUnits, psInv->comment)));
    1938          23 :     m_osUnit = ConvertUnitInText(bMetricUnits, psInv->unitName);
    1939          23 :     if (!m_osUnit.empty() && m_osUnit[0] == '[' && m_osUnit.back() == ']')
    1940             :     {
    1941          23 :         m_osUnit = m_osUnit.substr(1, m_osUnit.size() - 2);
    1942             :     }
    1943          46 :     m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1944          46 :         GetFullName(), "first_level", psInv->shortFstLevel));
    1945             : 
    1946          23 :     if (poBand->m_nDisciplineCode >= 0)
    1947             :     {
    1948          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    1949          14 :             GetFullName(), "discipline_code", poBand->m_nDisciplineCode));
    1950             :     }
    1951          23 :     if (!poBand->m_osDisciplineName.empty())
    1952             :     {
    1953          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1954          14 :             GetFullName(), "discipline_name", poBand->m_osDisciplineName));
    1955             :     }
    1956          23 :     if (poBand->m_nCenter >= 0)
    1957             :     {
    1958          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    1959          14 :             GetFullName(), "center_code", poBand->m_nCenter));
    1960             :     }
    1961          23 :     if (!poBand->m_osCenterName.empty())
    1962             :     {
    1963          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1964          14 :             GetFullName(), "center_name", poBand->m_osCenterName));
    1965             :     }
    1966          23 :     if (poBand->m_nSubCenter >= 0)
    1967             :     {
    1968          12 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    1969          12 :             GetFullName(), "subcenter_code", poBand->m_nSubCenter));
    1970             :     }
    1971          23 :     if (!poBand->m_osSubCenterName.empty())
    1972             :     {
    1973           0 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1974           0 :             GetFullName(), "subcenter_name", poBand->m_osSubCenterName));
    1975             :     }
    1976          23 :     if (!poBand->m_osSignRefTimeName.empty())
    1977             :     {
    1978          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1979           7 :             GetFullName(), "signification_of_ref_time",
    1980          14 :             poBand->m_osSignRefTimeName));
    1981             :     }
    1982          23 :     if (!poBand->m_osRefTime.empty())
    1983             :     {
    1984          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1985          14 :             GetFullName(), "reference_time_iso8601", poBand->m_osRefTime));
    1986             :     }
    1987          23 :     if (!poBand->m_osProductionStatus.empty())
    1988             :     {
    1989          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1990          14 :             GetFullName(), "production_status", poBand->m_osProductionStatus));
    1991             :     }
    1992          23 :     if (!poBand->m_osType.empty())
    1993             :     {
    1994          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    1995          14 :             GetFullName(), "type", poBand->m_osType));
    1996             :     }
    1997          23 :     if (poBand->m_nPDTN >= 0)
    1998             :     {
    1999          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    2000           7 :             GetFullName(), "product_definition_template_number",
    2001          14 :             poBand->m_nPDTN));
    2002             :     }
    2003          23 :     if (!poBand->m_anPDSTemplateAssembledValues.empty())
    2004             :     {
    2005          14 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    2006           7 :             GetFullName(), "product_definition_numbers",
    2007          14 :             poBand->m_anPDSTemplateAssembledValues));
    2008             :     }
    2009             : 
    2010          23 :     int bHasNoData = FALSE;
    2011          23 :     double dfNoData = poBand->GetNoDataValue(&bHasNoData);
    2012          23 :     if (bHasNoData)
    2013             :     {
    2014          14 :         m_abyNoData.resize(sizeof(double));
    2015          14 :         memcpy(&m_abyNoData[0], &dfNoData, sizeof(double));
    2016             :     }
    2017          23 : }
    2018             : 
    2019             : /************************************************************************/
    2020             : /*                         ExtendTimeDim()                              */
    2021             : /************************************************************************/
    2022             : 
    2023          24 : void GRIBArray::ExtendTimeDim(vsi_l_offset nOffset, int subgNum,
    2024             :                               double dfValidTime)
    2025             : {
    2026          24 :     m_anOffsets.push_back(nOffset);
    2027          24 :     m_anSubgNums.push_back(subgNum);
    2028          24 :     m_adfTimes.push_back(dfValidTime);
    2029          24 : }
    2030             : 
    2031             : /************************************************************************/
    2032             : /*                           Finalize()                                 */
    2033             : /************************************************************************/
    2034             : 
    2035          23 : void GRIBArray::Finalize(GRIBGroup *poGroup, inventoryType *psInv)
    2036             : {
    2037          23 :     CPLAssert(!m_adfTimes.empty());
    2038          23 :     CPLAssert(m_anOffsets.size() == m_adfTimes.size());
    2039             : 
    2040          23 :     if (m_adfTimes.size() == 1)
    2041             :     {
    2042          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    2043          44 :             GetFullName(), "forecast_time", psInv->foreSec));
    2044          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    2045          44 :             GetFullName(), "forecast_time_unit", "sec"));
    2046          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    2047          44 :             GetFullName(), "reference_time", psInv->refTime));
    2048          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    2049          44 :             GetFullName(), "reference_time_unit", "sec UTC"));
    2050          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeNumeric>(
    2051          44 :             GetFullName(), "validity_time", m_adfTimes[0]));
    2052          44 :         m_attributes.emplace_back(std::make_shared<GDALAttributeString>(
    2053          44 :             GetFullName(), "validity_time_unit", "sec UTC"));
    2054          22 :         return;
    2055             :     }
    2056             : 
    2057           1 :     std::shared_ptr<GDALDimension> poDimTime;
    2058             : 
    2059           3 :     for (const auto &poDim : poGroup->m_dims)
    2060             :     {
    2061           2 :         if (STARTS_WITH(poDim->GetName().c_str(), "TIME") &&
    2062           0 :             poDim->GetSize() == m_adfTimes.size())
    2063             :         {
    2064           0 :             auto poVar = poDim->GetIndexingVariable();
    2065           0 :             if (poVar)
    2066             :             {
    2067           0 :                 GUInt64 nStart = 0;
    2068           0 :                 size_t nCount = 1;
    2069           0 :                 double dfStartTime = 0;
    2070           0 :                 poVar->Read(&nStart, &nCount, nullptr, nullptr, m_dt,
    2071             :                             &dfStartTime);
    2072           0 :                 if (dfStartTime == m_adfTimes[0])
    2073             :                 {
    2074           0 :                     poDimTime = poDim;
    2075           0 :                     break;
    2076             :                 }
    2077             :             }
    2078             :         }
    2079             :     }
    2080             : 
    2081           1 :     if (!poDimTime)
    2082             :     {
    2083           2 :         std::string osName("TIME");
    2084           1 :         int counter = 2;
    2085           1 :         while (poGroup->m_oMapDims.find(osName) != poGroup->m_oMapDims.end())
    2086             :         {
    2087           0 :             osName = CPLSPrintf("TIME%d", counter);
    2088           0 :             counter++;
    2089             :         }
    2090             : 
    2091           2 :         poDimTime = std::make_shared<GDALDimensionWeakIndexingVar>(
    2092           1 :             poGroup->GetFullName(), osName, GDAL_DIM_TYPE_TEMPORAL,
    2093           3 :             std::string(), m_adfTimes.size());
    2094           1 :         poGroup->m_oMapDims[osName] = poDimTime;
    2095           1 :         poGroup->m_dims.emplace_back(poDimTime);
    2096             : 
    2097           1 :         auto var = poGroup->m_memRootGroup->CreateMDArray(
    2098             :             poDimTime->GetName(),
    2099           4 :             std::vector<std::shared_ptr<GDALDimension>>{poDimTime},
    2100           3 :             GDALExtendedDataType::Create(GDT_Float64), nullptr);
    2101           1 :         poDimTime->SetIndexingVariable(var);
    2102           1 :         poGroup->AddArray(var);
    2103             : 
    2104           1 :         GUInt64 nStart = 0;
    2105           1 :         size_t nCount = m_adfTimes.size();
    2106           1 :         var->SetUnit("sec UTC");
    2107           1 :         const GUInt64 anStart[] = {nStart};
    2108           1 :         const size_t anCount[] = {nCount};
    2109           2 :         var->Write(anStart, anCount, nullptr, nullptr, var->GetDataType(),
    2110           1 :                    &m_adfTimes[0]);
    2111           1 :         auto attr = var->CreateAttribute("long_name", {},
    2112           3 :                                          GDALExtendedDataType::CreateString());
    2113           1 :         attr->Write("validity_time");
    2114             :     }
    2115             : 
    2116             : #if defined(__GNUC__)
    2117             : #pragma GCC diagnostic push
    2118             : #pragma GCC diagnostic ignored "-Wnull-dereference"
    2119             : #endif
    2120           1 :     m_dims.insert(m_dims.begin(), poDimTime);
    2121             : #if defined(__GNUC__)
    2122             : #pragma GCC diagnostic pop
    2123             : #endif
    2124           1 :     if (m_poSRS)
    2125             :     {
    2126           2 :         auto mapping = m_poSRS->GetDataAxisToSRSAxisMapping();
    2127           3 :         for (auto &v : mapping)
    2128           2 :             v += 1;
    2129           1 :         m_poSRS->SetDataAxisToSRSAxisMapping(mapping);
    2130             :     }
    2131             : }
    2132             : 
    2133             : /************************************************************************/
    2134             : /*                              LoadData()                              */
    2135             : /************************************************************************/
    2136             : 
    2137           6 : const std::vector<double> &GRIBSharedResource::LoadData(vsi_l_offset nOffset,
    2138             :                                                         int subgNum)
    2139             : {
    2140           6 :     if (m_nOffsetCurData == nOffset)
    2141           1 :         return m_adfCurData;
    2142             : 
    2143           5 :     grib_MetaData *metadata = nullptr;
    2144           5 :     double *data = nullptr;
    2145           5 :     GRIBRasterBand::ReadGribData(m_fp, nOffset, subgNum, &data, &metadata);
    2146           5 :     if (data == nullptr || metadata == nullptr)
    2147             :     {
    2148           0 :         if (metadata != nullptr)
    2149             :         {
    2150           0 :             MetaFree(metadata);
    2151           0 :             delete metadata;
    2152             :         }
    2153           0 :         free(data);
    2154           0 :         m_adfCurData.clear();
    2155           0 :         return m_adfCurData;
    2156             :     }
    2157           5 :     const int nx = metadata->gds.Nx;
    2158           5 :     const int ny = metadata->gds.Ny;
    2159           5 :     MetaFree(metadata);
    2160           5 :     delete metadata;
    2161           5 :     if (nx <= 0 || ny <= 0)
    2162             :     {
    2163           0 :         free(data);
    2164           0 :         m_adfCurData.clear();
    2165           0 :         return m_adfCurData;
    2166             :     }
    2167           5 :     const size_t nPointCount = static_cast<size_t>(nx) * ny;
    2168           5 :     const size_t nByteCount = nPointCount * sizeof(double);
    2169             : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    2170             :     if (nByteCount > static_cast<size_t>(INT_MAX))
    2171             :     {
    2172             :         CPLError(CE_Failure, CPLE_OutOfMemory,
    2173             :                  "Too large memory allocation attempt");
    2174             :         free(data);
    2175             :         m_adfCurData.clear();
    2176             :         return m_adfCurData;
    2177             :     }
    2178             : #endif
    2179             :     try
    2180             :     {
    2181           5 :         m_adfCurData.resize(nPointCount);
    2182             :     }
    2183           0 :     catch (const std::exception &e)
    2184             :     {
    2185           0 :         CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
    2186           0 :         free(data);
    2187           0 :         m_adfCurData.clear();
    2188           0 :         return m_adfCurData;
    2189             :     }
    2190           5 :     m_nOffsetCurData = nOffset;
    2191           5 :     memcpy(&m_adfCurData[0], data, nByteCount);
    2192           5 :     free(data);
    2193           5 :     return m_adfCurData;
    2194             : }
    2195             : 
    2196             : /************************************************************************/
    2197             : /*                             IRead()                                  */
    2198             : /************************************************************************/
    2199             : 
    2200           4 : bool GRIBArray::IRead(const GUInt64 *arrayStartIdx, const size_t *count,
    2201             :                       const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
    2202             :                       const GDALExtendedDataType &bufferDataType,
    2203             :                       void *pDstBuffer) const
    2204             : {
    2205           4 :     const size_t nBufferDTSize(bufferDataType.GetSize());
    2206           4 :     if (m_dims.size() == 2)
    2207             :     {
    2208           2 :         auto &vals = m_poShared->LoadData(m_anOffsets[0], m_anSubgNums[0]);
    2209           2 :         constexpr int Y_IDX = 0;
    2210           2 :         constexpr int X_IDX = 1;
    2211           4 :         if (vals.empty() ||
    2212           2 :             vals.size() != m_dims[Y_IDX]->GetSize() * m_dims[X_IDX]->GetSize())
    2213           0 :             return false;
    2214           2 :         const size_t nWidth(static_cast<size_t>(m_dims[X_IDX]->GetSize()));
    2215           2 :         const bool bDirectCopy = m_dt == bufferDataType &&
    2216           3 :                                  arrayStep[X_IDX] == 1 &&
    2217           1 :                                  bufferStride[X_IDX] == 1;
    2218         150 :         for (size_t j = 0; j < count[Y_IDX]; j++)
    2219             :         {
    2220         148 :             const size_t y = static_cast<size_t>(arrayStartIdx[Y_IDX] +
    2221         148 :                                                  j * arrayStep[Y_IDX]);
    2222         148 :             GByte *pabyDstPtr = static_cast<GByte *>(pDstBuffer) +
    2223         148 :                                 j * bufferStride[Y_IDX] * nBufferDTSize;
    2224         148 :             const size_t x = static_cast<size_t>(arrayStartIdx[X_IDX]);
    2225         148 :             const double *srcPtr = &vals[y * nWidth + x];
    2226         148 :             if (bDirectCopy)
    2227             :             {
    2228          74 :                 memcpy(pabyDstPtr, srcPtr, count[X_IDX] * sizeof(double));
    2229             :             }
    2230             :             else
    2231             :             {
    2232          74 :                 const auto dstPtrInc = bufferStride[X_IDX] * nBufferDTSize;
    2233        4958 :                 for (size_t i = 0; i < count[X_IDX]; i++)
    2234             :                 {
    2235        4884 :                     GDALExtendedDataType::CopyValue(srcPtr, m_dt, pabyDstPtr,
    2236             :                                                     bufferDataType);
    2237        4884 :                     srcPtr += static_cast<std::ptrdiff_t>(arrayStep[X_IDX]);
    2238        4884 :                     pabyDstPtr += dstPtrInc;
    2239             :                 }
    2240             :             }
    2241             :         }
    2242           2 :         return true;
    2243             :     }
    2244             : 
    2245           2 :     constexpr int T_IDX = 0;
    2246           2 :     constexpr int Y_IDX = 1;
    2247           2 :     constexpr int X_IDX = 2;
    2248           2 :     const size_t nWidth(static_cast<size_t>(m_dims[X_IDX]->GetSize()));
    2249           3 :     const bool bDirectCopy = m_dt == bufferDataType && arrayStep[X_IDX] == 1 &&
    2250           1 :                              bufferStride[X_IDX] == 1;
    2251           6 :     for (size_t k = 0; k < count[T_IDX]; k++)
    2252             :     {
    2253           4 :         const size_t tIdx =
    2254           4 :             static_cast<size_t>(arrayStartIdx[T_IDX] + k * arrayStep[T_IDX]);
    2255           4 :         CPLAssert(tIdx < m_anOffsets.size());
    2256             :         auto &vals =
    2257           4 :             m_poShared->LoadData(m_anOffsets[tIdx], m_anSubgNums[tIdx]);
    2258           8 :         if (vals.empty() ||
    2259           4 :             vals.size() != m_dims[Y_IDX]->GetSize() * m_dims[X_IDX]->GetSize())
    2260           0 :             return false;
    2261         520 :         for (size_t j = 0; j < count[Y_IDX]; j++)
    2262             :         {
    2263         516 :             const size_t y = static_cast<size_t>(arrayStartIdx[Y_IDX] +
    2264         516 :                                                  j * arrayStep[Y_IDX]);
    2265         516 :             GByte *pabyDstPtr =
    2266             :                 static_cast<GByte *>(pDstBuffer) +
    2267         516 :                 (k * bufferStride[T_IDX] + j * bufferStride[Y_IDX]) *
    2268             :                     nBufferDTSize;
    2269         516 :             const size_t x = static_cast<size_t>(arrayStartIdx[X_IDX]);
    2270         516 :             const double *srcPtr = &vals[y * nWidth + x];
    2271         516 :             if (bDirectCopy)
    2272             :             {
    2273         258 :                 memcpy(pabyDstPtr, srcPtr, count[X_IDX] * sizeof(double));
    2274             :             }
    2275             :             else
    2276             :             {
    2277         258 :                 const auto dstPtrInc = bufferStride[X_IDX] * nBufferDTSize;
    2278       45924 :                 for (size_t i = 0; i < count[X_IDX]; i++)
    2279             :                 {
    2280       45666 :                     GDALExtendedDataType::CopyValue(srcPtr, m_dt, pabyDstPtr,
    2281             :                                                     bufferDataType);
    2282       45666 :                     srcPtr += static_cast<std::ptrdiff_t>(arrayStep[X_IDX]);
    2283       45666 :                     pabyDstPtr += dstPtrInc;
    2284             :                 }
    2285             :             }
    2286             :         }
    2287             :     }
    2288             : 
    2289           2 :     return true;
    2290             : }
    2291             : 
    2292             : /************************************************************************/
    2293             : /*                          OpenMultiDim()                              */
    2294             : /************************************************************************/
    2295             : 
    2296           4 : GDALDataset *GRIBDataset::OpenMultiDim(GDALOpenInfo *poOpenInfo)
    2297             : 
    2298             : {
    2299             :     auto poShared = std::make_shared<GRIBSharedResource>(
    2300           8 :         poOpenInfo->pszFilename, poOpenInfo->fpL);
    2301           8 :     auto poRootGroup = std::make_shared<GRIBGroup>(poShared);
    2302           4 :     poOpenInfo->fpL = nullptr;
    2303             : 
    2304           4 :     VSIFSeekL(poShared->m_fp, 0, SEEK_SET);
    2305             : 
    2306             :     // Contains an GRIB2 message inventory of the file.
    2307             :     // We can't use the potential .idx file
    2308           8 :     auto pInventories = std::make_unique<InventoryWrapperGrib>(poShared->m_fp);
    2309             : 
    2310           4 :     if (pInventories->result() <= 0)
    2311             :     {
    2312           0 :         char *errMsg = errSprintf(nullptr);
    2313           0 :         if (errMsg != nullptr)
    2314           0 :             CPLDebug("GRIB", "%s", errMsg);
    2315           0 :         free(errMsg);
    2316             : 
    2317           0 :         CPLError(CE_Failure, CPLE_OpenFailed,
    2318             :                  "%s is a grib file, "
    2319             :                  "but no raster dataset was successfully identified.",
    2320             :                  poOpenInfo->pszFilename);
    2321           0 :         return nullptr;
    2322             :     }
    2323             : 
    2324             :     // Create band objects.
    2325           4 :     GRIBDataset *poDS = new GRIBDataset();
    2326           4 :     poDS->fp = poShared->m_fp;
    2327             : 
    2328           4 :     std::shared_ptr<GRIBArray> poArray;
    2329           8 :     std::set<std::string> oSetArrayNames;
    2330           8 :     std::string osElement;
    2331           8 :     std::string osShortFstLevel;
    2332           4 :     double dfRefTime = 0;
    2333           4 :     double dfForecastTime = 0;
    2334          28 :     for (uInt4 i = 0; i < pInventories->length(); ++i)
    2335             :     {
    2336          24 :         inventoryType *psInv = pInventories->get(i);
    2337          24 :         uInt4 bandNr = i + 1;
    2338             : 
    2339             :         // GRIB messages can be preceded by "garbage". GRIB2Inventory()
    2340             :         // does not return the offset to the real start of the message
    2341             :         GByte abyHeader[1024 + 1];
    2342          24 :         VSIFSeekL(poShared->m_fp, psInv->start, SEEK_SET);
    2343             :         size_t nRead =
    2344          24 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader) - 1, poShared->m_fp);
    2345          24 :         abyHeader[nRead] = 0;
    2346             :         // Find the real offset of the fist message
    2347          24 :         const char *pasHeader = reinterpret_cast<char *>(abyHeader);
    2348          24 :         int nOffsetFirstMessage = 0;
    2349         144 :         for (int j = 0; j < poOpenInfo->nHeaderBytes - 3; j++)
    2350             :         {
    2351         144 :             if (STARTS_WITH_CI(pasHeader + j, "GRIB")
    2352             : #ifdef ENABLE_TDLP
    2353             :                 || STARTS_WITH_CI(pasHeader + j, "TDLP")
    2354             : #endif
    2355             :             )
    2356             :             {
    2357          24 :                 nOffsetFirstMessage = j;
    2358          24 :                 break;
    2359             :             }
    2360             :         }
    2361          24 :         psInv->start += nOffsetFirstMessage;
    2362             : 
    2363          46 :         if (poArray == nullptr || osElement != psInv->element ||
    2364          46 :             osShortFstLevel != psInv->shortFstLevel ||
    2365           1 :             !((dfRefTime == psInv->refTime &&
    2366           1 :                dfForecastTime != psInv->foreSec) ||
    2367           0 :               (dfRefTime != psInv->refTime &&
    2368           0 :                dfForecastTime == psInv->foreSec)))
    2369             :         {
    2370          23 :             if (poArray)
    2371             :             {
    2372          19 :                 poArray->Finalize(poRootGroup.get(), pInventories->get(i - 1));
    2373          19 :                 poRootGroup->AddArray(poArray);
    2374             :             }
    2375             : 
    2376          23 :             grib_MetaData *metaData = nullptr;
    2377          23 :             GRIBRasterBand::ReadGribData(poShared->m_fp, psInv->start,
    2378          23 :                                          psInv->subgNum, nullptr, &metaData);
    2379          23 :             if (metaData == nullptr || metaData->gds.Nx < 1 ||
    2380          23 :                 metaData->gds.Ny < 1)
    2381             :             {
    2382           0 :                 CPLError(CE_Failure, CPLE_OpenFailed,
    2383             :                          "%s is a grib file, "
    2384             :                          "but no raster dataset was successfully identified.",
    2385             :                          poOpenInfo->pszFilename);
    2386             : 
    2387           0 :                 if (metaData != nullptr)
    2388             :                 {
    2389           0 :                     MetaFree(metaData);
    2390           0 :                     delete metaData;
    2391             :                 }
    2392           0 :                 poDS->fp = nullptr;
    2393           0 :                 CPLReleaseMutex(hGRIBMutex);
    2394           0 :                 delete poDS;
    2395           0 :                 CPLAcquireMutex(hGRIBMutex, 1000.0);
    2396           0 :                 return nullptr;
    2397             :             }
    2398          23 :             psInv->GribVersion = metaData->GribVersion;
    2399             : 
    2400             :             // Set the DataSet's x,y size, georeference and projection from
    2401             :             // the first GRIB band.
    2402          23 :             poDS->SetGribMetaData(metaData);
    2403             : 
    2404             :             // coverity[tainted_data]
    2405          46 :             GRIBRasterBand gribBand(poDS, bandNr, psInv);
    2406          23 :             if (psInv->GribVersion == 2)
    2407           7 :                 gribBand.FindPDSTemplateGRIB2();
    2408          23 :             osElement = psInv->element;
    2409          23 :             osShortFstLevel = psInv->shortFstLevel;
    2410          23 :             dfRefTime = psInv->refTime;
    2411          23 :             dfForecastTime = psInv->foreSec;
    2412             : 
    2413          46 :             std::string osRadix(osElement + '_' + osShortFstLevel);
    2414          46 :             std::string osName(osRadix);
    2415          23 :             int nCounter = 2;
    2416          23 :             while (oSetArrayNames.find(osName) != oSetArrayNames.end())
    2417             :             {
    2418           0 :                 osName = osRadix + CPLSPrintf("_%d", nCounter);
    2419           0 :                 nCounter++;
    2420             :             }
    2421          23 :             oSetArrayNames.insert(osName);
    2422          23 :             poArray = GRIBArray::Create(osName, poShared);
    2423          23 :             poArray->Init(poRootGroup.get(), poDS, &gribBand, psInv);
    2424          23 :             poArray->ExtendTimeDim(psInv->start, psInv->subgNum,
    2425             :                                    psInv->validTime);
    2426             : 
    2427          23 :             MetaFree(metaData);
    2428          23 :             delete metaData;
    2429             :         }
    2430             :         else
    2431             :         {
    2432           1 :             poArray->ExtendTimeDim(psInv->start, psInv->subgNum,
    2433             :                                    psInv->validTime);
    2434             :         }
    2435             :     }
    2436             : 
    2437           4 :     if (poArray)
    2438             :     {
    2439           8 :         poArray->Finalize(poRootGroup.get(),
    2440           4 :                           pInventories->get(pInventories->length() - 1));
    2441           4 :         poRootGroup->AddArray(poArray);
    2442             :     }
    2443             : 
    2444           4 :     poDS->fp = nullptr;
    2445           4 :     poDS->m_poRootGroup = poRootGroup;
    2446             : 
    2447           4 :     poDS->SetDescription(poOpenInfo->pszFilename);
    2448             : 
    2449             :     // Release hGRIBMutex otherwise we'll deadlock with GDALDataset own
    2450             :     // hGRIBMutex.
    2451           4 :     CPLReleaseMutex(hGRIBMutex);
    2452           4 :     poDS->TryLoadXML();
    2453           4 :     CPLAcquireMutex(hGRIBMutex, 1000.0);
    2454             : 
    2455           4 :     return poDS;
    2456             : }
    2457             : 
    2458             : /************************************************************************/
    2459             : /*                            SetMetadata()                             */
    2460             : /************************************************************************/
    2461             : 
    2462         324 : void GRIBDataset::SetGribMetaData(grib_MetaData *meta)
    2463             : {
    2464         324 :     nRasterXSize = meta->gds.Nx;
    2465         324 :     nRasterYSize = meta->gds.Ny;
    2466             : 
    2467             :     // Image projection.
    2468         324 :     OGRSpatialReference oSRS;
    2469         324 :     oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2470             : 
    2471         324 :     switch (meta->gds.projType)
    2472             :     {
    2473         134 :         case GS3_LATLON:
    2474             :         case GS3_GAUSSIAN_LATLON:
    2475             :             // No projection, only latlon system (geographic).
    2476         134 :             break;
    2477           2 :         case GS3_ROTATED_LATLON:
    2478             :             // will apply pole rotation afterwards
    2479           2 :             break;
    2480          26 :         case GS3_MERCATOR:
    2481          26 :             if (meta->gds.orientLon == 0.0)
    2482             :             {
    2483          26 :                 if (meta->gds.meshLat == 0.0)
    2484           5 :                     oSRS.SetMercator(0.0, 0.0, 1.0, 0.0, 0.0);
    2485             :                 else
    2486          21 :                     oSRS.SetMercator2SP(meta->gds.meshLat, 0.0, 0.0, 0.0, 0.0);
    2487             :             }
    2488             :             else
    2489             :             {
    2490           0 :                 CPLError(CE_Warning, CPLE_NotSupported,
    2491             :                          "Orientation of the grid != 0 not supported");
    2492           0 :                 return;
    2493             :             }
    2494          26 :             break;
    2495         133 :         case GS3_TRANSVERSE_MERCATOR:
    2496         133 :             oSRS.SetTM(meta->gds.latitude_of_origin,
    2497             :                        Lon360to180(meta->gds.central_meridian),
    2498         133 :                        std::abs(meta->gds.scaleLat1 - 0.9996) < 1e8
    2499             :                            ? 0.9996
    2500             :                            : meta->gds.scaleLat1,
    2501             :                        meta->gds.x0, meta->gds.y0);
    2502         133 :             break;
    2503           9 :         case GS3_POLAR:
    2504           9 :             oSRS.SetPS(meta->gds.meshLat, meta->gds.orientLon, 1.0, 0.0, 0.0);
    2505           9 :             break;
    2506           9 :         case GS3_LAMBERT:
    2507           9 :             oSRS.SetLCC(meta->gds.scaleLat1, meta->gds.scaleLat2,
    2508             :                         meta->gds.meshLat, Lon360to180(meta->gds.orientLon),
    2509             :                         0.0, 0.0);
    2510           9 :             break;
    2511           5 :         case GS3_ALBERS_EQUAL_AREA:
    2512           5 :             oSRS.SetACEA(meta->gds.scaleLat1, meta->gds.scaleLat2,
    2513             :                          meta->gds.meshLat, Lon360to180(meta->gds.orientLon),
    2514             :                          0.0, 0.0);
    2515           5 :             break;
    2516             : 
    2517           0 :         case GS3_ORTHOGRAPHIC:
    2518             : 
    2519             :             // oSRS.SetOrthographic( 0.0, meta->gds.orientLon,
    2520             :             //                       meta->gds.lon2, meta->gds.lat2);
    2521             : 
    2522             :             // oSRS.SetGEOS( meta->gds.orientLon, meta->gds.stretchFactor,
    2523             :             //               meta->gds.lon2, meta->gds.lat2);
    2524             : 
    2525             :             // TODO: Hardcoded for now. How to parse the meta->gds section?
    2526           0 :             oSRS.SetGEOS(0, 35785831, 0, 0);
    2527           0 :             break;
    2528           6 :         case GS3_LAMBERT_AZIMUTHAL:
    2529           6 :             oSRS.SetLAEA(meta->gds.meshLat, Lon360to180(meta->gds.orientLon),
    2530             :                          0.0, 0.0);
    2531           6 :             break;
    2532             : 
    2533           0 :         case GS3_EQUATOR_EQUIDIST:
    2534           0 :             break;
    2535           0 :         case GS3_AZIMUTH_RANGE:
    2536           0 :             break;
    2537             :     }
    2538             : 
    2539         324 :     if (oSRS.IsProjected())
    2540             :     {
    2541         188 :         oSRS.SetLinearUnits("Metre", 1.0);
    2542             :     }
    2543             : 
    2544         324 :     const bool bHaveEarthModel =
    2545         324 :         meta->gds.majEarth > 0.0 && meta->gds.minEarth > 0.0;
    2546             :     // In meters.
    2547             :     const double a = bHaveEarthModel
    2548         324 :                          ? meta->gds.majEarth * 1.0e3
    2549           2 :                          : CPLAtof(CPLGetConfigOption("GRIB_DEFAULT_SEMI_MAJOR",
    2550         324 :                                                       "6377563.396"));
    2551             :     const double b =
    2552             :         bHaveEarthModel
    2553         326 :             ? meta->gds.minEarth * 1.0e3
    2554           2 :             : (meta->gds.f_sphere
    2555           2 :                    ? a
    2556           0 :                    : CPLAtof(CPLGetConfigOption("GRIB_DEFAULT_SEMI_MINOR",
    2557         324 :                                                 "6356256.910")));
    2558         324 :     if (meta->gds.majEarth == 0 || meta->gds.minEarth == 0)
    2559             :     {
    2560           0 :         CPLDebug("GRIB", "No earth model. Assuming a=%f and b=%f", a, b);
    2561             :     }
    2562         324 :     else if (meta->gds.majEarth < 0 || meta->gds.minEarth < 0)
    2563             :     {
    2564             :         const char *pszUseDefaultSpheroid =
    2565           2 :             CPLGetConfigOption("GRIB_USE_DEFAULT_SPHEROID", nullptr);
    2566           2 :         if (!pszUseDefaultSpheroid)
    2567             :         {
    2568           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    2569             :                      "The GRIB file contains invalid values for the spheroid. "
    2570             :                      "You may set the GRIB_USE_DEFAULT_SPHEROID configuration "
    2571             :                      "option to YES to use a default spheroid with "
    2572             :                      "a=%f and b=%f",
    2573             :                      a, b);
    2574           1 :             return;
    2575             :         }
    2576           1 :         else if (!CPLTestBool(pszUseDefaultSpheroid))
    2577             :         {
    2578           0 :             return;
    2579             :         }
    2580           1 :         CPLDebug("GRIB", "Invalid earth model. Assuming a=%f and b=%f", a, b);
    2581             :     }
    2582             : 
    2583         323 :     if (meta->gds.f_sphere || (a == b))
    2584             :     {
    2585          88 :         oSRS.SetGeogCS("Coordinate System imported from GRIB file", nullptr,
    2586             :                        "Sphere", a, 0.0);
    2587             :     }
    2588             :     else
    2589             :     {
    2590         235 :         const double fInv = a / (a - b);
    2591         335 :         if (std::abs(a - 6378137.0) < 0.01 &&
    2592         100 :             std::abs(fInv - 298.257223563) < 1e-9)  // WGS84
    2593             :         {
    2594          98 :             if (meta->gds.projType == GS3_LATLON)
    2595          68 :                 oSRS.SetFromUserInput(SRS_WKT_WGS84_LAT_LONG);
    2596             :             else
    2597             :             {
    2598          30 :                 oSRS.SetGeogCS("Coordinate System imported from GRIB file",
    2599             :                                "WGS_1984", "WGS 84", 6378137., 298.257223563);
    2600             :             }
    2601             :         }
    2602         139 :         else if (std::abs(a - 6378137.0) < 0.01 &&
    2603           2 :                  std::abs(fInv - 298.257222101) < 1e-9)  // GRS80
    2604             :         {
    2605           2 :             oSRS.SetGeogCS("Coordinate System imported from GRIB file", nullptr,
    2606             :                            "GRS80", 6378137., 298.257222101);
    2607             :         }
    2608             :         else
    2609             :         {
    2610         135 :             oSRS.SetGeogCS("Coordinate System imported from GRIB file", nullptr,
    2611             :                            "Spheroid imported from GRIB file", a, fInv);
    2612             :         }
    2613             :     }
    2614             : 
    2615         323 :     if (meta->gds.projType == GS3_ROTATED_LATLON)
    2616             :     {
    2617           2 :         oSRS.SetDerivedGeogCRSWithPoleRotationGRIBConvention(
    2618             :             oSRS.GetName(), meta->gds.southLat, Lon360to180(meta->gds.southLon),
    2619             :             meta->gds.angleRotate);
    2620             :     }
    2621             : 
    2622         323 :     OGRSpatialReference oLL;  // Construct the "geographic" part of oSRS.
    2623         323 :     oLL.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2624         323 :     oLL.CopyGeogCSFrom(&oSRS);
    2625             : 
    2626         323 :     double rMinX = 0.0;
    2627         323 :     double rMaxY = 0.0;
    2628         323 :     double rPixelSizeX = 0.0;
    2629         323 :     double rPixelSizeY = 0.0;
    2630         323 :     bool bError = false;
    2631         323 :     if (meta->gds.projType == GS3_ORTHOGRAPHIC)
    2632             :     {
    2633             :         // This is what should work, but it doesn't. Dx seems to have an
    2634             :         // inverse relation with pixel size.
    2635             :         // rMinX = -meta->gds.Dx * (meta->gds.Nx / 2);
    2636             :         // rMaxY = meta->gds.Dy * (meta->gds.Ny / 2);
    2637             :         // Hardcoded for now, assumption: GEOS projection, full disc (like MSG).
    2638           0 :         const double geosExtentInMeters = 11137496.552;
    2639           0 :         rMinX = -(geosExtentInMeters / 2);
    2640           0 :         rMaxY = geosExtentInMeters / 2;
    2641           0 :         rPixelSizeX = geosExtentInMeters / meta->gds.Nx;
    2642           0 :         rPixelSizeY = geosExtentInMeters / meta->gds.Ny;
    2643             :     }
    2644         323 :     else if (meta->gds.projType == GS3_TRANSVERSE_MERCATOR)
    2645             :     {
    2646         132 :         rMinX = meta->gds.x1;
    2647         132 :         rMaxY = meta->gds.y2;
    2648         132 :         rPixelSizeX = meta->gds.Dx;
    2649         132 :         rPixelSizeY = meta->gds.Dy;
    2650             :     }
    2651         191 :     else if (oSRS.IsProjected() && meta->gds.projType != GS3_ROTATED_LATLON)
    2652             :     {
    2653             :         // Longitude in degrees, to be transformed to meters (or degrees in
    2654             :         // case of latlon).
    2655          55 :         rMinX = meta->gds.lon1;
    2656             :         // Latitude in degrees, to be transformed to meters.
    2657          55 :         double dfGridOriY = meta->gds.lat1;
    2658             : 
    2659          55 :         if (m_poSRS == nullptr || m_poLL == nullptr ||
    2660          55 :             !m_poSRS->IsSame(&oSRS) || !m_poLL->IsSame(&oLL))
    2661             :         {
    2662         110 :             m_poCT = std::unique_ptr<OGRCoordinateTransformation>(
    2663          55 :                 OGRCreateCoordinateTransformation(&(oLL), &(oSRS)));
    2664             :         }
    2665             : 
    2666             :         // Transform it to meters.
    2667          55 :         if ((m_poCT != nullptr) && m_poCT->Transform(1, &rMinX, &dfGridOriY))
    2668             :         {
    2669          55 :             if (meta->gds.scan == GRIB2BIT_2)  // Y is minY, GDAL wants maxY.
    2670             :             {
    2671          55 :                 const char *pszConfigOpt = CPLGetConfigOption(
    2672             :                     "GRIB_LATITUDE_OF_FIRST_GRID_POINT_IS_SOUTHERN_MOST",
    2673             :                     nullptr);
    2674             :                 bool bLatOfFirstPointIsSouthernMost =
    2675          55 :                     !pszConfigOpt || CPLTestBool(pszConfigOpt);
    2676             : 
    2677             :                 // Hack for a file called MANAL_2023030103.grb2 that
    2678             :                 // uses LCC and has Latitude of false origin = 30
    2679             :                 // Longitude of false origin = 140
    2680             :                 // Latitude of 1st standard parallel = 60
    2681             :                 // Latitude of 2nd standard parallel = 30
    2682             :                 // but whose (meta->gds.lon1, meta->gds.lat1) qualifies the
    2683             :                 // northern-most point of the grid and not the bottom-most one
    2684             :                 // as it should given the scan == GRIB2BIT_2
    2685          55 :                 if (!pszConfigOpt && meta->gds.projType == GS3_LAMBERT &&
    2686           9 :                     std::fabs(meta->gds.scaleLat1 - 60) <= 1e-8 &&
    2687           1 :                     std::fabs(meta->gds.scaleLat2 - 30) <= 1e-8 &&
    2688         111 :                     std::fabs(meta->gds.meshLat - 30) <= 1e-8 &&
    2689           1 :                     std::fabs(Lon360to180(meta->gds.orientLon) - 140) <= 1e-8)
    2690             :                 {
    2691           1 :                     double dfXCenterProj = Lon360to180(meta->gds.orientLon);
    2692           1 :                     double dfYCenterProj = meta->gds.meshLat;
    2693           1 :                     if (m_poCT->Transform(1, &dfXCenterProj, &dfYCenterProj))
    2694             :                     {
    2695           1 :                         double dfXCenterGridNominal =
    2696           1 :                             rMinX + nRasterXSize * meta->gds.Dx / 2;
    2697           1 :                         double dfYCenterGridNominal =
    2698           1 :                             dfGridOriY + nRasterYSize * meta->gds.Dy / 2;
    2699           1 :                         double dfXCenterGridBuggy = dfXCenterGridNominal;
    2700           1 :                         double dfYCenterGridBuggy =
    2701           1 :                             dfGridOriY - nRasterYSize * meta->gds.Dy / 2;
    2702           5 :                         const auto SQR = [](double x) { return x * x; };
    2703           1 :                         if (SQR(dfXCenterGridBuggy - dfXCenterProj) +
    2704           1 :                                 SQR(dfYCenterGridBuggy - dfYCenterProj) <
    2705           1 :                             SQR(10) *
    2706           2 :                                 (SQR(dfXCenterGridNominal - dfXCenterProj) +
    2707           1 :                                  SQR(dfYCenterGridNominal - dfYCenterProj)))
    2708             :                         {
    2709           1 :                             CPLError(
    2710             :                                 CE_Warning, CPLE_AppDefined,
    2711             :                                 "Likely buggy grid registration for GRIB2 "
    2712             :                                 "product: heuristics shows that the "
    2713             :                                 "latitudeOfFirstGridPoint is likely to qualify "
    2714             :                                 "the latitude of the northern-most grid point "
    2715             :                                 "instead of the southern-most grid point as "
    2716             :                                 "expected. Please report to data producer. "
    2717             :                                 "This heuristics can be disabled by setting "
    2718             :                                 "the "
    2719             :                                 "GRIB_LATITUDE_OF_FIRST_GRID_POINT_IS_SOUTHERN_"
    2720             :                                 "MOST configuration option to YES.");
    2721           1 :                             bLatOfFirstPointIsSouthernMost = false;
    2722             :                         }
    2723             :                     }
    2724             :                 }
    2725          55 :                 if (bLatOfFirstPointIsSouthernMost)
    2726             :                 {
    2727             :                     // -1 because we GDAL needs the coordinates of the centre of
    2728             :                     // the pixel.
    2729          54 :                     rMaxY = dfGridOriY + (meta->gds.Ny - 1) * meta->gds.Dy;
    2730             :                 }
    2731             :                 else
    2732             :                 {
    2733           1 :                     rMaxY = dfGridOriY;
    2734             :                 }
    2735             :             }
    2736             :             else
    2737             :             {
    2738           0 :                 rMaxY = dfGridOriY;
    2739             :             }
    2740          55 :             rPixelSizeX = meta->gds.Dx;
    2741          55 :             rPixelSizeY = meta->gds.Dy;
    2742             :         }
    2743             :         else
    2744             :         {
    2745           0 :             rMinX = 0.0;
    2746             :             // rMaxY = 0.0;
    2747             : 
    2748           0 :             rPixelSizeX = 1.0;
    2749           0 :             rPixelSizeY = -1.0;
    2750             : 
    2751           0 :             bError = true;
    2752           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2753             :                      "Unable to perform coordinate transformations, so the "
    2754             :                      "correct projected geotransform could not be deduced "
    2755             :                      "from the lat/long control points.  "
    2756             :                      "Defaulting to ungeoreferenced.");
    2757             :         }
    2758             :     }
    2759             :     else
    2760             :     {
    2761             :         // Longitude in degrees, to be transformed to meters (or degrees in
    2762             :         // case of latlon).
    2763         136 :         rMinX = meta->gds.lon1;
    2764             :         // Latitude in degrees, to be transformed to meters.
    2765         136 :         rMaxY = meta->gds.lat1;
    2766             : 
    2767         136 :         double rMinY = meta->gds.lat2;
    2768         136 :         double rMaxX = meta->gds.lon2;
    2769         136 :         if (meta->gds.lat2 > rMaxY)
    2770             :         {
    2771         105 :             rMaxY = meta->gds.lat2;
    2772         105 :             rMinY = meta->gds.lat1;
    2773             :         }
    2774             : 
    2775         136 :         if (meta->gds.Nx == 1)
    2776          16 :             rPixelSizeX = meta->gds.Dx;
    2777         120 :         else if (meta->gds.lon1 > meta->gds.lon2)
    2778          13 :             rPixelSizeX = (360.0 - (meta->gds.lon1 - meta->gds.lon2)) /
    2779          13 :                           (meta->gds.Nx - 1);
    2780             :         else
    2781         107 :             rPixelSizeX =
    2782         107 :                 (meta->gds.lon2 - meta->gds.lon1) / (meta->gds.Nx - 1);
    2783             : 
    2784         136 :         if (meta->gds.Ny == 1)
    2785          17 :             rPixelSizeY = meta->gds.Dy;
    2786             :         else
    2787         119 :             rPixelSizeY = (rMaxY - rMinY) / (meta->gds.Ny - 1);
    2788             : 
    2789             :         // Do some sanity checks for cases that can't be handled by the above
    2790             :         // pixel size corrections. GRIB1 has a minimum precision of 0.001
    2791             :         // for latitudes and longitudes, so we'll allow a bit higher than that.
    2792         136 :         if (rPixelSizeX < 0 || fabs(rPixelSizeX - meta->gds.Dx) > 0.002)
    2793           0 :             rPixelSizeX = meta->gds.Dx;
    2794             : 
    2795         136 :         if (rPixelSizeY < 0 || fabs(rPixelSizeY - meta->gds.Dy) > 0.002)
    2796           0 :             rPixelSizeY = meta->gds.Dy;
    2797             : 
    2798             :         // GRIB2 files have longitudes in the [0-360] range
    2799             :         // Shift them to the traditional [-180,180] longitude range
    2800             :         // See https://github.com/OSGeo/gdal/issues/4524
    2801         194 :         if ((rMinX + rPixelSizeX >= 180 || rMaxX - rPixelSizeX >= 180) &&
    2802          58 :             CPLTestBool(
    2803             :                 CPLGetConfigOption("GRIB_ADJUST_LONGITUDE_RANGE", "YES")))
    2804             :         {
    2805          56 :             if (rPixelSizeX * nRasterXSize > 360 + rPixelSizeX / 4)
    2806           0 :                 CPLDebug("GRIB", "Cannot properly handle GRIB2 files with "
    2807             :                                  "overlaps and 0-360 longitudes");
    2808          56 :             else if (rMinX == 180)
    2809             :             {
    2810             :                 // Case of https://github.com/OSGeo/gdal/issues/10655
    2811           2 :                 CPLDebug("GRIB", "Shifting longitudes from %lf:%lf to %lf:%lf",
    2812             :                          rMinX, rMaxX, -180.0, Lon360to180(rMaxX));
    2813           2 :                 rMinX = -180;
    2814             :             }
    2815          54 :             else if (fabs(360 - rPixelSizeX * nRasterXSize) < rPixelSizeX / 4 &&
    2816          23 :                      rMinX <= 180 && meta->gds.projType == GS3_LATLON)
    2817             :             {
    2818             :                 // Find the first row number east of the antimeridian
    2819           8 :                 const int nSplitAndSwapColumnCandidate =
    2820           8 :                     static_cast<int>(ceil((180 - rMinX) / rPixelSizeX));
    2821           8 :                 if (nSplitAndSwapColumnCandidate < nRasterXSize)
    2822             :                 {
    2823           8 :                     nSplitAndSwapColumn = nSplitAndSwapColumnCandidate;
    2824           8 :                     CPLDebug("GRIB",
    2825             :                              "Rewrapping around the antimeridian at column %d",
    2826             :                              nSplitAndSwapColumn);
    2827           8 :                     rMinX = -180;
    2828           8 :                 }
    2829             :             }
    2830          46 :             else if (Lon360to180(rMinX) > Lon360to180(rMaxX))
    2831             :             {
    2832           2 :                 CPLDebug("GRIB", "GRIB with 0-360 longitudes spanning across "
    2833             :                                  "the antimeridian");
    2834           2 :                 rMinX = Lon360to180(rMinX);
    2835             :             }
    2836             :             else
    2837             :             {
    2838          44 :                 CPLDebug("GRIB", "Shifting longitudes from %lf:%lf to %lf:%lf",
    2839             :                          rMinX, rMaxX, Lon360to180(rMinX), Lon360to180(rMaxX));
    2840          44 :                 rMinX = Lon360to180(rMinX);
    2841             :             }
    2842             :         }
    2843             :     }
    2844             : 
    2845             :     // https://gdal.org/user/raster_data_model.html :
    2846             :     //   we need the top left corner of the top left pixel.
    2847             :     //   At the moment we have the center of the pixel.
    2848         323 :     rMinX -= rPixelSizeX / 2;
    2849         323 :     rMaxY += rPixelSizeY / 2;
    2850             : 
    2851         323 :     adfGeoTransform[0] = rMinX;
    2852         323 :     adfGeoTransform[3] = rMaxY;
    2853         323 :     adfGeoTransform[1] = rPixelSizeX;
    2854         323 :     adfGeoTransform[5] = -rPixelSizeY;
    2855             : 
    2856         323 :     if (bError)
    2857           0 :         m_poSRS.reset();
    2858             :     else
    2859         323 :         m_poSRS.reset(oSRS.Clone());
    2860         323 :     m_poLL = std::unique_ptr<OGRSpatialReference>(oLL.Clone());
    2861             : }
    2862             : 
    2863             : /************************************************************************/
    2864             : /*                       GDALDeregister_GRIB()                          */
    2865             : /************************************************************************/
    2866             : 
    2867         943 : static void GDALDeregister_GRIB(GDALDriver *)
    2868             : {
    2869         943 :     if (hGRIBMutex != nullptr)
    2870             :     {
    2871           1 :         MetanameCleanup();
    2872           1 :         CPLDestroyMutex(hGRIBMutex);
    2873           1 :         hGRIBMutex = nullptr;
    2874             :     }
    2875         943 : }
    2876             : 
    2877             : /************************************************************************/
    2878             : /*                          GDALGRIBDriver                              */
    2879             : /************************************************************************/
    2880             : 
    2881             : class GDALGRIBDriver : public GDALDriver
    2882             : {
    2883             :     bool m_bHasFullInitMetadata = false;
    2884             : 
    2885             :   public:
    2886        1384 :     GDALGRIBDriver() = default;
    2887             : 
    2888             :     char **GetMetadata(const char *pszDomain = "") override;
    2889             :     const char *GetMetadataItem(const char *pszName,
    2890             :                                 const char *pszDomain) override;
    2891             : };
    2892             : 
    2893             : /************************************************************************/
    2894             : /*                            GetMetadata()                             */
    2895             : /************************************************************************/
    2896             : 
    2897         275 : char **GDALGRIBDriver::GetMetadata(const char *pszDomain)
    2898             : {
    2899         275 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    2900             :     {
    2901             :         // Defer until necessary the setting of the CreationOptionList
    2902             :         // to let a chance to JPEG2000 drivers to have been loaded.
    2903         275 :         if (!m_bHasFullInitMetadata)
    2904             :         {
    2905           9 :             m_bHasFullInitMetadata = true;
    2906             : 
    2907          18 :             std::vector<CPLString> aosJ2KDrivers;
    2908          45 :             for (size_t i = 0; i < CPL_ARRAYSIZE(apszJ2KDrivers); i++)
    2909             :             {
    2910          36 :                 if (GDALGetDriverByName(apszJ2KDrivers[i]) != nullptr)
    2911             :                 {
    2912          18 :                     aosJ2KDrivers.push_back(apszJ2KDrivers[i]);
    2913             :                 }
    2914             :             }
    2915             : 
    2916             :             CPLString osCreationOptionList(
    2917             :                 "<CreationOptionList>"
    2918             :                 "   <Option name='DATA_ENCODING' type='string-select' "
    2919             :                 "default='AUTO' "
    2920             :                 "description='How data is encoded internally'>"
    2921             :                 "       <Value>AUTO</Value>"
    2922             :                 "       <Value>SIMPLE_PACKING</Value>"
    2923             :                 "       <Value>COMPLEX_PACKING</Value>"
    2924          18 :                 "       <Value>IEEE_FLOATING_POINT</Value>");
    2925           9 :             if (GDALGetDriverByName("PNG") != nullptr)
    2926           9 :                 osCreationOptionList += "       <Value>PNG</Value>";
    2927           9 :             if (!aosJ2KDrivers.empty())
    2928           9 :                 osCreationOptionList += "       <Value>JPEG2000</Value>";
    2929             :             osCreationOptionList +=
    2930             :                 "   </Option>"
    2931             :                 "   <Option name='NBITS' type='int' default='0' "
    2932             :                 "description='Number of bits per value'/>"
    2933             :                 "   <Option name='DECIMAL_SCALE_FACTOR' type='int' default='0' "
    2934             :                 "description='Value such that raw values are multiplied by "
    2935             :                 "10^DECIMAL_SCALE_FACTOR before integer encoding'/>"
    2936             :                 "   <Option name='SPATIAL_DIFFERENCING_ORDER' type='int' "
    2937             :                 "default='0' "
    2938           9 :                 "description='Order of spatial difference' min='0' max='2'/>";
    2939           9 :             if (!aosJ2KDrivers.empty())
    2940             :             {
    2941             :                 osCreationOptionList +=
    2942             :                     "   <Option name='COMPRESSION_RATIO' type='int' "
    2943             :                     "default='1' min='1' max='100' "
    2944             :                     "description='N:1 target compression ratio for JPEG2000'/>"
    2945             :                     "   <Option name='JPEG2000_DRIVER' type='string-select' "
    2946           9 :                     "description='Explicitly select a JPEG2000 driver'>";
    2947          27 :                 for (size_t i = 0; i < aosJ2KDrivers.size(); i++)
    2948             :                 {
    2949             :                     osCreationOptionList +=
    2950          18 :                         "       <Value>" + aosJ2KDrivers[i] + "</Value>";
    2951             :                 }
    2952           9 :                 osCreationOptionList += "   </Option>";
    2953             :             }
    2954             :             osCreationOptionList +=
    2955             :                 "   <Option name='DISCIPLINE' type='int' "
    2956             :                 "description='Discipline of the processed data'/>"
    2957             :                 "   <Option name='IDS' type='string' "
    2958             :                 "description='String equivalent to the GRIB_IDS metadata "
    2959             :                 "item'/>"
    2960             :                 "   <Option name='IDS_CENTER' type='int' "
    2961             :                 "description='Originating/generating center'/>"
    2962             :                 "   <Option name='IDS_SUBCENTER' type='int' "
    2963             :                 "description='Originating/generating subcenter'/>"
    2964             :                 "   <Option name='IDS_MASTER_TABLE' type='int' "
    2965             :                 "description='GRIB master tables version number'/>"
    2966             :                 "   <Option name='IDS_SIGNF_REF_TIME' type='int' "
    2967             :                 "description='Significance of Reference Time'/>"
    2968             :                 "   <Option name='IDS_REF_TIME' type='string' "
    2969             :                 "description='Reference time as YYYY-MM-DDTHH:MM:SSZ'/>"
    2970             :                 "   <Option name='IDS_PROD_STATUS' type='int' "
    2971             :                 "description='Production Status of Processed data'/>"
    2972             :                 "   <Option name='IDS_TYPE' type='int' "
    2973             :                 "description='Type of processed data'/>"
    2974             :                 "   <Option name='PDS_PDTN' type='int' "
    2975             :                 "description='Product Definition Template Number'/>"
    2976             :                 "   <Option name='PDS_TEMPLATE_NUMBERS' type='string' "
    2977             :                 "description='Product definition template raw numbers'/>"
    2978             :                 "   <Option name='PDS_TEMPLATE_ASSEMBLED_VALUES' type='string' "
    2979             :                 "description='Product definition template assembled values'/>"
    2980             :                 "   <Option name='INPUT_UNIT' type='string' "
    2981             :                 "description='Unit of input values. Only for temperatures. C "
    2982             :                 "or K'/>"
    2983             :                 "   <Option name='BAND_*' type='string' "
    2984             :                 "description='Override options at band level'/>"
    2985           9 :                 "</CreationOptionList>";
    2986             : 
    2987           9 :             SetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST, osCreationOptionList);
    2988             :         }
    2989             :     }
    2990         275 :     return GDALDriver::GetMetadata(pszDomain);
    2991             : }
    2992             : 
    2993             : /************************************************************************/
    2994             : /*                          GetMetadataItem()                           */
    2995             : /************************************************************************/
    2996             : 
    2997       58329 : const char *GDALGRIBDriver::GetMetadataItem(const char *pszName,
    2998             :                                             const char *pszDomain)
    2999             : {
    3000       58329 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    3001             :     {
    3002             :         // Defer until necessary the setting of the CreationOptionList
    3003             :         // to let a chance to JPEG2000 drivers to have been loaded.
    3004       58330 :         if (EQUAL(pszName, GDAL_DMD_CREATIONOPTIONLIST))
    3005         159 :             GetMetadata();
    3006             :     }
    3007       58329 :     return GDALDriver::GetMetadataItem(pszName, pszDomain);
    3008             : }
    3009             : 
    3010             : /************************************************************************/
    3011             : /*                         GDALRegister_GRIB()                          */
    3012             : /************************************************************************/
    3013             : 
    3014        1686 : void GDALRegister_GRIB()
    3015             : 
    3016             : {
    3017        1686 :     if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
    3018         302 :         return;
    3019             : 
    3020        1384 :     GDALDriver *poDriver = new GDALGRIBDriver();
    3021        1384 :     GRIBDriverSetCommonMetadata(poDriver);
    3022             : 
    3023        1384 :     poDriver->pfnOpen = GRIBDataset::Open;
    3024        1384 :     poDriver->pfnCreateCopy = GRIBDataset::CreateCopy;
    3025        1384 :     poDriver->pfnUnloadDriver = GDALDeregister_GRIB;
    3026             : 
    3027             : #ifdef USE_AEC
    3028        1384 :     poDriver->SetMetadataItem("HAVE_AEC", "YES");
    3029             : #endif
    3030             : 
    3031        1384 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    3032             : }

Generated by: LCOV version 1.14