forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdal_translate_lib.cpp
3591 lines (3193 loc) · 134 KB
/
gdal_translate_lib.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: GDAL Utilities
* Purpose: GDAL Image Translator Program
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 1998, 2002, Frank Warmerdam
* Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys.com>
* Copyright (c) 2015, Faza Mahamood
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "gdal_utils.h"
#include "gdal_utils_priv.h"
#include "gdalargumentparser.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <array>
#include <limits>
#include <set>
#include "commonutils.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_json.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
#include "gdal.h"
#include "gdal_priv.h"
#include "gdal_priv_templates.hpp"
#include "gdal_rat.h"
#include "gdal_vrt.h"
#include "ogr_core.h"
#include "ogr_spatialref.h"
#include "vrtdataset.h"
static void AttachMetadata(GDALDatasetH, const CPLStringList &);
static void AttachDomainMetadata(GDALDatasetH, const CPLStringList &);
static void CopyBandInfo(GDALRasterBand *poSrcBand, GDALRasterBand *poDstBand,
int bCanCopyStatsMetadata, int bCopyScale,
int bCopyNoData, bool bCopyRAT,
const GDALTranslateOptions *psOptions);
typedef enum
{
MASK_DISABLED,
MASK_AUTO,
MASK_USER
} MaskMode;
/************************************************************************/
/* GDALTranslateScaleParams */
/************************************************************************/
/** scaling parameters for use in GDALTranslateOptions.
*/
struct GDALTranslateScaleParams
{
/*! scaling is done only if it is set to TRUE. This is helpful when there is
a need to scale only certain bands. */
bool bScale = false;
/*! set it to TRUE if dfScaleSrcMin and dfScaleSrcMax is set. When it is
FALSE, the input range is automatically computed from the source data. */
bool bHaveScaleSrc = false;
/*! the range of input pixel values which need to be scaled */
double dfScaleSrcMin = 0;
double dfScaleSrcMax = 0;
/*! the range of output pixel values. If
GDALTranslateScaleParams::dfScaleDstMin and
GDALTranslateScaleParams::dfScaleDstMax are not set, then the output
range is 0 to 255. */
double dfScaleDstMin = 0;
double dfScaleDstMax = 0;
};
/************************************************************************/
/* GDALTranslateOptions */
/************************************************************************/
/** Options for use with GDALTranslate(). GDALTranslateOptions* must be
* allocated and freed with GDALTranslateOptionsNew() and
* GDALTranslateOptionsFree() respectively.
*/
struct GDALTranslateOptions
{
/*! output format. Use the short format name. */
std::string osFormat{};
/*! allow or suppress progress monitor and other non-error output */
bool bQuiet = true;
/*! the progress function to use */
GDALProgressFunc pfnProgress = GDALDummyProgress;
/*! pointer to the progress data variable */
void *pProgressData = nullptr;
/*! for the output bands to be of the indicated data type */
GDALDataType eOutputType = GDT_Unknown;
/*! Used only by parser logic */
bool bParsedMaskArgument = false;
MaskMode eMaskMode = MASK_AUTO;
/*! number of input bands to write to the output file, or to reorder bands
*/
int nBandCount = 0;
/*! list of input bands to write to the output file, or to reorder bands.
The value 1 corresponds to the 1st band. */
std::vector<int> anBandList{}; /* negative value of panBandList[i] means
mask band of ABS(panBandList[i]) */
/*! size of the output file. GDALTranslateOptions::nOXSizePixel is in pixels
and GDALTranslateOptions::nOYSizePixel is in lines. If one of the two
values is set to 0, its value will be determined from the other one,
while maintaining the aspect ratio of the source dataset */
int nOXSizePixel = 0;
int nOYSizePixel = 0;
/*! size of the output file. GDALTranslateOptions::dfOXSizePct and
GDALTranslateOptions::dfOYSizePct are fraction of the input image size.
The value 100 means 100%. If one of the two values is set to 0, its value
will be determined from the other one, while maintaining the aspect ratio
of the source dataset */
double dfOXSizePct = 0;
double dfOYSizePct = 0;
/*! list of creation options to the output format driver */
CPLStringList aosCreateOptions{};
/*! subwindow from the source image for copying based on pixel/line location
*/
std::array<double, 4> adfSrcWin{{0, 0, 0, 0}};
/*! don't be forgiving of mismatches and lost data when translating to the
* output format */
bool bStrict = false;
/*! apply the scale/offset metadata for the bands to convert scaled values
* to unscaled values. It is also often necessary to reset the output
* datatype with GDALTranslateOptions::eOutputType */
bool bUnscale = false;
bool bSetScale = false;
double dfScale = 1;
bool bSetOffset = false;
double dfOffset = 0;
/*! the list of scale parameters for each band. */
std::vector<GDALTranslateScaleParams> asScaleParams{};
/*! It is set to TRUE, when scale parameters are specific to each band */
bool bHasUsedExplicitScaleBand = false;
/*! to apply non-linear scaling with a power function. It is the list of
exponents of the power function (must be positive). This option must be
used with GDALTranslateOptions::asScaleParams. If
GDALTranslateOptions::adfExponent.size() is 1, it is applied to all
bands of the output image. */
std::vector<double> adfExponent{};
bool bHasUsedExplicitExponentBand = false;
/*! list of metadata key and value to set on the output dataset if possible. */
CPLStringList aosMetadataOptions{};
/*! list of metadata key and value in a domain to set on the output dataset if possible. */
CPLStringList aosDomainMetadataOptions{};
/*! override the projection for the output file. The SRS may be any of the
usual GDAL/OGR forms, complete WKT, PROJ.4, EPSG:n or a file containing
the WKT. */
std::string osOutputSRS{};
/*! Coordinate epoch of output SRS */
double dfOutputCoordinateEpoch = 0;
/*! does not copy source GCP into destination dataset (when TRUE) */
bool bNoGCP = false;
/*! number of GCPS to be added to the output dataset */
int nGCPCount = 0;
/*! list of GCPs to be added to the output dataset */
GDAL_GCP *pasGCPs = nullptr;
/*! assign/override the georeferenced bounds of the output file. This
assigns georeferenced bounds to the output file, ignoring what would have
been derived from the source file. So this does not cause reprojection to
the specified SRS. */
std::array<double, 4> adfULLR{{0, 0, 0, 0}};
/*! assign/override the geotransform of the output file. This
assigns a geotransform to the output file, ignoring what would have
been derived from the source file. So this does not cause reprojection to
the specified SRS. */
std::array<double, 6> adfGT{{0, 0, 0, 0, 0, 0}};
/*! set a nodata value specified in GDALTranslateOptions::osNoData to the
* output bands */
bool bSetNoData = 0;
/*! avoid setting a nodata value to the output file if one exists for the
* source file */
bool bUnsetNoData = 0;
/*! Assign a specified nodata value to output bands (
GDALTranslateOptions::bSetNoData option should be set). Note that if the
input dataset has a nodata value, this does not cause pixel values that
are equal to that nodata value to be changed to the value specified. */
std::string osNoData{};
/*! to expose a dataset with 1 band with a color table as a dataset with
3 (RGB) or 4 (RGBA) bands. Useful for output drivers such as JPEG,
JPEG2000, MrSID, ECW that don't support color indexed datasets.
The 1 value enables to expand a dataset with a color table that only
contains gray levels to a gray indexed dataset. */
int nRGBExpand = 0;
int nMaskBand = 0; /* negative value means mask band of ABS(nMaskBand) */
/*! force recomputation of statistics */
bool bStats = false;
bool bApproxStats = false;
/*! If this option is set, GDALTranslateOptions::adfSrcWin or
(GDALTranslateOptions::dfULX, GDALTranslateOptions::dfULY,
GDALTranslateOptions::dfLRX, GDALTranslateOptions::dfLRY) values that
falls partially outside the source raster extent will be considered as an
error. The default behavior is to accept such requests. */
bool bErrorOnPartiallyOutside = false;
/*! Same as bErrorOnPartiallyOutside, except that the criterion for
erroring out is when the request falls completely outside the
source raster extent. */
bool bErrorOnCompletelyOutside = false;
/*! does not copy source RAT into destination dataset (when TRUE) */
bool bNoRAT = false;
/*! resampling algorithm
nearest (default), bilinear, cubic, cubicspline, lanczos, average, mode
*/
std::string osResampling{};
/*! target resolution. The values must be expressed in georeferenced units.
Both must be positive values. This is exclusive with
GDALTranslateOptions::nOXSizePixel (or
GDALTranslateOptions::dfOXSizePct), GDALTranslateOptions::nOYSizePixel
(or GDALTranslateOptions::dfOYSizePct), GDALTranslateOptions::adfULLR,
and GDALTranslateOptions::adfGT.
*/
double dfXRes = 0;
double dfYRes = 0;
/*! subwindow from the source image for copying (like
GDALTranslateOptions::adfSrcWin) but with the corners given in
georeferenced coordinates (by default expressed in the SRS of the
dataset. Can be changed with osProjSRS) */
double dfULX = 0;
double dfULY = 0;
double dfLRX = 0;
double dfLRY = 0;
/*! SRS in which to interpret the coordinates given with
GDALTranslateOptions::dfULX, GDALTranslateOptions::dfULY,
GDALTranslateOptions::dfLRX, GDALTranslateOptions::dfLRY. The SRS may be
any of the usual GDAL/OGR forms, complete WKT, PROJ.4, EPSG:n or a file
containing the WKT. Note that this does not cause reprojection of the
dataset to the specified SRS. */
std::string osProjSRS{};
int nLimitOutSize = 0;
// Array of color interpretations per band. Should be a GDALColorInterp
// value, or -1 if no override.
std::vector<int> anColorInterp{};
/*! does not copy source XMP into destination dataset (when TRUE) */
bool bNoXMP = false;
/*! overview level of source file to be used */
int nOvLevel = OVR_LEVEL_AUTO;
/*! set to true to prevent overwriting existing dataset */
bool bNoOverwrite = false;
GDALTranslateOptions() = default;
~GDALTranslateOptions();
GDALTranslateOptions *Clone() const;
private:
GDALTranslateOptions(const GDALTranslateOptions &) = default;
GDALTranslateOptions &operator=(const GDALTranslateOptions &) = delete;
};
/************************************************************************/
/* GDALTranslateOptions::~GDALTranslateOptions() */
/************************************************************************/
GDALTranslateOptions::~GDALTranslateOptions()
{
if (nGCPCount)
GDALDeinitGCPs(nGCPCount, pasGCPs);
CPLFree(pasGCPs);
}
/************************************************************************/
/* GDALTranslateOptions::Clone(() */
/************************************************************************/
GDALTranslateOptions *GDALTranslateOptions::Clone() const
{
GDALTranslateOptions *psOptions = new GDALTranslateOptions(*this);
if (nGCPCount)
psOptions->pasGCPs = GDALDuplicateGCPs(nGCPCount, pasGCPs);
return psOptions;
}
/************************************************************************/
/* SrcToDst() */
/************************************************************************/
static void SrcToDst(double dfX, double dfY, double dfSrcXOff, double dfSrcYOff,
double dfSrcXSize, double dfSrcYSize, double dfDstXOff,
double dfDstYOff, double dfDstXSize, double dfDstYSize,
double &dfXOut, double &dfYOut)
{
dfXOut = ((dfX - dfSrcXOff) / dfSrcXSize) * dfDstXSize + dfDstXOff;
dfYOut = ((dfY - dfSrcYOff) / dfSrcYSize) * dfDstYSize + dfDstYOff;
}
/************************************************************************/
/* GetSrcDstWindow() */
/************************************************************************/
static bool FixSrcDstWindow(std::array<double, 4> &padfSrcWin,
std::array<double, 4> &padfDstWin,
int nSrcRasterXSize, int nSrcRasterYSize)
{
const double dfSrcXOff = padfSrcWin[0];
const double dfSrcYOff = padfSrcWin[1];
const double dfSrcXSize = padfSrcWin[2];
const double dfSrcYSize = padfSrcWin[3];
const double dfDstXOff = padfDstWin[0];
const double dfDstYOff = padfDstWin[1];
const double dfDstXSize = padfDstWin[2];
const double dfDstYSize = padfDstWin[3];
bool bModifiedX = false;
bool bModifiedY = false;
double dfModifiedSrcXOff = dfSrcXOff;
double dfModifiedSrcYOff = dfSrcYOff;
double dfModifiedSrcXSize = dfSrcXSize;
double dfModifiedSrcYSize = dfSrcYSize;
/* -------------------------------------------------------------------- */
/* Clamp within the bounds of the available source data. */
/* -------------------------------------------------------------------- */
if (dfModifiedSrcXOff < 0)
{
dfModifiedSrcXSize += dfModifiedSrcXOff;
dfModifiedSrcXOff = 0;
bModifiedX = true;
}
if (dfModifiedSrcYOff < 0)
{
dfModifiedSrcYSize += dfModifiedSrcYOff;
dfModifiedSrcYOff = 0;
bModifiedY = true;
}
if (dfModifiedSrcXOff + dfModifiedSrcXSize > nSrcRasterXSize)
{
dfModifiedSrcXSize = nSrcRasterXSize - dfModifiedSrcXOff;
bModifiedX = true;
}
if (dfModifiedSrcYOff + dfModifiedSrcYSize > nSrcRasterYSize)
{
dfModifiedSrcYSize = nSrcRasterYSize - dfModifiedSrcYOff;
bModifiedY = true;
}
/* -------------------------------------------------------------------- */
/* Don't do anything if the requesting region is completely off */
/* the source image. */
/* -------------------------------------------------------------------- */
if (dfModifiedSrcXOff >= nSrcRasterXSize ||
dfModifiedSrcYOff >= nSrcRasterYSize || dfModifiedSrcXSize <= 0 ||
dfModifiedSrcYSize <= 0)
{
return false;
}
padfSrcWin[0] = dfModifiedSrcXOff;
padfSrcWin[1] = dfModifiedSrcYOff;
padfSrcWin[2] = dfModifiedSrcXSize;
padfSrcWin[3] = dfModifiedSrcYSize;
/* -------------------------------------------------------------------- */
/* If we haven't had to modify the source rectangle, then the */
/* destination rectangle must be the whole region. */
/* -------------------------------------------------------------------- */
if (!bModifiedX && !bModifiedY)
return true;
/* -------------------------------------------------------------------- */
/* Now transform this possibly reduced request back into the */
/* destination buffer coordinates in case the output region is */
/* less than the whole buffer. */
/* -------------------------------------------------------------------- */
double dfDstULX, dfDstULY, dfDstLRX, dfDstLRY;
SrcToDst(dfModifiedSrcXOff, dfModifiedSrcYOff, dfSrcXOff, dfSrcYOff,
dfSrcXSize, dfSrcYSize, dfDstXOff, dfDstYOff, dfDstXSize,
dfDstYSize, dfDstULX, dfDstULY);
SrcToDst(dfModifiedSrcXOff + dfModifiedSrcXSize,
dfModifiedSrcYOff + dfModifiedSrcYSize, dfSrcXOff, dfSrcYOff,
dfSrcXSize, dfSrcYSize, dfDstXOff, dfDstYOff, dfDstXSize,
dfDstYSize, dfDstLRX, dfDstLRY);
double dfModifiedDstXOff = dfDstXOff;
double dfModifiedDstYOff = dfDstYOff;
double dfModifiedDstXSize = dfDstXSize;
double dfModifiedDstYSize = dfDstYSize;
if (bModifiedX)
{
dfModifiedDstXOff = dfDstULX - dfDstXOff;
dfModifiedDstXSize = (dfDstLRX - dfDstXOff) - dfModifiedDstXOff;
dfModifiedDstXOff = std::max(0.0, dfModifiedDstXOff);
if (dfModifiedDstXOff + dfModifiedDstXSize > dfDstXSize)
dfModifiedDstXSize = dfDstXSize - dfModifiedDstXOff;
}
if (bModifiedY)
{
dfModifiedDstYOff = dfDstULY - dfDstYOff;
dfModifiedDstYSize = (dfDstLRY - dfDstYOff) - dfModifiedDstYOff;
dfModifiedDstYOff = std::max(0.0, dfModifiedDstYOff);
if (dfModifiedDstYOff + dfModifiedDstYSize > dfDstYSize)
dfModifiedDstYSize = dfDstYSize - dfModifiedDstYOff;
}
if (dfModifiedDstXSize <= 0.0 || dfModifiedDstYSize <= 0.0)
{
return false;
}
padfDstWin[0] = dfModifiedDstXOff;
padfDstWin[1] = dfModifiedDstYOff;
padfDstWin[2] = dfModifiedDstXSize;
padfDstWin[3] = dfModifiedDstYSize;
return true;
}
/************************************************************************/
/* GDALTranslateFlush() */
/************************************************************************/
static GDALDatasetH GDALTranslateFlush(GDALDatasetH hOutDS)
{
if (hOutDS != nullptr)
{
CPLErr eErrBefore = CPLGetLastErrorType();
GDALFlushCache(hOutDS);
if (eErrBefore == CE_None && CPLGetLastErrorType() != CE_None)
{
GDALClose(hOutDS);
hOutDS = nullptr;
}
}
return hOutDS;
}
/************************************************************************/
/* EditISIS3MetadataForBandChange() */
/************************************************************************/
static CPLJSONObject Clone(const CPLJSONObject &obj)
{
auto serialized = obj.Format(CPLJSONObject::PrettyFormat::Plain);
CPLJSONDocument oJSONDocument;
const GByte *pabyData = reinterpret_cast<const GByte *>(serialized.c_str());
oJSONDocument.LoadMemory(pabyData);
return oJSONDocument.GetRoot();
}
static void ReworkArray(CPLJSONObject &container, const CPLJSONObject &obj,
int nSrcBandCount,
const GDALTranslateOptions *psOptions)
{
auto oArray = obj.ToArray();
if (oArray.Size() == nSrcBandCount)
{
CPLJSONArray oNewArray;
for (int nBand : psOptions->anBandList)
{
const int iSrcIdx = nBand - 1;
oNewArray.Add(oArray[iSrcIdx]);
}
const auto childName(obj.GetName());
container.Delete(childName);
container.Add(childName, oNewArray);
}
}
static CPLString
EditISIS3MetadataForBandChange(const char *pszJSON, int nSrcBandCount,
const GDALTranslateOptions *psOptions)
{
CPLJSONDocument oJSONDocument;
const GByte *pabyData = reinterpret_cast<const GByte *>(pszJSON);
if (!oJSONDocument.LoadMemory(pabyData))
{
return CPLString();
}
auto oRoot = oJSONDocument.GetRoot();
if (!oRoot.IsValid())
{
return CPLString();
}
auto oBandBin = oRoot.GetObj("IsisCube/BandBin");
if (oBandBin.IsValid() && oBandBin.GetType() == CPLJSONObject::Type::Object)
{
// Backup original BandBin object
oRoot.GetObj("IsisCube").Add("OriginalBandBin", Clone(oBandBin));
// Iterate over BandBin members and reorder/resize its arrays that
// have the same number of elements than the number of bands of the
// source dataset.
for (auto &child : oBandBin.GetChildren())
{
if (child.GetType() == CPLJSONObject::Type::Array)
{
ReworkArray(oBandBin, child, nSrcBandCount, psOptions);
}
else if (child.GetType() == CPLJSONObject::Type::Object)
{
auto oValue = child.GetObj("value");
auto oUnit = child.GetObj("unit");
if (oValue.GetType() == CPLJSONObject::Type::Array)
{
ReworkArray(child, oValue, nSrcBandCount, psOptions);
}
}
}
}
return oRoot.Format(CPLJSONObject::PrettyFormat::Pretty);
}
/************************************************************************/
/* AdjustNoDataValue() */
/************************************************************************/
static double AdjustNoDataValue(double dfInputNoDataValue,
GDALRasterBand *poBand,
const GDALTranslateOptions *psOptions)
{
bool bSignedByte = false;
const char *pszPixelType =
psOptions->aosCreateOptions.FetchNameValue("PIXELTYPE");
if (pszPixelType == nullptr && poBand->GetRasterDataType() == GDT_Byte)
{
poBand->EnablePixelTypeSignedByteWarning(false);
pszPixelType = poBand->GetMetadataItem("PIXELTYPE", "IMAGE_STRUCTURE");
poBand->EnablePixelTypeSignedByteWarning(true);
}
if (pszPixelType != nullptr && EQUAL(pszPixelType, "SIGNEDBYTE"))
bSignedByte = true;
int bClamped = FALSE;
int bRounded = FALSE;
double dfVal = 0.0;
const GDALDataType eBandType = poBand->GetRasterDataType();
if (bSignedByte)
{
if (dfInputNoDataValue < -128.0)
{
dfVal = -128.0;
bClamped = TRUE;
}
else if (dfInputNoDataValue > 127.0)
{
dfVal = 127.0;
bClamped = TRUE;
}
else
{
dfVal = static_cast<int>(floor(dfInputNoDataValue + 0.5));
if (dfVal != dfInputNoDataValue)
bRounded = TRUE;
}
}
else
{
dfVal = GDALAdjustValueToDataType(eBandType, dfInputNoDataValue,
&bClamped, &bRounded);
}
if (bClamped)
{
CPLError(CE_Warning, CPLE_AppDefined,
"for band %d, nodata value has been clamped "
"to %.0f, the original value being out of range.",
poBand->GetBand(), dfVal);
}
else if (bRounded)
{
CPLError(CE_Warning, CPLE_AppDefined,
"for band %d, nodata value has been rounded "
"to %.0f, %s being an integer datatype.",
poBand->GetBand(), dfVal, GDALGetDataTypeName(eBandType));
}
return dfVal;
}
/************************************************************************/
/* GDALTranslate() */
/************************************************************************/
/* clang-format off */
/**
* Converts raster data between different formats.
*
* This is the equivalent of the
* <a href="/programs/gdal_translate.html">gdal_translate</a> utility.
*
* GDALTranslateOptions* must be allocated and freed with
* GDALTranslateOptionsNew() and GDALTranslateOptionsFree() respectively.
*
* @param pszDest the destination dataset path.
* @param hSrcDataset the source dataset handle.
* @param psOptionsIn the options struct returned by GDALTranslateOptionsNew()
* or NULL.
* @param pbUsageError pointer to a integer output variable to store if any
* usage error has occurred or NULL.
* @return the output dataset (new dataset that must be closed using
* GDALClose()) or NULL in case of error. If the output
* format is a VRT dataset, then the returned VRT dataset has a reference to
* hSrcDataset. Hence hSrcDataset should be closed after the returned dataset
* if using GDALClose().
* A safer alternative is to use GDALReleaseDataset() instead of using
* GDALClose(), in which case you can close datasets in any order.
*
* @since GDAL 2.1
*/
/* clang-format on */
GDALDatasetH GDALTranslate(const char *pszDest, GDALDatasetH hSrcDataset,
const GDALTranslateOptions *psOptionsIn,
int *pbUsageError)
{
CPLErrorReset();
if (hSrcDataset == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "No source dataset specified.");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
if (pszDest == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "No target dataset specified.");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
GDALTranslateOptions *psOptions =
(psOptionsIn) ? psOptionsIn->Clone()
: GDALTranslateOptionsNew(nullptr, nullptr);
GDALDatasetH hOutDS = nullptr;
bool bGotBounds = false;
bool bGotGeoTransform = false;
if (pbUsageError)
*pbUsageError = FALSE;
if (psOptions->adfULLR[0] != 0.0 || psOptions->adfULLR[1] != 0.0 ||
psOptions->adfULLR[2] != 0.0 || psOptions->adfULLR[3] != 0.0)
bGotBounds = true;
if (psOptions->adfGT[0] != 0.0 || psOptions->adfGT[1] != 0.0 ||
psOptions->adfGT[2] != 0.0 || psOptions->adfGT[3] != 0.0 ||
psOptions->adfGT[4] != 0.0 || psOptions->adfGT[5] != 0.0)
bGotGeoTransform = true;
GDALDataset *poSrcDS = GDALDataset::FromHandle(hSrcDataset);
const char *pszSource = poSrcDS->GetDescription();
if (strcmp(pszSource, pszDest) == 0 && pszSource[0] != '\0' &&
poSrcDS->GetDriver() != GDALGetDriverByName("MEM"))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Source and destination datasets must be different.");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
CPLString osProjSRS;
if (!psOptions->osProjSRS.empty())
{
OGRSpatialReference oSRS;
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (oSRS.SetFromUserInput(psOptions->osProjSRS.c_str()) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to process SRS definition: %s",
psOptions->osProjSRS.c_str());
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
char *pszSRS = nullptr;
oSRS.exportToWkt(&pszSRS);
if (pszSRS)
osProjSRS = pszSRS;
CPLFree(pszSRS);
}
if (!psOptions->osOutputSRS.empty() && psOptions->osOutputSRS != "null" &&
psOptions->osOutputSRS != "none")
{
OGRSpatialReference oOutputSRS;
if (oOutputSRS.SetFromUserInput(psOptions->osOutputSRS.c_str()) !=
OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to process SRS definition: %s",
psOptions->osOutputSRS.c_str());
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
}
/* -------------------------------------------------------------------- */
/* Check that incompatible options are not used */
/* -------------------------------------------------------------------- */
if ((psOptions->nOXSizePixel != 0 || psOptions->dfOXSizePct != 0.0 ||
psOptions->nOYSizePixel != 0 || psOptions->dfOYSizePct != 0.0) &&
(psOptions->dfXRes != 0 && psOptions->dfYRes != 0))
{
CPLError(CE_Failure, CPLE_IllegalArg,
"-outsize and -tr options cannot be used at the same time.");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if ((bGotBounds | bGotGeoTransform) &&
(psOptions->dfXRes != 0 && psOptions->dfYRes != 0))
{
CPLError(
CE_Failure, CPLE_IllegalArg,
"-a_ullr or -a_gt options cannot be used at the same time as -tr.");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (bGotBounds && bGotGeoTransform)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"-a_ullr and -a_gt options cannot be used at the same time.");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Collect some information from the source file. */
/* -------------------------------------------------------------------- */
if (psOptions->adfSrcWin[2] == 0 && psOptions->adfSrcWin[3] == 0)
{
psOptions->adfSrcWin[2] = poSrcDS->GetRasterXSize();
psOptions->adfSrcWin[3] = poSrcDS->GetRasterYSize();
}
/* -------------------------------------------------------------------- */
/* Build band list to translate */
/* -------------------------------------------------------------------- */
bool bAllBandsInOrder = true;
if (psOptions->anBandList.empty())
{
psOptions->nBandCount = poSrcDS->GetRasterCount();
if ((psOptions->nBandCount == 0) && (psOptions->bStrict))
{
// if not strict then the driver can fail if it doesn't support zero
// bands
CPLError(CE_Failure, CPLE_AppDefined,
"Input file has no bands, and so cannot be translated.");
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
psOptions->anBandList.resize(psOptions->nBandCount);
for (int i = 0; i < psOptions->nBandCount; i++)
psOptions->anBandList[i] = i + 1;
}
else
{
for (int i = 0; i < psOptions->nBandCount; i++)
{
if (std::abs(psOptions->anBandList[i]) > poSrcDS->GetRasterCount())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Band %d requested, but only bands 1 to %d available.",
std::abs(psOptions->anBandList[i]),
poSrcDS->GetRasterCount());
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (psOptions->anBandList[i] != i + 1)
bAllBandsInOrder = FALSE;
}
if (psOptions->nBandCount != poSrcDS->GetRasterCount())
bAllBandsInOrder = FALSE;
}
if (static_cast<int>(psOptions->asScaleParams.size()) >
psOptions->nBandCount)
{
if (!psOptions->bHasUsedExplicitScaleBand)
CPLError(CE_Failure, CPLE_IllegalArg,
"-scale has been specified more times than the number of "
"output bands");
else
CPLError(CE_Failure, CPLE_IllegalArg,
"-scale_XX has been specified with XX greater than the "
"number of output bands");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (static_cast<int>(psOptions->adfExponent.size()) > psOptions->nBandCount)
{
if (!psOptions->bHasUsedExplicitExponentBand)
CPLError(CE_Failure, CPLE_IllegalArg,
"-exponent has been specified more times than the number "
"of output bands");
else
CPLError(CE_Failure, CPLE_IllegalArg,
"-exponent_XX has been specified with XX greater than the "
"number of output bands");
if (pbUsageError)
*pbUsageError = TRUE;
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (!psOptions->bQuiet && (psOptions->bSetScale || psOptions->bSetOffset) &&
psOptions->bUnscale)
{
// Cf https://github.com/OSGeo/gdal/issues/7863
CPLError(CE_Warning, CPLE_AppDefined,
"-a_scale/-a_offset are not applied by -unscale, but are set "
"after it, and -unscale uses the original source band "
"scale/offset values. "
"You may want to use -scale 0 1 %.16g %.16g instead. "
"This warning will not appear if -q is specified.",
psOptions->dfOffset, psOptions->dfOffset + psOptions->dfScale);
}
/* -------------------------------------------------------------------- */
/* Compute the source window from the projected source window */
/* if the projected coordinates were provided. Note that the */
/* projected coordinates are in ulx, uly, lrx, lry format, */
/* while the adfSrcWin is xoff, yoff, xsize, ysize with the */
/* xoff,yoff being the ulx, uly in pixel/line. */
/* -------------------------------------------------------------------- */
const char *pszProjection = nullptr;
if (psOptions->dfULX != 0.0 || psOptions->dfULY != 0.0 ||
psOptions->dfLRX != 0.0 || psOptions->dfLRY != 0.0)
{
double adfGeoTransform[6];
poSrcDS->GetGeoTransform(adfGeoTransform);
if (adfGeoTransform[1] == 0.0 || adfGeoTransform[5] == 0.0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"The -projwin option was used, but the geotransform is "
"invalid.");
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"The -projwin option was used, but the geotransform is\n"
"rotated. This configuration is not supported.");
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
if (!osProjSRS.empty())
{
pszProjection = poSrcDS->GetProjectionRef();
if (pszProjection != nullptr && strlen(pszProjection) > 0)
{
OGRSpatialReference oSRSIn;
OGRSpatialReference oSRSDS;
oSRSIn.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
oSRSDS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
oSRSIn.SetFromUserInput(osProjSRS);
oSRSDS.SetFromUserInput(pszProjection);
if (!oSRSIn.IsSame(&oSRSDS))
{
OGRCoordinateTransformation *poCT =
OGRCreateCoordinateTransformation(&oSRSIn, &oSRSDS);
if (!(poCT &&
poCT->Transform(1, &psOptions->dfULX,
&psOptions->dfULY) &&
poCT->Transform(1, &psOptions->dfLRX,
&psOptions->dfLRY)))
{
OGRCoordinateTransformation::DestroyCT(poCT);
CPLError(CE_Failure, CPLE_AppDefined,
"-projwin_srs ignored since coordinate "
"transformation failed.");
GDALTranslateOptionsFree(psOptions);
return nullptr;
}
delete poCT;
}
}
else
{
CPLError(CE_None, CPLE_None,
"-projwin_srs ignored since the dataset has no "
"projection.");
}
}
psOptions->adfSrcWin[0] =
(psOptions->dfULX - adfGeoTransform[0]) / adfGeoTransform[1];
psOptions->adfSrcWin[1] =
(psOptions->dfULY - adfGeoTransform[3]) / adfGeoTransform[5];
psOptions->adfSrcWin[2] =
(psOptions->dfLRX - psOptions->dfULX) / adfGeoTransform[1];
psOptions->adfSrcWin[3] =
(psOptions->dfLRY - psOptions->dfULY) / adfGeoTransform[5];
// In case of nearest resampling, round to integer pixels (#6610)
if (psOptions->osResampling.empty() ||
EQUALN(psOptions->osResampling.c_str(), "NEAR", 4))
{