LCOV - code coverage report
Current view: top level - apps - gdalalg_raster_create.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 211 226 93.4 %
Date: 2026-04-23 19:47:11 Functions: 4 4 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL
       4             :  * Purpose:  gdal "raster create" subcommand
       5             :  * Author:   Even Rouault <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2025, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "gdalalg_raster_create.h"
      14             : 
      15             : #include "cpl_conv.h"
      16             : #include "gdal_priv.h"
      17             : #include "gdal_utils.h"
      18             : #include "ogr_spatialref.h"
      19             : 
      20             : //! @cond Doxygen_Suppress
      21             : 
      22             : #ifndef _
      23             : #define _(x) (x)
      24             : #endif
      25             : 
      26             : /************************************************************************/
      27             : /*        GDALRasterCreateAlgorithm::GDALRasterCreateAlgorithm()        */
      28             : /************************************************************************/
      29             : 
      30         144 : GDALRasterCreateAlgorithm::GDALRasterCreateAlgorithm(
      31         144 :     bool standaloneStep) noexcept
      32             :     : GDALRasterPipelineStepAlgorithm(
      33             :           NAME, DESCRIPTION, HELP_URL,
      34         432 :           ConstructorOptions()
      35         144 :               .SetStandaloneStep(standaloneStep)
      36         144 :               .SetAddDefaultArguments(false)
      37         144 :               .SetAutoOpenInputDatasets(true)
      38         288 :               .SetInputDatasetHelpMsg("Template raster dataset")
      39         288 :               .SetInputDatasetAlias("like")
      40         288 :               .SetInputDatasetMetaVar("TEMPLATE-DATASET")
      41         144 :               .SetInputDatasetRequired(false)
      42         144 :               .SetInputDatasetPositional(false)
      43         432 :               .SetInputDatasetMaxCount(1))
      44             : {
      45         144 :     AddRasterInputArgs(false, false);
      46         144 :     if (standaloneStep)
      47             :     {
      48         105 :         AddProgressArg();
      49         105 :         AddRasterOutputArgs(false);
      50             :     }
      51             : 
      52         288 :     AddArg("size", 0, _("Output size in pixels"), &m_size)
      53         144 :         .SetMinCount(2)
      54         144 :         .SetMaxCount(2)
      55         144 :         .SetMinValueIncluded(0)
      56         144 :         .SetRepeatedArgAllowed(false)
      57         144 :         .SetDisplayHintAboutRepetition(false)
      58         144 :         .SetMetaVar("<width>,<height>");
      59         288 :     AddArg("band-count", 0, _("Number of bands"), &m_bandCount)
      60         144 :         .SetDefault(m_bandCount)
      61         144 :         .SetMinValueIncluded(0);
      62         144 :     AddOutputDataTypeArg(&m_type).SetDefault(m_type);
      63             : 
      64         144 :     AddNodataArg(&m_nodata, /* noneAllowed = */ true);
      65             : 
      66         144 :     AddArg("burn", 0, _("Burn value"), &m_burnValues);
      67         288 :     AddArg("crs", 0, _("Set CRS"), &m_crs)
      68         288 :         .AddHiddenAlias("a_srs")
      69         144 :         .SetIsCRSArg(/*noneAllowed=*/true);
      70         144 :     AddBBOXArg(&m_bbox);
      71             : 
      72             :     {
      73         288 :         auto &arg = AddArg("metadata", 0, _("Add metadata item"), &m_metadata)
      74         288 :                         .SetMetaVar("<KEY>=<VALUE>")
      75         144 :                         .SetPackedValuesAllowed(false);
      76          24 :         arg.AddValidationAction([this, &arg]()
      77         168 :                                 { return ParseAndValidateKeyValue(arg); });
      78         144 :         arg.AddHiddenAlias("mo");
      79             :     }
      80             : 
      81         144 :     const auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
      82         144 :     CPLAssertNotNull(inputArg);
      83             : 
      84             :     AddArg("copy-metadata", 0, _("Copy metadata from input dataset"),
      85         288 :            &m_copyMetadata)
      86         144 :         .AddDirectDependency(*inputArg);
      87             :     AddArg("copy-overviews", 0,
      88         288 :            _("Create same overview levels as input dataset"), &m_copyOverviews)
      89         144 :         .AddDirectDependency(*inputArg);
      90         144 : }
      91             : 
      92             : /************************************************************************/
      93             : /*                 GDALRasterCreateAlgorithm::RunImpl()                 */
      94             : /************************************************************************/
      95             : 
      96          53 : bool GDALRasterCreateAlgorithm::RunImpl(GDALProgressFunc pfnProgress,
      97             :                                         void *pProgressData)
      98             : {
      99          53 :     GDALPipelineStepRunContext stepCtxt;
     100          53 :     stepCtxt.m_pfnProgress = pfnProgress;
     101          53 :     stepCtxt.m_pProgressData = pProgressData;
     102          53 :     return RunPreStepPipelineValidations() && RunStep(stepCtxt);
     103             : }
     104             : 
     105             : /************************************************************************/
     106             : /*                 GDALRasterCreateAlgorithm::RunStep()                 */
     107             : /************************************************************************/
     108             : 
     109          56 : bool GDALRasterCreateAlgorithm::RunStep(GDALPipelineStepRunContext &)
     110             : {
     111          56 :     CPLAssert(!m_outputDataset.GetDatasetRef());
     112             : 
     113          56 :     if (m_standaloneStep)
     114             :     {
     115          53 :         if (m_format.empty())
     116             :         {
     117             :             const auto aosFormats =
     118             :                 CPLStringList(GDALGetOutputDriversForDatasetName(
     119          13 :                     m_outputDataset.GetName().c_str(), GDAL_OF_RASTER,
     120             :                     /* bSingleMatch = */ true,
     121          13 :                     /* bWarn = */ true));
     122          13 :             if (aosFormats.size() != 1)
     123             :             {
     124           1 :                 ReportError(CE_Failure, CPLE_AppDefined,
     125             :                             "Cannot guess driver for %s",
     126           1 :                             m_outputDataset.GetName().c_str());
     127           1 :                 return false;
     128             :             }
     129          12 :             m_format = aosFormats[0];
     130             :         }
     131             :     }
     132             :     else
     133             :     {
     134           3 :         m_format = "MEM";
     135             :     }
     136             : 
     137         110 :     OGRSpatialReference oSRS;
     138             : 
     139          55 :     GDALGeoTransform gt;
     140          55 :     bool bGTValid = false;
     141             : 
     142         110 :     CPLStringList aosCreationOptions(m_creationOptions);
     143             : 
     144          55 :     GDALDataset *poSrcDS = m_inputDataset.empty()
     145          55 :                                ? nullptr
     146          20 :                                : m_inputDataset.front().GetDatasetRef();
     147          55 :     if (poSrcDS)
     148             :     {
     149          20 :         if (m_size.empty())
     150             :         {
     151          54 :             m_size = std::vector<int>{poSrcDS->GetRasterXSize(),
     152          36 :                                       poSrcDS->GetRasterYSize()};
     153             :         }
     154             : 
     155          20 :         if (!GetArg("band-count")->IsExplicitlySet())
     156             :         {
     157          19 :             m_bandCount = poSrcDS->GetRasterCount();
     158             :         }
     159             : 
     160          20 :         if (!GetArg("datatype")->IsExplicitlySet())
     161             :         {
     162          19 :             if (m_bandCount > 0)
     163             :             {
     164             :                 m_type = GDALGetDataTypeName(
     165          19 :                     poSrcDS->GetRasterBand(1)->GetRasterDataType());
     166             :             }
     167             :         }
     168             : 
     169          20 :         if (m_crs.empty())
     170             :         {
     171          18 :             if (const auto poSRS = poSrcDS->GetSpatialRef())
     172          18 :                 oSRS = *poSRS;
     173             :         }
     174             : 
     175          20 :         if (m_bbox.empty())
     176             :         {
     177          19 :             bGTValid = poSrcDS->GetGeoTransform(gt) == CE_None;
     178             :         }
     179             : 
     180          20 :         if (m_nodata.empty() && m_bandCount > 0)
     181             :         {
     182          19 :             int bNoData = false;
     183             :             const double dfNoData =
     184          19 :                 poSrcDS->GetRasterBand(1)->GetNoDataValue(&bNoData);
     185          19 :             if (bNoData)
     186          10 :                 m_nodata = CPLSPrintf("%.17g", dfNoData);
     187             :         }
     188             : 
     189             :         // Replicate tiling of input datasets for a few popular output formats,
     190             :         // when compatible, and when the user hasn't specified creation options
     191             :         // affecting tiling.
     192          20 :         int nBlockXSize = 0, nBlockYSize = 0;
     193          20 :         if (m_bandCount > 0)
     194          20 :             poSrcDS->GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
     195             : 
     196          20 :         if (EQUAL(m_format.c_str(), "GTIFF") &&
     197           3 :             aosCreationOptions.FetchNameValue("TILED") == nullptr &&
     198           2 :             aosCreationOptions.FetchNameValue("BLOCKXSIZE") == nullptr &&
     199          25 :             aosCreationOptions.FetchNameValue("BLOCKYSIZE") == nullptr &&
     200           2 :             m_bandCount > 0)
     201             :         {
     202           2 :             if (nBlockXSize != poSrcDS->GetRasterXSize() &&
     203           2 :                 (nBlockXSize % 16) == 0 && (nBlockYSize % 16) == 0)
     204             :             {
     205           1 :                 aosCreationOptions.SetNameValue("TILED", "YES");
     206             :                 aosCreationOptions.SetNameValue("BLOCKXSIZE",
     207           1 :                                                 CPLSPrintf("%d", nBlockXSize));
     208             :                 aosCreationOptions.SetNameValue("BLOCKYSIZE",
     209           1 :                                                 CPLSPrintf("%d", nBlockYSize));
     210             :             }
     211             :         }
     212          18 :         else if (EQUAL(m_format.c_str(), "COG") &&
     213          19 :                  aosCreationOptions.FetchNameValue("BLOCKSIZE") == nullptr &&
     214           1 :                  m_bandCount > 0)
     215             :         {
     216           1 :             if (nBlockXSize != poSrcDS->GetRasterXSize() &&
     217           2 :                 nBlockXSize == nBlockYSize && nBlockXSize >= 128 &&
     218           1 :                 (nBlockXSize % 16) == 0)
     219             :             {
     220             :                 aosCreationOptions.SetNameValue("BLOCKSIZE",
     221           1 :                                                 CPLSPrintf("%d", nBlockXSize));
     222             :             }
     223             :         }
     224          17 :         else if (EQUAL(m_format.c_str(), "GPKG") &&
     225           3 :                  aosCreationOptions.FetchNameValue("BLOCKSIZE") == nullptr &&
     226           2 :                  aosCreationOptions.FetchNameValue("BLOCKXSIZE") == nullptr &&
     227          22 :                  aosCreationOptions.FetchNameValue("BLOCKYSIZE") == nullptr &&
     228           2 :                  m_bandCount > 0)
     229             :         {
     230           2 :             if (nBlockXSize != poSrcDS->GetRasterXSize() &&
     231           2 :                 nBlockXSize >= 256 && nBlockXSize <= 4096 &&
     232           4 :                 nBlockYSize >= 256 && nBlockYSize <= 4096)
     233             :             {
     234             :                 aosCreationOptions.SetNameValue("BLOCKXSIZE",
     235           1 :                                                 CPLSPrintf("%d", nBlockXSize));
     236             :                 aosCreationOptions.SetNameValue("BLOCKYSIZE",
     237           1 :                                                 CPLSPrintf("%d", nBlockYSize));
     238             :             }
     239             :         }
     240             :     }
     241             : 
     242          55 :     if (m_size.empty())
     243             :     {
     244           1 :         ReportError(CE_Failure, CPLE_IllegalArg,
     245             :                     "Argument 'size' should be specified, or 'like' dataset "
     246             :                     "should be specified");
     247           1 :         return false;
     248             :     }
     249             : 
     250          68 :     if (!m_burnValues.empty() && m_burnValues.size() != 1 &&
     251          14 :         static_cast<int>(m_burnValues.size()) != m_bandCount)
     252             :     {
     253           2 :         if (m_bandCount == 1)
     254             :         {
     255           1 :             ReportError(CE_Failure, CPLE_IllegalArg,
     256             :                         "One value should be provided for argument "
     257             :                         "'burn', given there is one band");
     258             :         }
     259             :         else
     260             :         {
     261           1 :             ReportError(CE_Failure, CPLE_IllegalArg,
     262             :                         "One or %d values should be provided for argument "
     263             :                         "'burn', given there are %d bands",
     264             :                         m_bandCount, m_bandCount);
     265             :         }
     266           2 :         return false;
     267             :     }
     268             : 
     269          52 :     auto poDriver = GetGDALDriverManager()->GetDriverByName(m_format.c_str());
     270          52 :     if (!poDriver)
     271             :     {
     272             :         // shouldn't happen given checks done in GDALAlgorithm
     273           0 :         ReportError(CE_Failure, CPLE_AppDefined, "Cannot find driver %s",
     274             :                     m_format.c_str());
     275           0 :         return false;
     276             :     }
     277             : 
     278          52 :     if (m_appendRaster)
     279             :     {
     280           2 :         if (poDriver->GetMetadataItem(GDAL_DCAP_CREATE_SUBDATASETS) == nullptr)
     281             :         {
     282           1 :             ReportError(CE_Failure, CPLE_NotSupported,
     283             :                         "-append option not supported for driver %s",
     284           1 :                         poDriver->GetDescription());
     285           1 :             return false;
     286             :         }
     287           1 :         aosCreationOptions.SetNameValue("APPEND_SUBDATASET", "YES");
     288             :     }
     289             : 
     290             :     auto poRetDS = std::unique_ptr<GDALDataset>(poDriver->Create(
     291         153 :         m_outputDataset.GetName().c_str(), m_size[0], m_size[1], m_bandCount,
     292         102 :         GDALGetDataTypeByName(m_type.c_str()), aosCreationOptions.List()));
     293          51 :     if (!poRetDS)
     294             :     {
     295           1 :         return false;
     296             :     }
     297             : 
     298          50 :     if (!m_crs.empty() && m_crs != "none" && m_crs != "null")
     299             :     {
     300          15 :         oSRS.SetFromUserInput(m_crs.c_str());
     301          15 :         oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     302             :     }
     303             : 
     304          50 :     if (!oSRS.IsEmpty())
     305             :     {
     306          33 :         if (poRetDS->SetSpatialRef(&oSRS) != CE_None)
     307             :         {
     308           1 :             ReportError(CE_Failure, CPLE_AppDefined, "Setting CRS failed");
     309           1 :             return false;
     310             :         }
     311             :     }
     312             : 
     313          49 :     if (!m_bbox.empty())
     314             :     {
     315          21 :         if (poRetDS->GetRasterXSize() == 0 || poRetDS->GetRasterYSize() == 0)
     316             :         {
     317           1 :             ReportError(CE_Failure, CPLE_AppDefined,
     318             :                         "Cannot set extent because one of dataset height or "
     319             :                         "width is null");
     320           1 :             return false;
     321             :         }
     322          20 :         bGTValid = true;
     323          20 :         gt.xorig = m_bbox[0];
     324          20 :         gt.xscale = (m_bbox[2] - m_bbox[0]) / poRetDS->GetRasterXSize();
     325          20 :         gt.xrot = 0;
     326          20 :         gt.yorig = m_bbox[3];
     327          20 :         gt.yrot = 0;
     328          20 :         gt.yscale = -(m_bbox[3] - m_bbox[1]) / poRetDS->GetRasterYSize();
     329             :     }
     330          48 :     if (bGTValid)
     331             :     {
     332          39 :         if (poRetDS->SetGeoTransform(gt) != CE_None)
     333             :         {
     334           1 :             ReportError(CE_Failure, CPLE_AppDefined, "Setting extent failed");
     335           1 :             return false;
     336             :         }
     337             :     }
     338             : 
     339          47 :     if (!m_nodata.empty() && !EQUAL(m_nodata.c_str(), "none"))
     340             :     {
     341          68 :         for (int i = 0; i < poRetDS->GetRasterCount(); ++i)
     342             :         {
     343          45 :             bool bCannotBeExactlyRepresented = false;
     344          45 :             if (poRetDS->GetRasterBand(i + 1)->SetNoDataValueAsString(
     345          45 :                     m_nodata.c_str(), &bCannotBeExactlyRepresented) != CE_None)
     346             :             {
     347           1 :                 if (bCannotBeExactlyRepresented)
     348             :                 {
     349           1 :                     ReportError(CE_Failure, CPLE_AppDefined,
     350             :                                 "Setting nodata value failed as it cannot be "
     351             :                                 "represented on its data type");
     352             :                 }
     353             :                 else
     354             :                 {
     355           0 :                     ReportError(CE_Failure, CPLE_AppDefined,
     356             :                                 "Setting nodata value failed");
     357             :                 }
     358           1 :                 return false;
     359             :             }
     360             :         }
     361             :     }
     362             : 
     363          46 :     if (m_copyMetadata)
     364             :     {
     365             : 
     366             :         // This should never happen because of the dependency set
     367           1 :         CPLAssertNotNull(poSrcDS);
     368             : 
     369             :         {
     370           1 :             const CPLStringList aosDomains(poSrcDS->GetMetadataDomainList());
     371           4 :             for (const char *domain : aosDomains)
     372             :             {
     373           3 :                 if (!EQUAL(domain, "IMAGE_STRUCTURE"))
     374             :                 {
     375           4 :                     if (poRetDS->SetMetadata(poSrcDS->GetMetadata(domain),
     376           4 :                                              domain) != CE_None)
     377             :                     {
     378           0 :                         ReportError(CE_Failure, CPLE_AppDefined,
     379             :                                     "Cannot copy '%s' metadata domain", domain);
     380           0 :                         return false;
     381             :                     }
     382             :                 }
     383             :             }
     384             :         }
     385           3 :         for (int i = 0; i < m_bandCount; ++i)
     386             :         {
     387             :             const CPLStringList aosDomains(
     388           2 :                 poSrcDS->GetRasterBand(i + 1)->GetMetadataDomainList());
     389           3 :             for (const char *domain : aosDomains)
     390             :             {
     391           1 :                 if (!EQUAL(domain, "IMAGE_STRUCTURE"))
     392             :                 {
     393           2 :                     if (poRetDS->GetRasterBand(i + 1)->SetMetadata(
     394           1 :                             poSrcDS->GetRasterBand(i + 1)->GetMetadata(domain),
     395           2 :                             domain) != CE_None)
     396             :                     {
     397           0 :                         ReportError(
     398             :                             CE_Failure, CPLE_AppDefined,
     399             :                             "Cannot copy '%s' metadata domain for band %d",
     400             :                             domain, i + 1);
     401           0 :                         return false;
     402             :                     }
     403             :                 }
     404             :             }
     405             :         }
     406             :     }
     407             : 
     408          92 :     const CPLStringList aosMD(m_metadata);
     409          58 :     for (const auto &[key, value] : cpl::IterateNameValue(aosMD))
     410             :     {
     411          12 :         if (poRetDS->SetMetadataItem(key, value) != CE_None)
     412             :         {
     413           0 :             ReportError(CE_Failure, CPLE_AppDefined,
     414             :                         "SetMetadataItem('%s', '%s') failed", key, value);
     415           0 :             return false;
     416             :         }
     417             :     }
     418             : 
     419          46 :     if (m_copyOverviews && m_bandCount > 0)
     420             :     {
     421             :         // This should never happen because of the dependency set
     422           2 :         CPLAssertNotNull(poSrcDS);
     423             : 
     424           3 :         if (poSrcDS->GetRasterXSize() != poRetDS->GetRasterXSize() ||
     425           1 :             poSrcDS->GetRasterYSize() != poRetDS->GetRasterYSize())
     426             :         {
     427           1 :             ReportError(CE_Failure, CPLE_AppDefined,
     428             :                         "Argument 'copy-overviews' can only be set when the "
     429             :                         "input and output datasets have the same dimension");
     430           1 :             return false;
     431             :         }
     432             :         const int nOverviewCount =
     433           1 :             poSrcDS->GetRasterBand(1)->GetOverviewCount();
     434           1 :         std::vector<int> anLevels;
     435           2 :         for (int i = 0; i < nOverviewCount; ++i)
     436             :         {
     437           1 :             const auto poOvrBand = poSrcDS->GetRasterBand(1)->GetOverview(i);
     438           1 :             const int nOvrFactor = GDALComputeOvFactor(
     439             :                 poOvrBand->GetXSize(), poSrcDS->GetRasterXSize(),
     440           1 :                 poOvrBand->GetYSize(), poSrcDS->GetRasterYSize());
     441           1 :             anLevels.push_back(nOvrFactor);
     442             :         }
     443           2 :         if (poRetDS->BuildOverviews(
     444           1 :                 "NONE", nOverviewCount, anLevels.data(),
     445             :                 /* nListBands = */ 0, /* panBandList = */ nullptr,
     446             :                 /* pfnProgress = */ nullptr, /* pProgressData = */ nullptr,
     447           1 :                 /* options = */ nullptr) != CE_None)
     448             :         {
     449           0 :             ReportError(CE_Failure, CPLE_AppDefined,
     450             :                         "Creating overview(s) failed");
     451           0 :             return false;
     452             :         }
     453             :     }
     454             : 
     455          45 :     if (!m_burnValues.empty())
     456             :     {
     457          38 :         for (int i = 0; i < m_bandCount; ++i)
     458             :         {
     459          25 :             const int burnValueIdx = m_burnValues.size() == 1 ? 0 : i;
     460          25 :             const auto poDstBand = poRetDS->GetRasterBand(i + 1);
     461             :             // cppcheck-suppress negativeContainerIndex
     462          25 :             if (poDstBand->Fill(m_burnValues[burnValueIdx]) != CE_None)
     463             :             {
     464           0 :                 ReportError(CE_Failure, CPLE_AppDefined,
     465             :                             "Setting burn value failed");
     466           0 :                 return false;
     467             :             }
     468             :         }
     469          13 :         if (poRetDS->FlushCache(false) != CE_None)
     470             :         {
     471           0 :             ReportError(CE_Failure, CPLE_AppDefined,
     472             :                         "Setting burn value failed");
     473           0 :             return false;
     474             :         }
     475             :     }
     476             : 
     477          45 :     m_outputDataset.Set(std::move(poRetDS));
     478             : 
     479          45 :     return true;
     480             : }
     481             : 
     482             : GDALRasterCreateAlgorithmStandalone::~GDALRasterCreateAlgorithmStandalone() =
     483             :     default;
     484             : 
     485             : //! @endcond

Generated by: LCOV version 1.14