Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: ISIS Version 3 Driver
4 : * Purpose: Implementation of ISIS3Dataset
5 : * Author: Trent Hare (thare@usgs.gov)
6 : * Frank Warmerdam (warmerdam@pobox.com)
7 : * Even Rouault (even.rouault at spatialys.com)
8 : *
9 : * NOTE: Original code authored by Trent and placed in the public domain as
10 : * per US government policy. I have (within my rights) appropriated it and
11 : * placed it under the following license. This is not intended to diminish
12 : * Trents contribution.
13 : ******************************************************************************
14 : * Copyright (c) 2007, Frank Warmerdam <warmerdam@pobox.com>
15 : * Copyright (c) 2009-2010, Even Rouault <even.rouault at spatialys.com>
16 : * Copyright (c) 2017 Hobu Inc
17 : * Copyright (c) 2017, Dmitry Baryshnikov <polimax@mail.ru>
18 : * Copyright (c) 2017, NextGIS <info@nextgis.com>
19 : *
20 : * SPDX-License-Identifier: MIT
21 : ****************************************************************************/
22 :
23 : #include "cpl_json.h"
24 : #include "cpl_string.h"
25 : #include "cpl_time.h"
26 : #include "cpl_vsi_error.h"
27 : #include "cpl_vsi_virtual.h"
28 : #include "gdal_frmts.h"
29 : #include "gdal_proxy.h"
30 : #include "nasakeywordhandler.h"
31 : #include "ogrgeojsonreader.h"
32 : #include "ogr_spatialref.h"
33 : #include "rawdataset.h"
34 : #include "vrtdataset.h"
35 : #include "cpl_safemaths.hpp"
36 : #include "pdsdrivercore.h"
37 : #include "json_utils.h"
38 :
39 : // For gethostname()
40 : #ifdef _WIN32
41 : #include <winsock2.h>
42 : #else
43 : #include <unistd.h>
44 : #endif
45 :
46 : #include <algorithm>
47 : #include <cinttypes>
48 : #include <map>
49 : #include <utility> // pair
50 : #include <vector>
51 :
52 : // Constants coming from ISIS3 source code
53 : // in isis/src/base/objs/SpecialPixel/SpecialPixel.h
54 :
55 : // There are several types of special pixels
56 : // * Isis::Null Pixel has no data available
57 : // * Isis::Lis Pixel was saturated on the instrument
58 : // * Isis::His Pixel was saturated on the instrument
59 : // * Isis::Lrs Pixel was saturated during a computation
60 : // * Isis::Hrs Pixel was saturated during a computation
61 :
62 : // 1-byte special pixel values
63 : const unsigned char ISIS3_NULL1 = 0;
64 : const unsigned char LOW_REPR_SAT1 = 0;
65 : const unsigned char LOW_INSTR_SAT1 = 0;
66 : const unsigned char HIGH_INSTR_SAT1 = 255;
67 : const unsigned char HIGH_REPR_SAT1 = 255;
68 :
69 : // 2-byte unsigned special pixel values
70 : const unsigned short ISIS3_NULLU2 = 0;
71 : const unsigned short LOW_REPR_SATU2 = 1;
72 : const unsigned short LOW_INSTR_SATU2 = 2;
73 : const unsigned short HIGH_INSTR_SATU2 = 65534;
74 : const unsigned short HIGH_REPR_SATU2 = 65535;
75 :
76 : // 2-byte signed special pixel values
77 : const short ISIS3_NULL2 = -32768;
78 : const short LOW_REPR_SAT2 = -32767;
79 : const short LOW_INSTR_SAT2 = -32766;
80 : const short HIGH_INSTR_SAT2 = -32765;
81 : const short HIGH_REPR_SAT2 = -32764;
82 :
83 : // Define 4-byte special pixel values for IEEE floating point
84 : const float ISIS3_NULL4 = -3.4028226550889045e+38f; // 0xFF7FFFFB;
85 : const float LOW_REPR_SAT4 = -3.4028228579130005e+38f; // 0xFF7FFFFC;
86 : const float LOW_INSTR_SAT4 = -3.4028230607370965e+38f; // 0xFF7FFFFD;
87 : const float HIGH_INSTR_SAT4 = -3.4028232635611926e+38f; // 0xFF7FFFFE;
88 : const float HIGH_REPR_SAT4 = -3.4028234663852886e+38f; // 0xFF7FFFFF;
89 :
90 : // Must be large enough to hold an integer
91 : static const char *const pszSTARTBYTE_PLACEHOLDER = "!*^STARTBYTE^*!";
92 : // Must be large enough to hold an integer
93 : static const char *const pszLABEL_BYTES_PLACEHOLDER = "!*^LABEL_BYTES^*!";
94 : // Must be large enough to hold an integer
95 : static const char *const pszHISTORY_STARTBYTE_PLACEHOLDER =
96 : "!*^HISTORY_STARTBYTE^*!";
97 :
98 : /************************************************************************/
99 : /* ==================================================================== */
100 : /* ISISDataset */
101 : /* ==================================================================== */
102 : /************************************************************************/
103 :
104 : class ISIS3Dataset final : public RawDataset
105 : {
106 : friend class ISIS3RawRasterBand;
107 : friend class ISISTiledBand;
108 : friend class ISIS3WrapperRasterBand;
109 :
110 : class NonPixelSection
111 : {
112 : public:
113 : CPLString osSrcFilename{};
114 : CPLString osDstFilename{}; // empty for same file
115 : vsi_l_offset nSrcOffset{};
116 : vsi_l_offset nSize{};
117 : CPLString osPlaceHolder{}; // empty if not same file
118 : };
119 :
120 : VSILFILE *m_fpLabel{}; // label file (only used for writing)
121 : VSILFILE *m_fpImage{}; // image data file. May be == fpLabel
122 : GDALDataset *m_poExternalDS{}; // external dataset (GeoTIFF)
123 : bool m_bGeoTIFFAsRegularExternal{}; // creation only
124 : bool m_bGeoTIFFInitDone{true}; // creation only
125 :
126 : CPLString m_osExternalFilename{};
127 : bool m_bIsLabelWritten{true}; // creation only
128 :
129 : bool m_bIsTiled{};
130 : bool m_bInitToNodata{}; // creation only
131 :
132 : NASAKeywordHandler m_oKeywords{};
133 :
134 : bool m_bGotTransform{};
135 : GDALGeoTransform m_gt{};
136 :
137 : bool m_bHasSrcNoData{}; // creation only
138 : double m_dfSrcNoData{}; // creation only
139 :
140 : OGRSpatialReference m_oSRS{};
141 :
142 : // creation only variables
143 : CPLString m_osComment{};
144 : CPLString m_osLatitudeType{};
145 : CPLString m_osLongitudeDirection{};
146 : CPLString m_osTargetName{};
147 : bool m_bForce360{};
148 : bool m_bWriteBoundingDegrees{true};
149 : CPLString m_osBoundingDegrees{};
150 :
151 : CPLJSONObject m_oJSonLabel{};
152 : CPLString m_osHistory{}; // creation only
153 : bool m_bUseSrcLabel{true}; // creation only
154 : bool m_bUseSrcMapping{}; // creation only
155 : bool m_bUseSrcHistory{true}; // creation only
156 : bool m_bAddGDALHistory{true}; // creation only
157 : CPLString m_osGDALHistory{}; // creation only
158 : std::vector<NonPixelSection> m_aoNonPixelSections{}; // creation only
159 : CPLJSONObject m_oSrcJSonLabel{}; // creation only
160 : CPLStringList m_aosISIS3MD{};
161 : CPLStringList m_aosAdditionalFiles{};
162 : CPLString m_osFromFilename{}; // creation only
163 :
164 : RawBinaryLayout m_sLayout{};
165 :
166 : bool m_bResolveOfflineContent = true;
167 : int m_nMaxOfflineContentSize = 100000000;
168 : bool m_bHasResolvedOfflineContent = false;
169 :
170 : const char *GetKeyword(const char *pszPath, const char *pszDefault = "");
171 :
172 : double FixLong(double dfLong);
173 : void BuildLabel();
174 : void BuildHistory();
175 : void WriteLabel();
176 : void InvalidateLabel();
177 : void ResolveOfflineContentOfLabel();
178 :
179 : static CPLString SerializeAsPDL(const CPLJSONObject &oObj);
180 : static void SerializeAsPDL(VSILFILE *fp, const CPLJSONObject &oObj,
181 : int nDepth = 0);
182 :
183 : CPL_DISALLOW_COPY_ASSIGN(ISIS3Dataset)
184 :
185 : protected:
186 : CPLErr Close(GDALProgressFunc = nullptr, void * = nullptr) override;
187 :
188 : public:
189 : ISIS3Dataset();
190 : ~ISIS3Dataset() override;
191 :
192 : int CloseDependentDatasets() override;
193 :
194 : CPLErr GetGeoTransform(GDALGeoTransform >) const override;
195 : CPLErr SetGeoTransform(const GDALGeoTransform >) override;
196 :
197 : const OGRSpatialReference *GetSpatialRef() const override;
198 : CPLErr SetSpatialRef(const OGRSpatialReference *poSRS) override;
199 :
200 : char **GetFileList() override;
201 :
202 : char **GetMetadataDomainList() override;
203 : CSLConstList GetMetadata(const char *pszDomain = "") override;
204 : CPLErr SetMetadata(CSLConstList papszMD,
205 : const char *pszDomain = "") override;
206 :
207 : bool GetRawBinaryLayout(GDALDataset::RawBinaryLayout &) override;
208 :
209 : static GDALDataset *Open(GDALOpenInfo *);
210 : static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
211 : int nBandsIn, GDALDataType eType,
212 : CSLConstList papszOptions);
213 : static GDALDataset *CreateCopy(const char *pszFilename,
214 : GDALDataset *poSrcDS, int bStrict,
215 : CSLConstList papszOptions,
216 : GDALProgressFunc pfnProgress,
217 : void *pProgressData);
218 : };
219 :
220 : /************************************************************************/
221 : /* ==================================================================== */
222 : /* ISISTiledBand */
223 : /* ==================================================================== */
224 : /************************************************************************/
225 :
226 : class ISISTiledBand final : public GDALPamRasterBand
227 : {
228 : friend class ISIS3Dataset;
229 :
230 : VSILFILE *const m_fpVSIL{};
231 : GIntBig m_nFirstTileOffset{};
232 : GIntBig m_nXTileOffset{};
233 : GIntBig m_nYTileOffset{};
234 : const bool m_bNativeOrder{};
235 : bool m_bHasOffset{};
236 : bool m_bHasScale{};
237 : double m_dfOffset{};
238 : double m_dfScale{1.0};
239 : double m_dfNoData{};
240 : bool m_bValid = false;
241 :
242 : CPL_DISALLOW_COPY_ASSIGN(ISISTiledBand)
243 :
244 : public:
245 : ISISTiledBand(GDALDataset *poDS, VSILFILE *fpVSIL, int nBand,
246 : GDALDataType eDT, int nTileXSize, int nTileYSize,
247 : GIntBig nFirstTileOffset, GIntBig nXTileOffset,
248 : GIntBig nYTileOffset, int bNativeOrder);
249 :
250 41 : bool IsValid() const
251 : {
252 41 : return m_bValid;
253 : }
254 :
255 : CPLErr IReadBlock(int, int, void *) override;
256 : CPLErr IWriteBlock(int, int, void *) override;
257 :
258 : double GetOffset(int *pbSuccess = nullptr) override;
259 : double GetScale(int *pbSuccess = nullptr) override;
260 : CPLErr SetOffset(double dfNewOffset) override;
261 : CPLErr SetScale(double dfNewScale) override;
262 : double GetNoDataValue(int *pbSuccess = nullptr) override;
263 : CPLErr SetNoDataValue(double dfNewNoData) override;
264 :
265 : void SetMaskBand(std::unique_ptr<GDALRasterBand> poMaskBand);
266 : };
267 :
268 : /************************************************************************/
269 : /* ==================================================================== */
270 : /* ISIS3RawRasterBand */
271 : /* ==================================================================== */
272 : /************************************************************************/
273 :
274 : class ISIS3RawRasterBand final : public RawRasterBand
275 : {
276 : friend class ISIS3Dataset;
277 :
278 : bool m_bHasOffset;
279 : bool m_bHasScale;
280 : double m_dfOffset;
281 : double m_dfScale{1.0};
282 : double m_dfNoData;
283 :
284 : public:
285 : ISIS3RawRasterBand(GDALDataset *l_poDS, int l_nBand, VSILFILE *l_fpRaw,
286 : vsi_l_offset l_nImgOffset, int l_nPixelOffset,
287 : int l_nLineOffset, GDALDataType l_eDataType,
288 : int l_bNativeOrder);
289 :
290 : CPLErr IReadBlock(int, int, void *) override;
291 : CPLErr IWriteBlock(int, int, void *) override;
292 :
293 : CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
294 : GDALDataType, GSpacing nPixelSpace, GSpacing nLineSpace,
295 : GDALRasterIOExtraArg *psExtraArg) override;
296 :
297 : double GetOffset(int *pbSuccess = nullptr) override;
298 : double GetScale(int *pbSuccess = nullptr) override;
299 : CPLErr SetOffset(double dfNewOffset) override;
300 : CPLErr SetScale(double dfNewScale) override;
301 : double GetNoDataValue(int *pbSuccess = nullptr) override;
302 : CPLErr SetNoDataValue(double dfNewNoData) override;
303 :
304 : void SetMaskBand(std::unique_ptr<GDALRasterBand> poMaskBand);
305 : };
306 :
307 : /************************************************************************/
308 : /* ==================================================================== */
309 : /* ISIS3WrapperRasterBand */
310 : /* */
311 : /* proxy for bands stored in other formats. */
312 : /* ==================================================================== */
313 : /************************************************************************/
314 : class ISIS3WrapperRasterBand final : public GDALProxyRasterBand
315 : {
316 : friend class ISIS3Dataset;
317 :
318 : GDALRasterBand *m_poBaseBand{};
319 : bool m_bHasOffset{};
320 : bool m_bHasScale{};
321 : double m_dfOffset{};
322 : double m_dfScale{1.0};
323 : double m_dfNoData{};
324 :
325 : CPL_DISALLOW_COPY_ASSIGN(ISIS3WrapperRasterBand)
326 :
327 : protected:
328 : virtual GDALRasterBand *
329 127 : RefUnderlyingRasterBand(bool /* bForceOpen */) const override
330 : {
331 127 : return m_poBaseBand;
332 : }
333 :
334 : public:
335 : explicit ISIS3WrapperRasterBand(GDALRasterBand *poBaseBandIn);
336 :
337 : void InitFile();
338 :
339 : virtual CPLErr Fill(double dfRealValue,
340 : double dfImaginaryValue = 0) override;
341 : CPLErr IWriteBlock(int, int, void *) override;
342 :
343 : CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
344 : GDALDataType, GSpacing nPixelSpace, GSpacing nLineSpace,
345 : GDALRasterIOExtraArg *psExtraArg) override;
346 :
347 : double GetOffset(int *pbSuccess = nullptr) override;
348 : double GetScale(int *pbSuccess = nullptr) override;
349 : CPLErr SetOffset(double dfNewOffset) override;
350 : CPLErr SetScale(double dfNewScale) override;
351 : double GetNoDataValue(int *pbSuccess = nullptr) override;
352 : CPLErr SetNoDataValue(double dfNewNoData) override;
353 :
354 4 : int GetMaskFlags() override
355 : {
356 4 : return nMaskFlags;
357 : }
358 :
359 4 : GDALRasterBand *GetMaskBand() override
360 : {
361 4 : return poMask;
362 : }
363 :
364 : void SetMaskBand(std::unique_ptr<GDALRasterBand> poMaskBand);
365 : };
366 :
367 : /************************************************************************/
368 : /* ==================================================================== */
369 : /* ISISMaskBand */
370 : /* ==================================================================== */
371 :
372 : class ISISMaskBand final : public GDALRasterBand
373 : {
374 : GDALRasterBand *m_poBaseBand{};
375 : void *m_pBuffer{};
376 :
377 : CPL_DISALLOW_COPY_ASSIGN(ISISMaskBand)
378 :
379 : public:
380 : explicit ISISMaskBand(GDALRasterBand *poBaseBand);
381 : ~ISISMaskBand() override;
382 :
383 : CPLErr IReadBlock(int, int, void *) override;
384 : };
385 :
386 : /************************************************************************/
387 : /* ISISTiledBand() */
388 : /************************************************************************/
389 :
390 51 : ISISTiledBand::ISISTiledBand(GDALDataset *poDSIn, VSILFILE *fpVSILIn,
391 : int nBandIn, GDALDataType eDT, int nTileXSize,
392 : int nTileYSize, GIntBig nFirstTileOffsetIn,
393 : GIntBig nXTileOffsetIn, GIntBig nYTileOffsetIn,
394 51 : int bNativeOrderIn)
395 : : m_fpVSIL(fpVSILIn), m_nXTileOffset(nXTileOffsetIn),
396 : m_nYTileOffset(nYTileOffsetIn),
397 51 : m_bNativeOrder(CPL_TO_BOOL(bNativeOrderIn))
398 : {
399 51 : poDS = poDSIn;
400 51 : nBand = nBandIn;
401 51 : eDataType = eDT;
402 51 : nBlockXSize = nTileXSize;
403 51 : nBlockYSize = nTileYSize;
404 51 : nRasterXSize = poDSIn->GetRasterXSize();
405 51 : nRasterYSize = poDSIn->GetRasterYSize();
406 :
407 51 : const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
408 51 : const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);
409 :
410 51 : if (m_nXTileOffset == 0 && m_nYTileOffset == 0)
411 : {
412 51 : m_nXTileOffset =
413 51 : static_cast<GIntBig>(GDALGetDataTypeSizeBytes(eDT)) * nTileXSize;
414 51 : if (m_nXTileOffset > GINTBIG_MAX / nTileYSize)
415 : {
416 0 : CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
417 0 : return;
418 : }
419 51 : m_nXTileOffset *= nTileYSize;
420 :
421 51 : if (m_nXTileOffset > GINTBIG_MAX / l_nBlocksPerRow)
422 : {
423 0 : CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
424 0 : return;
425 : }
426 51 : m_nYTileOffset = m_nXTileOffset * l_nBlocksPerRow;
427 : }
428 :
429 51 : m_nFirstTileOffset = nFirstTileOffsetIn;
430 51 : if (nBand > 1)
431 : {
432 19 : if (m_nYTileOffset > GINTBIG_MAX / (nBand - 1) ||
433 19 : (nBand - 1) * m_nYTileOffset > GINTBIG_MAX / l_nBlocksPerColumn ||
434 19 : m_nFirstTileOffset >
435 19 : GINTBIG_MAX - (nBand - 1) * m_nYTileOffset * l_nBlocksPerColumn)
436 : {
437 0 : CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
438 0 : return;
439 : }
440 19 : m_nFirstTileOffset += (nBand - 1) * m_nYTileOffset * l_nBlocksPerColumn;
441 : }
442 51 : m_bValid = true;
443 : }
444 :
445 : /************************************************************************/
446 : /* IReadBlock() */
447 : /************************************************************************/
448 :
449 476 : CPLErr ISISTiledBand::IReadBlock(int nXBlock, int nYBlock, void *pImage)
450 :
451 : {
452 476 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
453 476 : if (poGDS->m_osExternalFilename.empty())
454 : {
455 232 : if (!poGDS->m_bIsLabelWritten)
456 2 : poGDS->WriteLabel();
457 : }
458 :
459 476 : const vsi_l_offset nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset +
460 476 : nYBlock * m_nYTileOffset;
461 476 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
462 476 : const size_t nBlockSize =
463 476 : static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize;
464 :
465 476 : if (VSIFSeekL(m_fpVSIL, nOffset, SEEK_SET) != 0)
466 : {
467 0 : CPLError(CE_Failure, CPLE_FileIO,
468 : "Failed to seek to offset %d to read tile %d,%d.",
469 : static_cast<int>(nOffset), nXBlock, nYBlock);
470 0 : return CE_Failure;
471 : }
472 :
473 476 : if (VSIFReadL(pImage, 1, nBlockSize, m_fpVSIL) != nBlockSize)
474 : {
475 0 : CPLError(CE_Failure, CPLE_FileIO,
476 : "Failed to read %d bytes for tile %d,%d.",
477 : static_cast<int>(nBlockSize), nXBlock, nYBlock);
478 0 : return CE_Failure;
479 : }
480 :
481 476 : if (!m_bNativeOrder && eDataType != GDT_UInt8)
482 0 : GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);
483 :
484 476 : return CE_None;
485 : }
486 :
487 : /************************************************************************/
488 : /* RemapNoDataT() */
489 : /************************************************************************/
490 :
491 : template <class T>
492 6 : static void RemapNoDataT(T *pBuffer, int nItems, T srcNoData, T dstNoData)
493 : {
494 67542 : for (int i = 0; i < nItems; i++)
495 : {
496 67536 : if (pBuffer[i] == srcNoData)
497 6 : pBuffer[i] = dstNoData;
498 : }
499 6 : }
500 :
501 : /************************************************************************/
502 : /* RemapNoData() */
503 : /************************************************************************/
504 :
505 6 : static void RemapNoData(GDALDataType eDataType, void *pBuffer, int nItems,
506 : double dfSrcNoData, double dfDstNoData)
507 : {
508 6 : if (eDataType == GDT_UInt8)
509 : {
510 3 : RemapNoDataT(reinterpret_cast<GByte *>(pBuffer), nItems,
511 3 : static_cast<GByte>(dfSrcNoData),
512 3 : static_cast<GByte>(dfDstNoData));
513 : }
514 3 : else if (eDataType == GDT_UInt16)
515 : {
516 1 : RemapNoDataT(reinterpret_cast<GUInt16 *>(pBuffer), nItems,
517 1 : static_cast<GUInt16>(dfSrcNoData),
518 1 : static_cast<GUInt16>(dfDstNoData));
519 : }
520 2 : else if (eDataType == GDT_Int16)
521 : {
522 1 : RemapNoDataT(reinterpret_cast<GInt16 *>(pBuffer), nItems,
523 1 : static_cast<GInt16>(dfSrcNoData),
524 1 : static_cast<GInt16>(dfDstNoData));
525 : }
526 : else
527 : {
528 1 : CPLAssert(eDataType == GDT_Float32);
529 1 : RemapNoDataT(reinterpret_cast<float *>(pBuffer), nItems,
530 : static_cast<float>(dfSrcNoData),
531 : static_cast<float>(dfDstNoData));
532 : }
533 6 : }
534 :
535 : /************************************************************************/
536 : /* IReadBlock() */
537 : /************************************************************************/
538 :
539 225 : CPLErr ISISTiledBand::IWriteBlock(int nXBlock, int nYBlock, void *pImage)
540 :
541 : {
542 225 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
543 225 : if (poGDS->m_osExternalFilename.empty())
544 : {
545 223 : if (!poGDS->m_bIsLabelWritten)
546 2 : poGDS->WriteLabel();
547 : }
548 :
549 225 : if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
550 : {
551 1 : RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
552 : poGDS->m_dfSrcNoData, m_dfNoData);
553 : }
554 :
555 225 : const vsi_l_offset nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset +
556 225 : nYBlock * m_nYTileOffset;
557 225 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
558 225 : const size_t nBlockSize =
559 225 : static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize;
560 :
561 225 : const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
562 225 : const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);
563 :
564 : // Pad partial blocks to nodata value
565 225 : if (nXBlock == l_nBlocksPerRow - 1 && (nRasterXSize % nBlockXSize) != 0)
566 : {
567 24 : GByte *pabyImage = static_cast<GByte *>(pImage);
568 24 : int nXStart = nRasterXSize % nBlockXSize;
569 1688 : for (int iY = 0; iY < nBlockYSize; iY++)
570 : {
571 1664 : GDALCopyWords(&m_dfNoData, GDT_Float64, 0,
572 1664 : pabyImage + (iY * nBlockXSize + nXStart) * nDTSize,
573 1664 : eDataType, nDTSize, nBlockXSize - nXStart);
574 : }
575 : }
576 225 : if (nYBlock == l_nBlocksPerColumn - 1 && (nRasterYSize % nBlockYSize) != 0)
577 : {
578 49 : GByte *pabyImage = static_cast<GByte *>(pImage);
579 1685 : for (int iY = nRasterYSize % nBlockYSize; iY < nBlockYSize; iY++)
580 : {
581 1636 : GDALCopyWords(&m_dfNoData, GDT_Float64, 0,
582 1636 : pabyImage + iY * nBlockXSize * nDTSize, eDataType,
583 : nDTSize, nBlockXSize);
584 : }
585 : }
586 :
587 225 : if (VSIFSeekL(m_fpVSIL, nOffset, SEEK_SET) != 0)
588 : {
589 0 : CPLError(CE_Failure, CPLE_FileIO,
590 : "Failed to seek to offset %d to read tile %d,%d.",
591 : static_cast<int>(nOffset), nXBlock, nYBlock);
592 0 : return CE_Failure;
593 : }
594 :
595 225 : if (!m_bNativeOrder && eDataType != GDT_UInt8)
596 0 : GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);
597 :
598 225 : if (VSIFWriteL(pImage, 1, nBlockSize, m_fpVSIL) != nBlockSize)
599 : {
600 0 : CPLError(CE_Failure, CPLE_FileIO,
601 : "Failed to write %d bytes for tile %d,%d.",
602 : static_cast<int>(nBlockSize), nXBlock, nYBlock);
603 0 : return CE_Failure;
604 : }
605 :
606 225 : if (!m_bNativeOrder && eDataType != GDT_UInt8)
607 0 : GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);
608 :
609 225 : return CE_None;
610 : }
611 :
612 : /************************************************************************/
613 : /* SetMaskBand() */
614 : /************************************************************************/
615 :
616 41 : void ISISTiledBand::SetMaskBand(std::unique_ptr<GDALRasterBand> poMaskBand)
617 : {
618 41 : poMask.reset(std::move(poMaskBand));
619 41 : nMaskFlags = 0;
620 41 : }
621 :
622 : /************************************************************************/
623 : /* GetOffset() */
624 : /************************************************************************/
625 :
626 14 : double ISISTiledBand::GetOffset(int *pbSuccess)
627 : {
628 14 : if (pbSuccess)
629 4 : *pbSuccess = m_bHasOffset;
630 14 : return m_dfOffset;
631 : }
632 :
633 : /************************************************************************/
634 : /* GetScale() */
635 : /************************************************************************/
636 :
637 14 : double ISISTiledBand::GetScale(int *pbSuccess)
638 : {
639 14 : if (pbSuccess)
640 4 : *pbSuccess = m_bHasScale;
641 14 : return m_dfScale;
642 : }
643 :
644 : /************************************************************************/
645 : /* SetOffset() */
646 : /************************************************************************/
647 :
648 14 : CPLErr ISISTiledBand::SetOffset(double dfNewOffset)
649 : {
650 14 : m_dfOffset = dfNewOffset;
651 14 : m_bHasOffset = true;
652 14 : return CE_None;
653 : }
654 :
655 : /************************************************************************/
656 : /* SetScale() */
657 : /************************************************************************/
658 :
659 14 : CPLErr ISISTiledBand::SetScale(double dfNewScale)
660 : {
661 14 : m_dfScale = dfNewScale;
662 14 : m_bHasScale = true;
663 14 : return CE_None;
664 : }
665 :
666 : /************************************************************************/
667 : /* GetNoDataValue() */
668 : /************************************************************************/
669 :
670 12 : double ISISTiledBand::GetNoDataValue(int *pbSuccess)
671 : {
672 12 : if (pbSuccess)
673 8 : *pbSuccess = true;
674 12 : return m_dfNoData;
675 : }
676 :
677 : /************************************************************************/
678 : /* SetNoDataValue() */
679 : /************************************************************************/
680 :
681 51 : CPLErr ISISTiledBand::SetNoDataValue(double dfNewNoData)
682 : {
683 51 : m_dfNoData = dfNewNoData;
684 51 : return CE_None;
685 : }
686 :
687 : /************************************************************************/
688 : /* ISIS3RawRasterBand() */
689 : /************************************************************************/
690 :
691 381 : ISIS3RawRasterBand::ISIS3RawRasterBand(GDALDataset *l_poDS, int l_nBand,
692 : VSILFILE *l_fpRaw,
693 : vsi_l_offset l_nImgOffset,
694 : int l_nPixelOffset, int l_nLineOffset,
695 : GDALDataType l_eDataType,
696 381 : int l_bNativeOrder)
697 : : RawRasterBand(l_poDS, l_nBand, l_fpRaw, l_nImgOffset, l_nPixelOffset,
698 : l_nLineOffset, l_eDataType, l_bNativeOrder,
699 : RawRasterBand::OwnFP::NO),
700 : m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0),
701 381 : m_dfNoData(0.0)
702 : {
703 381 : }
704 :
705 : /************************************************************************/
706 : /* IReadBlock() */
707 : /************************************************************************/
708 :
709 2071 : CPLErr ISIS3RawRasterBand::IReadBlock(int nXBlock, int nYBlock, void *pImage)
710 :
711 : {
712 2071 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
713 2071 : if (poGDS->m_osExternalFilename.empty())
714 : {
715 930 : if (!poGDS->m_bIsLabelWritten)
716 0 : poGDS->WriteLabel();
717 : }
718 2071 : return RawRasterBand::IReadBlock(nXBlock, nYBlock, pImage);
719 : }
720 :
721 : /************************************************************************/
722 : /* IWriteBlock() */
723 : /************************************************************************/
724 :
725 856 : CPLErr ISIS3RawRasterBand::IWriteBlock(int nXBlock, int nYBlock, void *pImage)
726 :
727 : {
728 856 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
729 856 : if (poGDS->m_osExternalFilename.empty())
730 : {
731 796 : if (!poGDS->m_bIsLabelWritten)
732 0 : poGDS->WriteLabel();
733 : }
734 :
735 856 : if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
736 : {
737 0 : RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
738 : poGDS->m_dfSrcNoData, m_dfNoData);
739 : }
740 :
741 856 : return RawRasterBand::IWriteBlock(nXBlock, nYBlock, pImage);
742 : }
743 :
744 : /************************************************************************/
745 : /* IRasterIO() */
746 : /************************************************************************/
747 :
748 1956 : CPLErr ISIS3RawRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
749 : int nXSize, int nYSize, void *pData,
750 : int nBufXSize, int nBufYSize,
751 : GDALDataType eBufType,
752 : GSpacing nPixelSpace, GSpacing nLineSpace,
753 : GDALRasterIOExtraArg *psExtraArg)
754 :
755 : {
756 1956 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
757 1956 : if (poGDS->m_osExternalFilename.empty())
758 : {
759 1153 : if (!poGDS->m_bIsLabelWritten)
760 55 : poGDS->WriteLabel();
761 : }
762 1956 : if (eRWFlag == GF_Write && poGDS->m_bHasSrcNoData &&
763 30 : poGDS->m_dfSrcNoData != m_dfNoData)
764 : {
765 4 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
766 4 : if (eBufType == eDataType && nPixelSpace == nDTSize &&
767 4 : nLineSpace == nPixelSpace * nBufXSize)
768 : {
769 4 : RemapNoData(eDataType, pData, nBufXSize * nBufYSize,
770 : poGDS->m_dfSrcNoData, m_dfNoData);
771 : }
772 : else
773 : {
774 0 : const GByte *pabySrc = reinterpret_cast<GByte *>(pData);
775 : GByte *pabyTemp = reinterpret_cast<GByte *>(
776 0 : VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize));
777 0 : for (int i = 0; i < nBufYSize; i++)
778 : {
779 0 : GDALCopyWords(pabySrc + i * nLineSpace, eBufType,
780 : static_cast<int>(nPixelSpace),
781 0 : pabyTemp + i * nBufXSize * nDTSize, eDataType,
782 : nDTSize, nBufXSize);
783 : }
784 0 : RemapNoData(eDataType, pabyTemp, nBufXSize * nBufYSize,
785 : poGDS->m_dfSrcNoData, m_dfNoData);
786 0 : CPLErr eErr = RawRasterBand::IRasterIO(
787 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize,
788 : nBufYSize, eDataType, nDTSize,
789 0 : static_cast<GSpacing>(nDTSize) * nBufXSize, psExtraArg);
790 0 : VSIFree(pabyTemp);
791 0 : return eErr;
792 : }
793 : }
794 1956 : return RawRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
795 : pData, nBufXSize, nBufYSize, eBufType,
796 1956 : nPixelSpace, nLineSpace, psExtraArg);
797 : }
798 :
799 : /************************************************************************/
800 : /* SetMaskBand() */
801 : /************************************************************************/
802 :
803 243 : void ISIS3RawRasterBand::SetMaskBand(std::unique_ptr<GDALRasterBand> poMaskBand)
804 : {
805 243 : poMask.reset(std::move(poMaskBand));
806 243 : nMaskFlags = 0;
807 243 : }
808 :
809 : /************************************************************************/
810 : /* GetOffset() */
811 : /************************************************************************/
812 :
813 170 : double ISIS3RawRasterBand::GetOffset(int *pbSuccess)
814 : {
815 170 : if (pbSuccess)
816 25 : *pbSuccess = m_bHasOffset;
817 170 : return m_dfOffset;
818 : }
819 :
820 : /************************************************************************/
821 : /* GetScale() */
822 : /************************************************************************/
823 :
824 170 : double ISIS3RawRasterBand::GetScale(int *pbSuccess)
825 : {
826 170 : if (pbSuccess)
827 25 : *pbSuccess = m_bHasScale;
828 170 : return m_dfScale;
829 : }
830 :
831 : /************************************************************************/
832 : /* SetOffset() */
833 : /************************************************************************/
834 :
835 51 : CPLErr ISIS3RawRasterBand::SetOffset(double dfNewOffset)
836 : {
837 51 : m_dfOffset = dfNewOffset;
838 51 : m_bHasOffset = true;
839 51 : return CE_None;
840 : }
841 :
842 : /************************************************************************/
843 : /* SetScale() */
844 : /************************************************************************/
845 :
846 51 : CPLErr ISIS3RawRasterBand::SetScale(double dfNewScale)
847 : {
848 51 : m_dfScale = dfNewScale;
849 51 : m_bHasScale = true;
850 51 : return CE_None;
851 : }
852 :
853 : /************************************************************************/
854 : /* GetNoDataValue() */
855 : /************************************************************************/
856 :
857 148 : double ISIS3RawRasterBand::GetNoDataValue(int *pbSuccess)
858 : {
859 148 : if (pbSuccess)
860 97 : *pbSuccess = true;
861 148 : return m_dfNoData;
862 : }
863 :
864 : /************************************************************************/
865 : /* SetNoDataValue() */
866 : /************************************************************************/
867 :
868 382 : CPLErr ISIS3RawRasterBand::SetNoDataValue(double dfNewNoData)
869 : {
870 382 : m_dfNoData = dfNewNoData;
871 382 : return CE_None;
872 : }
873 :
874 : /************************************************************************/
875 : /* ISIS3WrapperRasterBand() */
876 : /************************************************************************/
877 :
878 45 : ISIS3WrapperRasterBand::ISIS3WrapperRasterBand(GDALRasterBand *poBaseBandIn)
879 45 : : m_poBaseBand(poBaseBandIn)
880 : {
881 45 : eDataType = m_poBaseBand->GetRasterDataType();
882 45 : m_poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
883 45 : }
884 :
885 : /************************************************************************/
886 : /* SetMaskBand() */
887 : /************************************************************************/
888 :
889 21 : void ISIS3WrapperRasterBand::SetMaskBand(
890 : std::unique_ptr<GDALRasterBand> poMaskBand)
891 : {
892 21 : poMask.reset(std::move(poMaskBand));
893 21 : nMaskFlags = 0;
894 21 : }
895 :
896 : /************************************************************************/
897 : /* GetOffset() */
898 : /************************************************************************/
899 :
900 22 : double ISIS3WrapperRasterBand::GetOffset(int *pbSuccess)
901 : {
902 22 : if (pbSuccess)
903 4 : *pbSuccess = m_bHasOffset;
904 22 : return m_dfOffset;
905 : }
906 :
907 : /************************************************************************/
908 : /* GetScale() */
909 : /************************************************************************/
910 :
911 22 : double ISIS3WrapperRasterBand::GetScale(int *pbSuccess)
912 : {
913 22 : if (pbSuccess)
914 4 : *pbSuccess = m_bHasScale;
915 22 : return m_dfScale;
916 : }
917 :
918 : /************************************************************************/
919 : /* SetOffset() */
920 : /************************************************************************/
921 :
922 12 : CPLErr ISIS3WrapperRasterBand::SetOffset(double dfNewOffset)
923 : {
924 12 : m_dfOffset = dfNewOffset;
925 12 : m_bHasOffset = true;
926 :
927 12 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
928 12 : if (poGDS->m_poExternalDS && eAccess == GA_Update)
929 4 : poGDS->m_poExternalDS->GetRasterBand(nBand)->SetOffset(dfNewOffset);
930 :
931 12 : return CE_None;
932 : }
933 :
934 : /************************************************************************/
935 : /* SetScale() */
936 : /************************************************************************/
937 :
938 12 : CPLErr ISIS3WrapperRasterBand::SetScale(double dfNewScale)
939 : {
940 12 : m_dfScale = dfNewScale;
941 12 : m_bHasScale = true;
942 :
943 12 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
944 12 : if (poGDS->m_poExternalDS && eAccess == GA_Update)
945 4 : poGDS->m_poExternalDS->GetRasterBand(nBand)->SetScale(dfNewScale);
946 :
947 12 : return CE_None;
948 : }
949 :
950 : /************************************************************************/
951 : /* GetNoDataValue() */
952 : /************************************************************************/
953 :
954 4 : double ISIS3WrapperRasterBand::GetNoDataValue(int *pbSuccess)
955 : {
956 4 : if (pbSuccess)
957 4 : *pbSuccess = true;
958 4 : return m_dfNoData;
959 : }
960 :
961 : /************************************************************************/
962 : /* SetNoDataValue() */
963 : /************************************************************************/
964 :
965 45 : CPLErr ISIS3WrapperRasterBand::SetNoDataValue(double dfNewNoData)
966 : {
967 45 : m_dfNoData = dfNewNoData;
968 :
969 45 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
970 45 : if (poGDS->m_poExternalDS && eAccess == GA_Update)
971 25 : poGDS->m_poExternalDS->GetRasterBand(nBand)->SetNoDataValue(
972 25 : dfNewNoData);
973 :
974 45 : return CE_None;
975 : }
976 :
977 : /************************************************************************/
978 : /* InitFile() */
979 : /************************************************************************/
980 :
981 8 : void ISIS3WrapperRasterBand::InitFile()
982 : {
983 8 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
984 8 : if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
985 : {
986 8 : poGDS->m_bGeoTIFFInitDone = true;
987 :
988 8 : const int nBands = poGDS->GetRasterCount();
989 : // We need to make sure that blocks are written in the right order
990 22 : for (int i = 0; i < nBands; i++)
991 : {
992 14 : poGDS->m_poExternalDS->GetRasterBand(i + 1)->Fill(m_dfNoData);
993 : }
994 8 : poGDS->m_poExternalDS->FlushCache(false);
995 :
996 : // Check that blocks are effectively written in expected order.
997 : const int nBlockSizeBytes =
998 8 : nBlockXSize * nBlockYSize * GDALGetDataTypeSizeBytes(eDataType);
999 :
1000 8 : GIntBig nLastOffset = 0;
1001 8 : bool bGoOn = true;
1002 8 : const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
1003 8 : const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);
1004 22 : for (int i = 0; i < nBands && bGoOn; i++)
1005 : {
1006 641 : for (int y = 0; y < l_nBlocksPerColumn && bGoOn; y++)
1007 : {
1008 1473 : for (int x = 0; x < l_nBlocksPerRow && bGoOn; x++)
1009 : {
1010 : const char *pszBlockOffset =
1011 846 : poGDS->m_poExternalDS->GetRasterBand(i + 1)
1012 846 : ->GetMetadataItem(
1013 846 : CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y), "TIFF");
1014 846 : if (pszBlockOffset)
1015 : {
1016 846 : GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset);
1017 846 : if (i != 0 || x != 0 || y != 0)
1018 : {
1019 838 : if (nOffset != nLastOffset + nBlockSizeBytes)
1020 : {
1021 0 : CPLError(CE_Warning, CPLE_AppDefined,
1022 : "Block %d,%d band %d not at expected "
1023 : "offset",
1024 : x, y, i + 1);
1025 0 : bGoOn = false;
1026 0 : poGDS->m_bGeoTIFFAsRegularExternal = false;
1027 : }
1028 : }
1029 846 : nLastOffset = nOffset;
1030 : }
1031 : else
1032 : {
1033 0 : CPLError(CE_Warning, CPLE_AppDefined,
1034 : "Block %d,%d band %d not at expected "
1035 : "offset",
1036 : x, y, i + 1);
1037 0 : bGoOn = false;
1038 0 : poGDS->m_bGeoTIFFAsRegularExternal = false;
1039 : }
1040 : }
1041 : }
1042 : }
1043 : }
1044 8 : }
1045 :
1046 : /************************************************************************/
1047 : /* Fill() */
1048 : /************************************************************************/
1049 :
1050 4 : CPLErr ISIS3WrapperRasterBand::Fill(double dfRealValue, double dfImaginaryValue)
1051 : {
1052 4 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
1053 4 : if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData == dfRealValue)
1054 : {
1055 0 : dfRealValue = m_dfNoData;
1056 : }
1057 4 : if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
1058 : {
1059 1 : InitFile();
1060 : }
1061 :
1062 4 : return GDALProxyRasterBand::Fill(dfRealValue, dfImaginaryValue);
1063 : }
1064 :
1065 : /************************************************************************/
1066 : /* IWriteBlock() */
1067 : /************************************************************************/
1068 :
1069 0 : CPLErr ISIS3WrapperRasterBand::IWriteBlock(int nXBlock, int nYBlock,
1070 : void *pImage)
1071 :
1072 : {
1073 0 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
1074 0 : if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
1075 : {
1076 0 : RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
1077 : poGDS->m_dfSrcNoData, m_dfNoData);
1078 : }
1079 0 : if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
1080 : {
1081 0 : InitFile();
1082 : }
1083 :
1084 0 : return GDALProxyRasterBand::IWriteBlock(nXBlock, nYBlock, pImage);
1085 : }
1086 :
1087 : /************************************************************************/
1088 : /* IRasterIO() */
1089 : /************************************************************************/
1090 :
1091 46 : CPLErr ISIS3WrapperRasterBand::IRasterIO(
1092 : GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
1093 : void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
1094 : GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg *psExtraArg)
1095 :
1096 : {
1097 46 : ISIS3Dataset *poGDS = cpl::down_cast<ISIS3Dataset *>(poDS);
1098 46 : if (eRWFlag == GF_Write && poGDS->m_bGeoTIFFAsRegularExternal &&
1099 17 : !poGDS->m_bGeoTIFFInitDone)
1100 : {
1101 6 : InitFile();
1102 : }
1103 46 : if (eRWFlag == GF_Write && poGDS->m_bHasSrcNoData &&
1104 9 : poGDS->m_dfSrcNoData != m_dfNoData)
1105 : {
1106 1 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
1107 1 : if (eBufType == eDataType && nPixelSpace == nDTSize &&
1108 1 : nLineSpace == nPixelSpace * nBufXSize)
1109 : {
1110 1 : RemapNoData(eDataType, pData, nBufXSize * nBufYSize,
1111 : poGDS->m_dfSrcNoData, m_dfNoData);
1112 : }
1113 : else
1114 : {
1115 0 : const GByte *pabySrc = reinterpret_cast<GByte *>(pData);
1116 : GByte *pabyTemp = reinterpret_cast<GByte *>(
1117 0 : VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize));
1118 0 : for (int i = 0; i < nBufYSize; i++)
1119 : {
1120 0 : GDALCopyWords(pabySrc + i * nLineSpace, eBufType,
1121 : static_cast<int>(nPixelSpace),
1122 0 : pabyTemp + i * nBufXSize * nDTSize, eDataType,
1123 : nDTSize, nBufXSize);
1124 : }
1125 0 : RemapNoData(eDataType, pabyTemp, nBufXSize * nBufYSize,
1126 : poGDS->m_dfSrcNoData, m_dfNoData);
1127 0 : CPLErr eErr = GDALProxyRasterBand::IRasterIO(
1128 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize,
1129 : nBufYSize, eDataType, nDTSize,
1130 0 : static_cast<GSpacing>(nDTSize) * nBufXSize, psExtraArg);
1131 0 : VSIFree(pabyTemp);
1132 0 : return eErr;
1133 : }
1134 : }
1135 46 : return GDALProxyRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
1136 : pData, nBufXSize, nBufYSize, eBufType,
1137 46 : nPixelSpace, nLineSpace, psExtraArg);
1138 : }
1139 :
1140 : /************************************************************************/
1141 : /* ISISMaskBand() */
1142 : /************************************************************************/
1143 :
1144 305 : ISISMaskBand::ISISMaskBand(GDALRasterBand *poBaseBand)
1145 305 : : m_poBaseBand(poBaseBand), m_pBuffer(nullptr)
1146 : {
1147 305 : eDataType = GDT_UInt8;
1148 305 : poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
1149 305 : nRasterXSize = poBaseBand->GetXSize();
1150 305 : nRasterYSize = poBaseBand->GetYSize();
1151 305 : }
1152 :
1153 : /************************************************************************/
1154 : /* ~ISISMaskBand() */
1155 : /************************************************************************/
1156 :
1157 610 : ISISMaskBand::~ISISMaskBand()
1158 : {
1159 305 : VSIFree(m_pBuffer);
1160 610 : }
1161 :
1162 : /************************************************************************/
1163 : /* FillMask() */
1164 : /************************************************************************/
1165 :
1166 : template <class T>
1167 72 : static void FillMask(void *pvBuffer, GByte *pabyDst, int nReqXSize,
1168 : int nReqYSize, int nBlockXSize, T NULL_VAL, T LOW_REPR_SAT,
1169 : T LOW_INSTR_SAT, T HIGH_INSTR_SAT, T HIGH_REPR_SAT)
1170 : {
1171 72 : const T *pSrc = static_cast<T *>(pvBuffer);
1172 148 : for (int y = 0; y < nReqYSize; y++)
1173 : {
1174 9708 : for (int x = 0; x < nReqXSize; x++)
1175 : {
1176 9632 : const T nSrc = pSrc[y * nBlockXSize + x];
1177 9632 : if (nSrc == NULL_VAL || nSrc == LOW_REPR_SAT ||
1178 6418 : nSrc == LOW_INSTR_SAT || nSrc == HIGH_INSTR_SAT ||
1179 : nSrc == HIGH_REPR_SAT)
1180 : {
1181 3214 : pabyDst[y * nBlockXSize + x] = 0;
1182 : }
1183 : else
1184 : {
1185 6418 : pabyDst[y * nBlockXSize + x] = 255;
1186 : }
1187 : }
1188 : }
1189 72 : }
1190 :
1191 : /************************************************************************/
1192 : /* IReadBlock() */
1193 : /************************************************************************/
1194 :
1195 72 : CPLErr ISISMaskBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
1196 :
1197 : {
1198 72 : const GDALDataType eSrcDT = m_poBaseBand->GetRasterDataType();
1199 72 : const int nSrcDTSize = GDALGetDataTypeSizeBytes(eSrcDT);
1200 72 : if (m_pBuffer == nullptr)
1201 : {
1202 24 : m_pBuffer = VSI_MALLOC3_VERBOSE(nBlockXSize, nBlockYSize, nSrcDTSize);
1203 24 : if (m_pBuffer == nullptr)
1204 0 : return CE_Failure;
1205 : }
1206 :
1207 72 : const int nXOff = nBlockXOff * nBlockXSize;
1208 72 : const int nReqXSize = std::min(nBlockXSize, nRasterXSize - nXOff);
1209 72 : const int nYOff = nBlockYOff * nBlockYSize;
1210 72 : const int nReqYSize = std::min(nBlockYSize, nRasterYSize - nYOff);
1211 :
1212 144 : if (m_poBaseBand->RasterIO(GF_Read, nXOff, nYOff, nReqXSize, nReqYSize,
1213 : m_pBuffer, nReqXSize, nReqYSize, eSrcDT,
1214 : nSrcDTSize,
1215 72 : static_cast<GSpacing>(nSrcDTSize) * nBlockXSize,
1216 72 : nullptr) != CE_None)
1217 : {
1218 0 : return CE_Failure;
1219 : }
1220 :
1221 72 : GByte *pabyDst = static_cast<GByte *>(pImage);
1222 72 : if (eSrcDT == GDT_UInt8)
1223 : {
1224 48 : FillMask<GByte>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
1225 : ISIS3_NULL1, LOW_REPR_SAT1, LOW_INSTR_SAT1,
1226 : HIGH_INSTR_SAT1, HIGH_REPR_SAT1);
1227 : }
1228 24 : else if (eSrcDT == GDT_UInt16)
1229 : {
1230 8 : FillMask<GUInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
1231 : ISIS3_NULLU2, LOW_REPR_SATU2, LOW_INSTR_SATU2,
1232 : HIGH_INSTR_SATU2, HIGH_REPR_SATU2);
1233 : }
1234 16 : else if (eSrcDT == GDT_Int16)
1235 : {
1236 8 : FillMask<GInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
1237 : ISIS3_NULL2, LOW_REPR_SAT2, LOW_INSTR_SAT2,
1238 : HIGH_INSTR_SAT2, HIGH_REPR_SAT2);
1239 : }
1240 : else
1241 : {
1242 8 : CPLAssert(eSrcDT == GDT_Float32);
1243 8 : FillMask<float>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
1244 : ISIS3_NULL4, LOW_REPR_SAT4, LOW_INSTR_SAT4,
1245 : HIGH_INSTR_SAT4, HIGH_REPR_SAT4);
1246 : }
1247 :
1248 72 : return CE_None;
1249 : }
1250 :
1251 : /************************************************************************/
1252 : /* ISIS3Dataset() */
1253 : /************************************************************************/
1254 :
1255 400 : ISIS3Dataset::ISIS3Dataset()
1256 : {
1257 400 : m_oKeywords.SetStripSurroundingQuotes(true);
1258 :
1259 : // Deinit JSON objects
1260 400 : m_oJSonLabel.Deinit();
1261 400 : m_oSrcJSonLabel.Deinit();
1262 400 : }
1263 :
1264 : /************************************************************************/
1265 : /* ~ISIS3Dataset() */
1266 : /************************************************************************/
1267 :
1268 800 : ISIS3Dataset::~ISIS3Dataset()
1269 :
1270 : {
1271 400 : ISIS3Dataset::Close();
1272 800 : }
1273 :
1274 : /************************************************************************/
1275 : /* Close() */
1276 : /************************************************************************/
1277 :
1278 774 : CPLErr ISIS3Dataset::Close(GDALProgressFunc, void *)
1279 : {
1280 774 : CPLErr eErr = CE_None;
1281 774 : if (nOpenFlags != OPEN_FLAGS_CLOSED)
1282 : {
1283 400 : if (!m_bIsLabelWritten)
1284 72 : WriteLabel();
1285 400 : if (m_poExternalDS && m_bGeoTIFFAsRegularExternal &&
1286 8 : !m_bGeoTIFFInitDone)
1287 : {
1288 : cpl::down_cast<ISIS3WrapperRasterBand *>(GetRasterBand(1))
1289 0 : ->InitFile();
1290 : }
1291 400 : if (ISIS3Dataset::FlushCache(true) != CE_None)
1292 0 : eErr = CE_Failure;
1293 400 : if (m_fpLabel)
1294 : {
1295 131 : if (VSIFCloseL(m_fpLabel) != 0)
1296 0 : eErr = CE_Failure;
1297 : }
1298 400 : if (m_fpImage && m_fpImage != m_fpLabel)
1299 : {
1300 247 : if (VSIFCloseL(m_fpImage) != 0)
1301 0 : eErr = CE_Failure;
1302 : }
1303 :
1304 400 : ISIS3Dataset::CloseDependentDatasets();
1305 400 : if (GDALPamDataset::Close() != CE_None)
1306 0 : eErr = CE_Failure;
1307 : }
1308 774 : return eErr;
1309 : }
1310 :
1311 : /************************************************************************/
1312 : /* CloseDependentDatasets() */
1313 : /************************************************************************/
1314 :
1315 400 : int ISIS3Dataset::CloseDependentDatasets()
1316 : {
1317 400 : int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();
1318 :
1319 400 : if (m_poExternalDS)
1320 : {
1321 43 : bHasDroppedRef = FALSE;
1322 43 : delete m_poExternalDS;
1323 43 : m_poExternalDS = nullptr;
1324 : }
1325 :
1326 877 : for (int iBand = 0; iBand < nBands; iBand++)
1327 : {
1328 477 : delete papoBands[iBand];
1329 : }
1330 400 : nBands = 0;
1331 :
1332 400 : return bHasDroppedRef;
1333 : }
1334 :
1335 : /************************************************************************/
1336 : /* GetFileList() */
1337 : /************************************************************************/
1338 :
1339 90 : char **ISIS3Dataset::GetFileList()
1340 :
1341 : {
1342 90 : char **papszFileList = GDALPamDataset::GetFileList();
1343 :
1344 90 : if (!m_osExternalFilename.empty())
1345 27 : papszFileList = CSLAddString(papszFileList, m_osExternalFilename);
1346 116 : for (int i = 0; i < m_aosAdditionalFiles.Count(); ++i)
1347 : {
1348 26 : if (CSLFindString(papszFileList, m_aosAdditionalFiles[i]) < 0)
1349 : {
1350 : papszFileList =
1351 26 : CSLAddString(papszFileList, m_aosAdditionalFiles[i]);
1352 : }
1353 : }
1354 :
1355 90 : return papszFileList;
1356 : }
1357 :
1358 : /************************************************************************/
1359 : /* GetSpatialRef() */
1360 : /************************************************************************/
1361 :
1362 78 : const OGRSpatialReference *ISIS3Dataset::GetSpatialRef() const
1363 :
1364 : {
1365 78 : if (!m_oSRS.IsEmpty())
1366 54 : return &m_oSRS;
1367 :
1368 24 : return GDALPamDataset::GetSpatialRef();
1369 : }
1370 :
1371 : /************************************************************************/
1372 : /* SetSpatialRef() */
1373 : /************************************************************************/
1374 :
1375 64 : CPLErr ISIS3Dataset::SetSpatialRef(const OGRSpatialReference *poSRS)
1376 : {
1377 64 : if (eAccess == GA_ReadOnly)
1378 0 : return GDALPamDataset::SetSpatialRef(poSRS);
1379 64 : if (poSRS)
1380 64 : m_oSRS = *poSRS;
1381 : else
1382 0 : m_oSRS.Clear();
1383 64 : if (m_poExternalDS)
1384 6 : m_poExternalDS->SetSpatialRef(poSRS);
1385 64 : InvalidateLabel();
1386 64 : return CE_None;
1387 : }
1388 :
1389 : /************************************************************************/
1390 : /* GetGeoTransform() */
1391 : /************************************************************************/
1392 :
1393 87 : CPLErr ISIS3Dataset::GetGeoTransform(GDALGeoTransform >) const
1394 :
1395 : {
1396 87 : if (m_bGotTransform)
1397 : {
1398 65 : gt = m_gt;
1399 65 : return CE_None;
1400 : }
1401 :
1402 22 : return GDALPamDataset::GetGeoTransform(gt);
1403 : }
1404 :
1405 : /************************************************************************/
1406 : /* SetGeoTransform() */
1407 : /************************************************************************/
1408 :
1409 56 : CPLErr ISIS3Dataset::SetGeoTransform(const GDALGeoTransform >)
1410 :
1411 : {
1412 56 : if (eAccess == GA_ReadOnly)
1413 0 : return GDALPamDataset::SetGeoTransform(gt);
1414 56 : if (gt.xscale <= 0.0 || gt.xscale != -gt.yscale || gt.xrot != 0.0 ||
1415 56 : gt.yrot != 0.0)
1416 : {
1417 0 : CPLError(CE_Failure, CPLE_NotSupported,
1418 : "Only north-up geotransform with square pixels supported");
1419 0 : return CE_Failure;
1420 : }
1421 56 : m_bGotTransform = true;
1422 56 : m_gt = gt;
1423 56 : if (m_poExternalDS)
1424 6 : m_poExternalDS->SetGeoTransform(m_gt);
1425 56 : InvalidateLabel();
1426 56 : return CE_None;
1427 : }
1428 :
1429 : /************************************************************************/
1430 : /* GetMetadataDomainList() */
1431 : /************************************************************************/
1432 :
1433 1 : char **ISIS3Dataset::GetMetadataDomainList()
1434 : {
1435 1 : return BuildMetadataDomainList(nullptr, FALSE, "", "json:ISIS3", nullptr);
1436 : }
1437 :
1438 : /************************************************************************/
1439 : /* GetMetadata() */
1440 : /************************************************************************/
1441 :
1442 128 : CSLConstList ISIS3Dataset::GetMetadata(const char *pszDomain)
1443 : {
1444 128 : if (pszDomain != nullptr && EQUAL(pszDomain, "json:ISIS3"))
1445 : {
1446 66 : if (m_aosISIS3MD.empty())
1447 : {
1448 60 : if (eAccess == GA_Update && !m_oJSonLabel.IsValid())
1449 : {
1450 1 : BuildLabel();
1451 : }
1452 60 : CPLAssert(m_oJSonLabel.IsValid());
1453 60 : if (m_bResolveOfflineContent && !m_bHasResolvedOfflineContent)
1454 : {
1455 59 : ResolveOfflineContentOfLabel();
1456 : }
1457 : const CPLString osJson =
1458 120 : m_oJSonLabel.Format(CPLJSONObject::PrettyFormat::Pretty);
1459 60 : m_aosISIS3MD.InsertString(0, osJson.c_str());
1460 : }
1461 66 : return m_aosISIS3MD.List();
1462 : }
1463 62 : return GDALPamDataset::GetMetadata(pszDomain);
1464 : }
1465 :
1466 : /************************************************************************/
1467 : /* ResolveOfflineContentOfLabel() */
1468 : /************************************************************************/
1469 :
1470 59 : void ISIS3Dataset::ResolveOfflineContentOfLabel()
1471 : {
1472 59 : m_bHasResolvedOfflineContent = true;
1473 :
1474 118 : std::vector<GByte> abyData;
1475 :
1476 296 : for (CPLJSONObject &oObj : m_oJSonLabel.GetChildren())
1477 : {
1478 237 : if (oObj.GetType() == CPLJSONObject::Type::Object)
1479 : {
1480 179 : CPLString osContainerName = oObj.GetName();
1481 358 : CPLJSONObject oContainerName = oObj.GetObj("_container_name");
1482 179 : if (oContainerName.GetType() == CPLJSONObject::Type::String)
1483 : {
1484 72 : osContainerName = oContainerName.ToString();
1485 : }
1486 :
1487 179 : std::string osFilename;
1488 179 : CPLJSONObject oFilename = oObj.GetObj("^" + osContainerName);
1489 179 : if (oFilename.GetType() == CPLJSONObject::Type::String)
1490 : {
1491 : VSIStatBufL sStat;
1492 108 : osFilename = CPLFormFilenameSafe(
1493 72 : CPLGetPathSafe(GetDescription()).c_str(),
1494 108 : oFilename.ToString().c_str(), nullptr);
1495 36 : if (CPLHasPathTraversal(oFilename.ToString().c_str()))
1496 : {
1497 0 : CPLError(CE_Warning, CPLE_AppDefined,
1498 : "Path traversal detected for ^%s: %s",
1499 : osContainerName.c_str(),
1500 0 : oFilename.ToString().c_str());
1501 17 : continue;
1502 : }
1503 36 : else if (VSIStatL(osFilename.c_str(), &sStat) != 0)
1504 : {
1505 17 : CPLDebug("ISIS3", "File %s referenced but not foud",
1506 : osFilename.c_str());
1507 17 : continue;
1508 : }
1509 : }
1510 : else
1511 : {
1512 143 : osFilename = GetDescription();
1513 : }
1514 :
1515 324 : CPLJSONObject oBytes = oObj.GetObj("Bytes");
1516 162 : if (oBytes.GetType() == CPLJSONObject::Type::Long)
1517 : {
1518 0 : CPLError(CE_Warning, CPLE_AppDefined,
1519 : "Too large content reference by %s to be captured in "
1520 : "json:ISIS3 metadata domain",
1521 0 : oObj.GetName().c_str());
1522 0 : continue;
1523 : }
1524 257 : else if (oBytes.GetType() != CPLJSONObject::Type::Integer ||
1525 95 : oBytes.ToInteger() <= 0)
1526 : {
1527 67 : continue;
1528 : }
1529 95 : if (oBytes.ToInteger() > m_nMaxOfflineContentSize)
1530 : {
1531 1 : CPLError(CE_Warning, CPLE_AppDefined,
1532 : "Too large content reference by %s to be captured in "
1533 : "json:ISIS3 metadata domain",
1534 2 : oObj.GetName().c_str());
1535 1 : continue;
1536 : }
1537 :
1538 188 : CPLJSONObject oStartByte = oObj.GetObj("StartByte");
1539 94 : if ((oStartByte.GetType() != CPLJSONObject::Type::Integer &&
1540 143 : oStartByte.GetType() != CPLJSONObject::Type::Long) ||
1541 49 : oStartByte.ToLong() <= 0)
1542 : {
1543 45 : continue;
1544 : }
1545 :
1546 : // 1-based offsets
1547 : const auto nOffset =
1548 49 : static_cast<vsi_l_offset>(oStartByte.ToLong() - 1);
1549 :
1550 49 : const auto nSize = static_cast<size_t>(oBytes.ToInteger());
1551 : try
1552 : {
1553 49 : abyData.resize(nSize);
1554 : }
1555 0 : catch (const std::exception &)
1556 : {
1557 0 : CPLError(CE_Warning, CPLE_AppDefined,
1558 : "Out of memory: too large content referenced by %s "
1559 : "to be captured in json:ISIS3 metadata domain",
1560 0 : oObj.GetName().c_str());
1561 0 : continue;
1562 : }
1563 :
1564 49 : VSIVirtualHandleUniquePtr fp(VSIFOpenL(osFilename.c_str(), "rb"));
1565 49 : if (!fp)
1566 : {
1567 0 : CPLError(CE_Warning, CPLE_FileIO,
1568 : "Cannot open %s referenced by %s", osFilename.c_str(),
1569 0 : oObj.GetName().c_str());
1570 0 : continue;
1571 : }
1572 :
1573 98 : if (fp->Seek(nOffset, SEEK_SET) != 0 ||
1574 49 : fp->Read(abyData.data(), abyData.size(), 1) != 1)
1575 : {
1576 0 : CPLError(CE_Warning, CPLE_FileIO,
1577 : "Cannot read %u bytes at offset %" PRIu64
1578 : " in %s, referenced by %s",
1579 0 : static_cast<unsigned>(abyData.size()),
1580 : static_cast<uint64_t>(nOffset), osFilename.c_str(),
1581 0 : oObj.GetName().c_str());
1582 0 : continue;
1583 : }
1584 :
1585 98 : CPLJSONObject oData;
1586 49 : char *pszHex = CPLBinaryToHex(static_cast<int>(abyData.size()),
1587 49 : abyData.data());
1588 49 : oObj.Add("_data", pszHex);
1589 49 : CPLFree(pszHex);
1590 : }
1591 : }
1592 59 : }
1593 :
1594 : /************************************************************************/
1595 : /* InvalidateLabel() */
1596 : /************************************************************************/
1597 :
1598 148 : void ISIS3Dataset::InvalidateLabel()
1599 : {
1600 148 : m_oJSonLabel.Deinit();
1601 148 : m_aosISIS3MD.Clear();
1602 148 : m_bHasResolvedOfflineContent = false;
1603 148 : }
1604 :
1605 : /************************************************************************/
1606 : /* SetMetadata() */
1607 : /************************************************************************/
1608 :
1609 28 : CPLErr ISIS3Dataset::SetMetadata(CSLConstList papszMD, const char *pszDomain)
1610 : {
1611 28 : if (m_bUseSrcLabel && eAccess == GA_Update && pszDomain != nullptr &&
1612 28 : EQUAL(pszDomain, "json:ISIS3"))
1613 : {
1614 28 : m_oSrcJSonLabel.Deinit();
1615 28 : InvalidateLabel();
1616 28 : if (papszMD != nullptr && papszMD[0] != nullptr)
1617 : {
1618 28 : CPLJSONDocument oJSONDocument;
1619 28 : const GByte *pabyData = reinterpret_cast<const GByte *>(papszMD[0]);
1620 28 : if (!oJSONDocument.LoadMemory(pabyData))
1621 : {
1622 1 : return CE_Failure;
1623 : }
1624 :
1625 27 : m_oSrcJSonLabel = oJSONDocument.GetRoot();
1626 27 : if (!m_oSrcJSonLabel.IsValid())
1627 : {
1628 0 : return CE_Failure;
1629 : }
1630 : }
1631 27 : return CE_None;
1632 : }
1633 0 : return GDALPamDataset::SetMetadata(papszMD, pszDomain);
1634 : }
1635 :
1636 : /************************************************************************/
1637 : /* GetRawBinaryLayout() */
1638 : /************************************************************************/
1639 :
1640 2 : bool ISIS3Dataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
1641 : {
1642 2 : if (m_sLayout.osRawFilename.empty())
1643 0 : return false;
1644 2 : sLayout = m_sLayout;
1645 2 : return true;
1646 : }
1647 :
1648 : /************************************************************************/
1649 : /* GetValueAndUnits() */
1650 : /************************************************************************/
1651 :
1652 50 : static void GetValueAndUnits(const CPLJSONObject &obj,
1653 : std::vector<double> &adfValues,
1654 : std::vector<std::string> &aosUnits,
1655 : int nExpectedVals)
1656 : {
1657 100 : if (obj.GetType() == CPLJSONObject::Type::Integer ||
1658 50 : obj.GetType() == CPLJSONObject::Type::Double)
1659 : {
1660 32 : adfValues.push_back(obj.ToDouble());
1661 : }
1662 18 : else if (obj.GetType() == CPLJSONObject::Type::Object)
1663 : {
1664 24 : auto oValue = obj.GetObj("value");
1665 24 : auto oUnit = obj.GetObj("unit");
1666 8 : if (oValue.IsValid() &&
1667 8 : (oValue.GetType() == CPLJSONObject::Type::Integer ||
1668 2 : oValue.GetType() == CPLJSONObject::Type::Double ||
1669 2 : oValue.GetType() == CPLJSONObject::Type::Array) &&
1670 16 : oUnit.IsValid() && oUnit.GetType() == CPLJSONObject::Type::String)
1671 : {
1672 8 : if (oValue.GetType() == CPLJSONObject::Type::Array)
1673 : {
1674 2 : GetValueAndUnits(oValue, adfValues, aosUnits, nExpectedVals);
1675 : }
1676 : else
1677 : {
1678 6 : adfValues.push_back(oValue.ToDouble());
1679 : }
1680 8 : aosUnits.push_back(oUnit.ToString());
1681 : }
1682 : }
1683 10 : else if (obj.GetType() == CPLJSONObject::Type::Array)
1684 : {
1685 10 : auto oArray = obj.ToArray();
1686 10 : if (oArray.Size() == nExpectedVals)
1687 : {
1688 34 : for (int i = 0; i < nExpectedVals; i++)
1689 : {
1690 60 : if (oArray[i].GetType() == CPLJSONObject::Type::Integer ||
1691 36 : oArray[i].GetType() == CPLJSONObject::Type::Double)
1692 : {
1693 24 : adfValues.push_back(oArray[i].ToDouble());
1694 : }
1695 : else
1696 : {
1697 0 : adfValues.clear();
1698 0 : return;
1699 : }
1700 : }
1701 : }
1702 : }
1703 : }
1704 :
1705 : /************************************************************************/
1706 : /* Open() */
1707 : /************************************************************************/
1708 :
1709 269 : GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo)
1710 :
1711 : {
1712 : /* -------------------------------------------------------------------- */
1713 : /* Does this look like a CUBE dataset? */
1714 : /* -------------------------------------------------------------------- */
1715 269 : if (!ISIS3DriverIdentify(poOpenInfo))
1716 0 : return nullptr;
1717 :
1718 : /* -------------------------------------------------------------------- */
1719 : /* Open the file using the large file API. */
1720 : /* -------------------------------------------------------------------- */
1721 538 : auto poDS = std::make_unique<ISIS3Dataset>();
1722 :
1723 269 : if (!poDS->m_oKeywords.Ingest(poOpenInfo->fpL, 0))
1724 : {
1725 1 : VSIFCloseL(poOpenInfo->fpL);
1726 1 : poOpenInfo->fpL = nullptr;
1727 1 : return nullptr;
1728 : }
1729 :
1730 268 : poDS->m_bResolveOfflineContent = CPLTestBool(CSLFetchNameValueDef(
1731 268 : poOpenInfo->papszOpenOptions, "INCLUDE_OFFLINE_CONTENT", "YES"));
1732 268 : poDS->m_nMaxOfflineContentSize = std::max(
1733 268 : 0, atoi(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
1734 268 : "MAX_SIZE_OFFLINE_CONTENT", "100000000")));
1735 :
1736 268 : poDS->m_oJSonLabel = poDS->m_oKeywords.GetJsonObject();
1737 268 : poDS->m_oJSonLabel.Add("_filename", poOpenInfo->pszFilename);
1738 :
1739 : // Find additional files from the label
1740 1329 : for (const CPLJSONObject &oObj : poDS->m_oJSonLabel.GetChildren())
1741 : {
1742 1061 : if (oObj.GetType() == CPLJSONObject::Type::Object)
1743 : {
1744 1586 : CPLString osContainerName = oObj.GetName();
1745 2379 : CPLJSONObject oContainerName = oObj.GetObj("_container_name");
1746 793 : if (oContainerName.GetType() == CPLJSONObject::Type::String)
1747 : {
1748 286 : osContainerName = oContainerName.ToString();
1749 : }
1750 :
1751 1586 : CPLJSONObject oFilename = oObj.GetObj("^" + osContainerName);
1752 793 : if (oFilename.GetType() == CPLJSONObject::Type::String)
1753 : {
1754 : VSIStatBufL sStat;
1755 369 : const CPLString osFilename(CPLFormFilenameSafe(
1756 246 : CPLGetPathSafe(poOpenInfo->pszFilename).c_str(),
1757 492 : oFilename.ToString().c_str(), nullptr));
1758 123 : if (CPLHasPathTraversal(oFilename.ToString().c_str()))
1759 : {
1760 0 : CPLError(CE_Warning, CPLE_AppDefined,
1761 : "Path traversal detected for ^%s: %s",
1762 : osContainerName.c_str(),
1763 0 : oFilename.ToString().c_str());
1764 : }
1765 123 : else if (VSIStatL(osFilename, &sStat) == 0)
1766 : {
1767 81 : poDS->m_aosAdditionalFiles.AddString(osFilename);
1768 : }
1769 : else
1770 : {
1771 42 : CPLDebug("ISIS3", "File %s referenced but not foud",
1772 : osFilename.c_str());
1773 : }
1774 : }
1775 : }
1776 : }
1777 :
1778 268 : VSIFCloseL(poOpenInfo->fpL);
1779 268 : poOpenInfo->fpL = nullptr;
1780 :
1781 : /* -------------------------------------------------------------------- */
1782 : /* Assume user is pointing to label (i.e. .lbl) file for detached option */
1783 : /* -------------------------------------------------------------------- */
1784 : // Image can be inline or detached and point to an image name
1785 : // the Format can be Tiled or Raw
1786 : // Object = Core
1787 : // StartByte = 65537
1788 : // Format = Tile
1789 : // TileSamples = 128
1790 : // TileLines = 128
1791 : // OR-----
1792 : // Object = Core
1793 : // StartByte = 1
1794 : // ^Core = r0200357_detatched.cub
1795 : // Format = BandSequential
1796 : // OR-----
1797 : // Object = Core
1798 : // StartByte = 1
1799 : // ^Core = r0200357_detached_tiled.cub
1800 : // Format = Tile
1801 : // TileSamples = 128
1802 : // TileLines = 128
1803 : // OR-----
1804 : // Object = Core
1805 : // StartByte = 1
1806 : // ^Core = some.tif
1807 : // Format = GeoTIFF
1808 :
1809 : /* -------------------------------------------------------------------- */
1810 : /* What file contains the actual data? */
1811 : /* -------------------------------------------------------------------- */
1812 268 : const char *pszCore = poDS->GetKeyword("IsisCube.Core.^Core");
1813 : CPLString osQubeFile(
1814 268 : EQUAL(pszCore, "")
1815 364 : ? CPLString(poOpenInfo->pszFilename)
1816 : : CPLFormFilenameSafe(
1817 460 : CPLGetPathSafe(poOpenInfo->pszFilename).c_str(), pszCore,
1818 536 : nullptr));
1819 268 : if (CPLHasPathTraversal(pszCore))
1820 : {
1821 0 : CPLError(CE_Failure, CPLE_NotSupported,
1822 : "Path traversal detected in IsisCube.Core.^Core: %s", pszCore);
1823 0 : return nullptr;
1824 : }
1825 268 : if (!EQUAL(pszCore, ""))
1826 : {
1827 96 : poDS->m_osExternalFilename = osQubeFile;
1828 : }
1829 :
1830 : /* -------------------------------------------------------------------- */
1831 : /* Check if file an ISIS3 header file? Read a few lines of text */
1832 : /* searching for something starting with nrows or ncols. */
1833 : /* -------------------------------------------------------------------- */
1834 :
1835 : /************* Skipbytes *****************************/
1836 268 : int nSkipBytes = atoi(poDS->GetKeyword("IsisCube.Core.StartByte", "1"));
1837 268 : if (nSkipBytes <= 1)
1838 99 : nSkipBytes = 0;
1839 : else
1840 169 : nSkipBytes -= 1;
1841 :
1842 : /******* Grab format type (BandSequential, Tiled) *******/
1843 536 : CPLString osFormat = poDS->GetKeyword("IsisCube.Core.Format");
1844 :
1845 268 : int tileSizeX = 0;
1846 268 : int tileSizeY = 0;
1847 :
1848 268 : if (EQUAL(osFormat, "Tile"))
1849 : {
1850 26 : poDS->m_bIsTiled = true;
1851 : /******* Get Tile Sizes *********/
1852 26 : tileSizeX = atoi(poDS->GetKeyword("IsisCube.Core.TileSamples"));
1853 26 : tileSizeY = atoi(poDS->GetKeyword("IsisCube.Core.TileLines"));
1854 26 : if (tileSizeX <= 0 || tileSizeY <= 0)
1855 : {
1856 1 : CPLError(CE_Failure, CPLE_OpenFailed,
1857 : "Wrong tile dimensions : %d x %d", tileSizeX, tileSizeY);
1858 1 : return nullptr;
1859 : }
1860 : }
1861 242 : else if (!EQUAL(osFormat, "BandSequential") && !EQUAL(osFormat, "GeoTIFF"))
1862 : {
1863 1 : CPLError(CE_Failure, CPLE_OpenFailed, "%s format not supported.",
1864 : osFormat.c_str());
1865 1 : return nullptr;
1866 : }
1867 :
1868 : /*********** Grab samples lines band ************/
1869 : const int nCols =
1870 266 : atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Samples"));
1871 266 : const int nRows = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Lines"));
1872 266 : const int nBands = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Bands"));
1873 :
1874 : /****** Grab format type - ISIS3 only supports 8,U16,S16,32 *****/
1875 266 : GDALDataType eDataType = GDT_UInt8;
1876 266 : double dfNoData = 0.0;
1877 :
1878 266 : const char *itype = poDS->GetKeyword("IsisCube.Core.Pixels.Type");
1879 266 : if (EQUAL(itype, "UnsignedByte"))
1880 : {
1881 215 : eDataType = GDT_UInt8;
1882 215 : dfNoData = ISIS3_NULL1;
1883 : }
1884 51 : else if (EQUAL(itype, "UnsignedWord"))
1885 : {
1886 17 : eDataType = GDT_UInt16;
1887 17 : dfNoData = ISIS3_NULLU2;
1888 : }
1889 34 : else if (EQUAL(itype, "SignedWord"))
1890 : {
1891 14 : eDataType = GDT_Int16;
1892 14 : dfNoData = ISIS3_NULL2;
1893 : }
1894 20 : else if (EQUAL(itype, "Real") || EQUAL(itype, ""))
1895 : {
1896 19 : eDataType = GDT_Float32;
1897 19 : dfNoData = ISIS3_NULL4;
1898 : }
1899 : else
1900 : {
1901 1 : CPLError(CE_Failure, CPLE_OpenFailed, "%s pixel type not supported.",
1902 : itype);
1903 1 : return nullptr;
1904 : }
1905 :
1906 : /*********** Grab samples lines band ************/
1907 :
1908 : // default to MSB
1909 : const bool bIsLSB =
1910 265 : EQUAL(poDS->GetKeyword("IsisCube.Core.Pixels.ByteOrder"), "Lsb");
1911 :
1912 : /*********** Grab Cellsize ************/
1913 265 : double dfXDim = 1.0;
1914 265 : double dfYDim = 1.0;
1915 :
1916 265 : const char *pszRes = poDS->GetKeyword("IsisCube.Mapping.PixelResolution");
1917 265 : if (strlen(pszRes) > 0)
1918 : {
1919 105 : dfXDim = CPLAtof(pszRes); /* values are in meters */
1920 105 : dfYDim = -CPLAtof(pszRes);
1921 : }
1922 :
1923 : /*********** Grab UpperLeftCornerY ************/
1924 265 : double dfULYMap = 0.5;
1925 :
1926 265 : const char *pszULY = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerY");
1927 265 : if (strlen(pszULY) > 0)
1928 : {
1929 105 : dfULYMap = CPLAtof(pszULY);
1930 : }
1931 :
1932 : /*********** Grab UpperLeftCornerX ************/
1933 265 : double dfULXMap = 0.5;
1934 :
1935 265 : const char *pszULX = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerX");
1936 265 : if (strlen(pszULX) > 0)
1937 : {
1938 105 : dfULXMap = CPLAtof(pszULX);
1939 : }
1940 :
1941 : // Read the projection from the ISIS PVL Mapping group.
1942 : const CPLJSONObject oMapping =
1943 795 : poDS->m_oJSonLabel.GetObj("IsisCube").GetObj("Mapping");
1944 265 : if (oMapping.IsValid())
1945 121 : poDS->m_oSRS.importFromISISPVL(oMapping);
1946 :
1947 : /* END ISIS3 Label Read */
1948 : /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
1949 :
1950 : /* -------------------------------------------------------------------- */
1951 : /* Did we get the required keywords? If not we return with */
1952 : /* this never having been considered to be a match. This isn't */
1953 : /* an error! */
1954 : /* -------------------------------------------------------------------- */
1955 529 : if (!GDALCheckDatasetDimensions(nCols, nRows) ||
1956 264 : !GDALCheckBandCount(nBands, false))
1957 : {
1958 2 : return nullptr;
1959 : }
1960 :
1961 : /* -------------------------------------------------------------------- */
1962 : /* Capture some information from the file that is of interest. */
1963 : /* -------------------------------------------------------------------- */
1964 263 : poDS->nRasterXSize = nCols;
1965 263 : poDS->nRasterYSize = nRows;
1966 :
1967 : /* -------------------------------------------------------------------- */
1968 : /* Open target binary file. */
1969 : /* -------------------------------------------------------------------- */
1970 263 : if (EQUAL(osFormat, "GeoTIFF"))
1971 : {
1972 27 : if (nSkipBytes != 0)
1973 : {
1974 2 : CPLError(CE_Warning, CPLE_NotSupported,
1975 : "Ignoring StartByte=%d for format=GeoTIFF",
1976 : 1 + nSkipBytes);
1977 : }
1978 27 : if (osQubeFile == poOpenInfo->pszFilename)
1979 : {
1980 0 : CPLError(CE_Failure, CPLE_AppDefined, "A ^Core file must be set");
1981 0 : return nullptr;
1982 : }
1983 54 : poDS->m_poExternalDS =
1984 27 : GDALDataset::Open(osQubeFile, poOpenInfo->eAccess);
1985 27 : if (poDS->m_poExternalDS == nullptr)
1986 : {
1987 2 : return nullptr;
1988 : }
1989 25 : if (poDS->m_poExternalDS->GetRasterXSize() != poDS->nRasterXSize ||
1990 24 : poDS->m_poExternalDS->GetRasterYSize() != poDS->nRasterYSize ||
1991 71 : poDS->m_poExternalDS->GetRasterCount() != nBands ||
1992 22 : poDS->m_poExternalDS->GetRasterBand(1)->GetRasterDataType() !=
1993 : eDataType)
1994 : {
1995 4 : CPLError(CE_Failure, CPLE_AppDefined,
1996 : "%s has incompatible characteristics with the ones "
1997 : "declared in the label.",
1998 : osQubeFile.c_str());
1999 4 : return nullptr;
2000 : }
2001 : }
2002 : else
2003 : {
2004 236 : if (poOpenInfo->eAccess == GA_ReadOnly)
2005 234 : poDS->m_fpImage = VSIFOpenL(osQubeFile, "r");
2006 : else
2007 2 : poDS->m_fpImage = VSIFOpenL(osQubeFile, "r+");
2008 :
2009 236 : if (poDS->m_fpImage == nullptr)
2010 : {
2011 2 : CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open %s: %s.",
2012 2 : osQubeFile.c_str(), VSIStrerror(errno));
2013 2 : return nullptr;
2014 : }
2015 :
2016 : // Sanity checks in case the external raw file appears to be a
2017 : // TIFF file
2018 234 : if (EQUAL(CPLGetExtensionSafe(osQubeFile).c_str(), "tif"))
2019 : {
2020 23 : const char *const apszAllowedDrivers[] = {"GTiff", nullptr};
2021 : auto poTIF_DS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
2022 : osQubeFile, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
2023 46 : apszAllowedDrivers));
2024 23 : if (poTIF_DS)
2025 : {
2026 23 : bool bWarned = false;
2027 23 : if (poTIF_DS->GetRasterXSize() != poDS->nRasterXSize ||
2028 22 : poTIF_DS->GetRasterYSize() != poDS->nRasterYSize ||
2029 21 : poTIF_DS->GetRasterCount() != nBands ||
2030 20 : poTIF_DS->GetRasterBand(1)->GetRasterDataType() !=
2031 45 : eDataType ||
2032 38 : poTIF_DS->GetMetadataItem(GDALMD_COMPRESSION,
2033 19 : GDAL_MDD_IMAGE_STRUCTURE) !=
2034 : nullptr)
2035 : {
2036 5 : bWarned = true;
2037 5 : CPLError(
2038 : CE_Warning, CPLE_AppDefined,
2039 : "%s has incompatible characteristics with the ones "
2040 : "declared in the label.",
2041 : osQubeFile.c_str());
2042 : }
2043 23 : int nBlockXSize = 1, nBlockYSize = 1;
2044 23 : poTIF_DS->GetRasterBand(1)->GetBlockSize(&nBlockXSize,
2045 : &nBlockYSize);
2046 23 : if ((poDS->m_bIsTiled &&
2047 46 : (nBlockXSize != tileSizeX || nBlockYSize != tileSizeY)) ||
2048 23 : (!poDS->m_bIsTiled && (nBlockXSize != nCols ||
2049 2 : (nBands > 1 && nBlockYSize != 1))))
2050 : {
2051 2 : if (!bWarned)
2052 : {
2053 1 : bWarned = true;
2054 1 : CPLError(
2055 : CE_Warning, CPLE_AppDefined,
2056 : "%s has incompatible characteristics with the ones "
2057 : "declared in the label.",
2058 : osQubeFile.c_str());
2059 : }
2060 : }
2061 : // to please Clang Static Analyzer
2062 23 : nBlockXSize = std::max(1, nBlockXSize);
2063 23 : nBlockYSize = std::max(1, nBlockYSize);
2064 :
2065 : // Check that blocks are effectively written in expected order.
2066 23 : const int nBlockSizeBytes = nBlockXSize * nBlockYSize *
2067 23 : GDALGetDataTypeSizeBytes(eDataType);
2068 23 : bool bGoOn = !bWarned;
2069 23 : const int l_nBlocksPerRow = DIV_ROUND_UP(nCols, nBlockXSize);
2070 23 : const int l_nBlocksPerColumn = DIV_ROUND_UP(nRows, nBlockYSize);
2071 23 : int nBlockNo = 0;
2072 52 : for (int i = 0; i < nBands && bGoOn; i++)
2073 : {
2074 1285 : for (int y = 0; y < l_nBlocksPerColumn && bGoOn; y++)
2075 : {
2076 2950 : for (int x = 0; x < l_nBlocksPerRow && bGoOn; x++)
2077 : {
2078 : const char *pszBlockOffset =
2079 3388 : poTIF_DS->GetRasterBand(i + 1)->GetMetadataItem(
2080 : CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y),
2081 1694 : "TIFF");
2082 1694 : if (pszBlockOffset)
2083 : {
2084 1694 : GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset);
2085 1694 : if (nOffset !=
2086 1694 : nSkipBytes + nBlockNo * nBlockSizeBytes)
2087 : {
2088 : // bWarned = true;
2089 2 : CPLError(CE_Warning, CPLE_AppDefined,
2090 : "%s has incompatible "
2091 : "characteristics with the ones "
2092 : "declared in the label.",
2093 : osQubeFile.c_str());
2094 2 : bGoOn = false;
2095 : }
2096 : }
2097 1694 : nBlockNo++;
2098 : }
2099 : }
2100 : }
2101 : }
2102 : }
2103 : }
2104 :
2105 255 : poDS->eAccess = poOpenInfo->eAccess;
2106 :
2107 : /* -------------------------------------------------------------------- */
2108 : /* Compute the line offset. */
2109 : /* -------------------------------------------------------------------- */
2110 255 : int nLineOffset = 0;
2111 255 : int nPixelOffset = 0;
2112 255 : vsi_l_offset nBandOffset = 0;
2113 :
2114 255 : if (EQUAL(osFormat, "BandSequential"))
2115 : {
2116 209 : const int nItemSize = GDALGetDataTypeSizeBytes(eDataType);
2117 209 : nPixelOffset = nItemSize;
2118 : try
2119 : {
2120 209 : nLineOffset = (CPLSM(nPixelOffset) * CPLSM(nCols)).v();
2121 : }
2122 0 : catch (const CPLSafeIntOverflow &)
2123 : {
2124 0 : return nullptr;
2125 : }
2126 209 : nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nRows;
2127 :
2128 209 : poDS->m_sLayout.osRawFilename = std::move(osQubeFile);
2129 209 : if (nBands > 1)
2130 16 : poDS->m_sLayout.eInterleaving = RawBinaryLayout::Interleaving::BSQ;
2131 209 : poDS->m_sLayout.eDataType = eDataType;
2132 209 : poDS->m_sLayout.bLittleEndianOrder = bIsLSB;
2133 209 : poDS->m_sLayout.nImageOffset = nSkipBytes;
2134 209 : poDS->m_sLayout.nPixelOffset = nPixelOffset;
2135 209 : poDS->m_sLayout.nLineOffset = nLineOffset;
2136 209 : poDS->m_sLayout.nBandOffset = static_cast<GIntBig>(nBandOffset);
2137 : }
2138 : /* else Tiled or external */
2139 :
2140 : /* -------------------------------------------------------------------- */
2141 : /* Extract BandBin info. */
2142 : /* -------------------------------------------------------------------- */
2143 510 : std::vector<std::string> aosBandNames;
2144 510 : std::vector<std::string> aosBandUnits;
2145 510 : std::vector<double> adfWavelengths;
2146 510 : std::vector<std::string> aosWavelengthsUnit;
2147 510 : std::vector<double> adfBandwidth;
2148 510 : std::vector<std::string> aosBandwidthUnit;
2149 765 : const auto oIsisCube = poDS->m_oJSonLabel.GetObj("IsisCube");
2150 255 : if (oIsisCube.GetType() == CPLJSONObject::Type::Object)
2151 : {
2152 979 : for (const auto &oChildIsisCube : oIsisCube.GetChildren())
2153 : {
2154 461 : if (oChildIsisCube.GetType() == CPLJSONObject::Type::Object &&
2155 2075 : oChildIsisCube.GetString("_type") == "group" &&
2156 1094 : (oChildIsisCube.GetName() == "BandBin" ||
2157 890 : oChildIsisCube.GetString("_container_name") == "BandBin"))
2158 : {
2159 187 : for (const auto &child : oChildIsisCube.GetChildren())
2160 : {
2161 146 : if (CPLString(child.GetName()).ifind("name") !=
2162 : std::string::npos)
2163 : {
2164 : // Use "name" in priority
2165 15 : if (EQUAL(child.GetName().c_str(), "name"))
2166 : {
2167 5 : aosBandNames.clear();
2168 : }
2169 10 : else if (!aosBandNames.empty())
2170 : {
2171 3 : continue;
2172 : }
2173 :
2174 12 : if (child.GetType() == CPLJSONObject::Type::String &&
2175 : nBands == 1)
2176 : {
2177 4 : aosBandNames.push_back(child.ToString());
2178 : }
2179 8 : else if (child.GetType() == CPLJSONObject::Type::Array)
2180 : {
2181 16 : auto oArray = child.ToArray();
2182 8 : if (oArray.Size() == nBands)
2183 : {
2184 28 : for (int i = 0; i < nBands; i++)
2185 : {
2186 20 : if (oArray[i].GetType() ==
2187 : CPLJSONObject::Type::String)
2188 : {
2189 20 : aosBandNames.push_back(
2190 40 : oArray[i].ToString());
2191 : }
2192 : else
2193 : {
2194 0 : aosBandNames.clear();
2195 0 : break;
2196 : }
2197 : }
2198 : }
2199 : }
2200 : }
2201 135 : else if (EQUAL(child.GetName().c_str(), "BandSuffixUnit") &&
2202 4 : child.GetType() == CPLJSONObject::Type::Array)
2203 : {
2204 8 : auto oArray = child.ToArray();
2205 4 : if (oArray.Size() == nBands)
2206 : {
2207 12 : for (int i = 0; i < nBands; i++)
2208 : {
2209 8 : if (oArray[i].GetType() ==
2210 : CPLJSONObject::Type::String)
2211 : {
2212 8 : aosBandUnits.push_back(
2213 16 : oArray[i].ToString());
2214 : }
2215 : else
2216 : {
2217 0 : aosBandUnits.clear();
2218 0 : break;
2219 : }
2220 : }
2221 : }
2222 : }
2223 377 : else if (EQUAL(child.GetName().c_str(), "BandBinCenter") ||
2224 250 : EQUAL(child.GetName().c_str(), "Center"))
2225 : {
2226 41 : GetValueAndUnits(child, adfWavelengths,
2227 : aosWavelengthsUnit, nBands);
2228 : }
2229 90 : else if (EQUAL(child.GetName().c_str(), "BandBinUnit") &&
2230 4 : child.GetType() == CPLJSONObject::Type::String)
2231 : {
2232 12 : CPLString unit(child.ToString());
2233 4 : if (STARTS_WITH_CI(unit, "micromet") ||
2234 0 : EQUAL(unit, "um") ||
2235 4 : STARTS_WITH_CI(unit, "nanomet") ||
2236 0 : EQUAL(unit, "nm"))
2237 : {
2238 4 : aosWavelengthsUnit.push_back(child.ToString());
2239 : }
2240 : }
2241 82 : else if (EQUAL(child.GetName().c_str(), "Width"))
2242 : {
2243 7 : GetValueAndUnits(child, adfBandwidth, aosBandwidthUnit,
2244 : nBands);
2245 : }
2246 : }
2247 :
2248 41 : if (!adfWavelengths.empty() && aosWavelengthsUnit.size() == 1)
2249 : {
2250 11 : for (int i = 1; i < nBands; i++)
2251 : {
2252 4 : aosWavelengthsUnit.push_back(aosWavelengthsUnit[0]);
2253 : }
2254 : }
2255 41 : if (!adfBandwidth.empty() && aosBandwidthUnit.size() == 1)
2256 : {
2257 7 : for (int i = 1; i < nBands; i++)
2258 : {
2259 2 : aosBandwidthUnit.push_back(aosBandwidthUnit[0]);
2260 : }
2261 : }
2262 : }
2263 : }
2264 : }
2265 :
2266 : /* -------------------------------------------------------------------- */
2267 : /* Create band information objects. */
2268 : /* -------------------------------------------------------------------- */
2269 : #ifdef CPL_LSB
2270 255 : const bool bNativeOrder = bIsLSB;
2271 : #else
2272 : const bool bNativeOrder = !bIsLSB;
2273 : #endif
2274 :
2275 560 : for (int i = 0; i < nBands; i++)
2276 : {
2277 : GDALRasterBand *poBand;
2278 :
2279 305 : if (poDS->m_poExternalDS != nullptr)
2280 : {
2281 : auto poISISBand = std::make_unique<ISIS3WrapperRasterBand>(
2282 21 : poDS->m_poExternalDS->GetRasterBand(i + 1));
2283 42 : poISISBand->SetMaskBand(
2284 42 : std::make_unique<ISISMaskBand>(poISISBand.get()));
2285 21 : poDS->SetBand(i + 1, std::move(poISISBand));
2286 21 : poBand = poDS->GetRasterBand(i + 1);
2287 : }
2288 284 : else if (poDS->m_bIsTiled)
2289 : {
2290 : auto poISISBand = std::make_unique<ISISTiledBand>(
2291 41 : poDS.get(), poDS->m_fpImage, i + 1, eDataType, tileSizeX,
2292 82 : tileSizeY, nSkipBytes, 0, 0, bNativeOrder);
2293 41 : if (!poISISBand->IsValid())
2294 : {
2295 0 : return nullptr;
2296 : }
2297 82 : poISISBand->SetMaskBand(
2298 82 : std::make_unique<ISISMaskBand>(poISISBand.get()));
2299 41 : poDS->SetBand(i + 1, std::move(poISISBand));
2300 41 : poBand = poDS->GetRasterBand(i + 1);
2301 : }
2302 : else
2303 : {
2304 : auto poISISBand = std::make_unique<ISIS3RawRasterBand>(
2305 243 : poDS.get(), i + 1, poDS->m_fpImage,
2306 243 : nSkipBytes + nBandOffset * i, nPixelOffset, nLineOffset,
2307 243 : eDataType, bNativeOrder);
2308 243 : if (!poISISBand->IsValid())
2309 : {
2310 0 : return nullptr;
2311 : }
2312 486 : poISISBand->SetMaskBand(
2313 486 : std::make_unique<ISISMaskBand>(poISISBand.get()));
2314 243 : poDS->SetBand(i + 1, std::move(poISISBand));
2315 243 : poBand = poDS->GetRasterBand(i + 1);
2316 : }
2317 :
2318 305 : if (i < static_cast<int>(aosBandNames.size()))
2319 : {
2320 17 : poBand->SetDescription(aosBandNames[i].c_str());
2321 : }
2322 354 : if (i < static_cast<int>(adfWavelengths.size()) &&
2323 49 : i < static_cast<int>(aosWavelengthsUnit.size()))
2324 : {
2325 11 : poBand->SetMetadataItem("WAVELENGTH",
2326 11 : CPLSPrintf("%f", adfWavelengths[i]));
2327 11 : poBand->SetMetadataItem("WAVELENGTH_UNIT",
2328 11 : aosWavelengthsUnit[i].c_str());
2329 18 : if (i < static_cast<int>(adfBandwidth.size()) &&
2330 7 : i < static_cast<int>(aosBandwidthUnit.size()))
2331 : {
2332 7 : poBand->SetMetadataItem("BANDWIDTH",
2333 7 : CPLSPrintf("%f", adfBandwidth[i]));
2334 7 : poBand->SetMetadataItem("BANDWIDTH_UNIT",
2335 7 : aosBandwidthUnit[i].c_str());
2336 : }
2337 : }
2338 305 : if (i < static_cast<int>(aosBandUnits.size()))
2339 : {
2340 8 : poBand->SetUnitType(aosBandUnits[i].c_str());
2341 : }
2342 :
2343 305 : poBand->SetNoDataValue(dfNoData);
2344 :
2345 : // Set offset/scale values.
2346 : const double dfOffset =
2347 305 : CPLAtofM(poDS->GetKeyword("IsisCube.Core.Pixels.Base", "0.0"));
2348 305 : const double dfScale = CPLAtofM(
2349 : poDS->GetKeyword("IsisCube.Core.Pixels.Multiplier", "1.0"));
2350 305 : if (dfOffset != 0.0 || dfScale != 1.0)
2351 : {
2352 52 : poBand->SetOffset(dfOffset);
2353 52 : poBand->SetScale(dfScale);
2354 : }
2355 : }
2356 :
2357 : /* -------------------------------------------------------------------- */
2358 : /* Check for a .prj file. For ISIS3 I would like to keep this in */
2359 : /* -------------------------------------------------------------------- */
2360 510 : const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename);
2361 510 : const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename);
2362 510 : const std::string osPrjFile = CPLFormCIFilenameSafe(osPath, osName, "prj");
2363 :
2364 255 : VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "r");
2365 255 : if (fp != nullptr)
2366 : {
2367 0 : VSIFCloseL(fp);
2368 :
2369 0 : char **papszLines = CSLLoad(osPrjFile.c_str());
2370 :
2371 0 : OGRSpatialReference oSRS2;
2372 0 : if (oSRS2.importFromESRI(papszLines) == OGRERR_NONE)
2373 : {
2374 0 : poDS->m_aosAdditionalFiles.AddString(osPrjFile.c_str());
2375 0 : poDS->m_oSRS = std::move(oSRS2);
2376 0 : poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2377 : }
2378 :
2379 0 : CSLDestroy(papszLines);
2380 : }
2381 :
2382 255 : if (dfULXMap != 0.5 || dfULYMap != 0.5 || dfXDim != 1.0 || dfYDim != 1.0)
2383 : {
2384 102 : poDS->m_bGotTransform = true;
2385 102 : poDS->m_gt.xorig = dfULXMap;
2386 102 : poDS->m_gt.xscale = dfXDim;
2387 102 : poDS->m_gt.xrot = 0.0;
2388 102 : poDS->m_gt.yorig = dfULYMap;
2389 102 : poDS->m_gt.yrot = 0.0;
2390 102 : poDS->m_gt.yscale = dfYDim;
2391 : }
2392 :
2393 255 : if (!poDS->m_bGotTransform)
2394 : {
2395 306 : poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
2396 306 : poOpenInfo->pszFilename, "cbw", poDS->m_gt.data()));
2397 153 : if (poDS->m_bGotTransform)
2398 : {
2399 0 : poDS->m_aosAdditionalFiles.AddString(
2400 0 : CPLResetExtensionSafe(poOpenInfo->pszFilename, "cbw").c_str());
2401 : }
2402 : }
2403 :
2404 255 : if (!poDS->m_bGotTransform)
2405 : {
2406 306 : poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
2407 306 : poOpenInfo->pszFilename, "wld", poDS->m_gt.data()));
2408 153 : if (poDS->m_bGotTransform)
2409 : {
2410 0 : poDS->m_aosAdditionalFiles.AddString(
2411 0 : CPLResetExtensionSafe(poOpenInfo->pszFilename, "wld").c_str());
2412 : }
2413 : }
2414 :
2415 : /* -------------------------------------------------------------------- */
2416 : /* Initialize any PAM information. */
2417 : /* -------------------------------------------------------------------- */
2418 255 : poDS->SetDescription(poOpenInfo->pszFilename);
2419 255 : poDS->TryLoadXML();
2420 :
2421 : /* -------------------------------------------------------------------- */
2422 : /* Check for overviews. */
2423 : /* -------------------------------------------------------------------- */
2424 255 : poDS->oOvManager.Initialize(poDS.get(), poOpenInfo->pszFilename);
2425 :
2426 255 : return poDS.release();
2427 : }
2428 :
2429 : /************************************************************************/
2430 : /* GetKeyword() */
2431 : /************************************************************************/
2432 :
2433 3590 : const char *ISIS3Dataset::GetKeyword(const char *pszPath,
2434 : const char *pszDefault)
2435 :
2436 : {
2437 3590 : return m_oKeywords.GetKeyword(pszPath, pszDefault);
2438 : }
2439 :
2440 : /************************************************************************/
2441 : /* FixLong() */
2442 : /************************************************************************/
2443 :
2444 247 : double ISIS3Dataset::FixLong(double dfLong)
2445 : {
2446 247 : if (m_osLongitudeDirection == "PositiveWest")
2447 4 : dfLong = -dfLong;
2448 247 : if (m_bForce360 && dfLong < 0)
2449 2 : dfLong += 360.0;
2450 247 : return dfLong;
2451 : }
2452 :
2453 : /************************************************************************/
2454 : /* BuildLabel() */
2455 : /************************************************************************/
2456 :
2457 132 : void ISIS3Dataset::BuildLabel()
2458 : {
2459 264 : CPLJSONObject oLabel = m_oSrcJSonLabel;
2460 132 : if (!oLabel.IsValid())
2461 : {
2462 105 : oLabel = CPLJSONObject();
2463 : }
2464 : // If we have a source label, then edit it directly
2465 396 : CPLJSONObject oIsisCube = GetOrCreateJSONObject(oLabel, "IsisCube");
2466 132 : oIsisCube.Set("_type", "object");
2467 :
2468 132 : if (!m_osComment.empty())
2469 1 : oIsisCube.Set("_comment", m_osComment);
2470 :
2471 396 : CPLJSONObject oCore = GetOrCreateJSONObject(oIsisCube, "Core");
2472 132 : if (oCore.GetType() != CPLJSONObject::Type::Object)
2473 : {
2474 0 : oIsisCube.Delete("Core");
2475 0 : oCore = CPLJSONObject();
2476 0 : oIsisCube.Add("Core", oCore);
2477 : }
2478 132 : oCore.Set("_type", "object");
2479 :
2480 132 : if (!m_osExternalFilename.empty())
2481 : {
2482 31 : if (m_poExternalDS && m_bGeoTIFFAsRegularExternal)
2483 : {
2484 8 : if (!m_bGeoTIFFInitDone)
2485 : {
2486 : cpl::down_cast<ISIS3WrapperRasterBand *>(GetRasterBand(1))
2487 1 : ->InitFile();
2488 : }
2489 :
2490 : const char *pszOffset =
2491 8 : m_poExternalDS->GetRasterBand(1)->GetMetadataItem(
2492 8 : "BLOCK_OFFSET_0_0", "TIFF");
2493 8 : if (pszOffset)
2494 : {
2495 8 : oCore.Set("StartByte", 1 + atoi(pszOffset));
2496 : }
2497 : else
2498 : {
2499 : // Shouldn't happen normally
2500 0 : CPLError(CE_Warning, CPLE_AppDefined,
2501 : "Missing BLOCK_OFFSET_0_0");
2502 0 : m_bGeoTIFFAsRegularExternal = false;
2503 0 : oCore.Set("StartByte", 1);
2504 8 : }
2505 : }
2506 : else
2507 : {
2508 23 : oCore.Set("StartByte", 1);
2509 : }
2510 31 : if (!m_osExternalFilename.empty())
2511 : {
2512 : const CPLString osExternalFilename =
2513 31 : CPLGetFilename(m_osExternalFilename);
2514 31 : oCore.Set("^Core", osExternalFilename);
2515 : }
2516 : }
2517 : else
2518 : {
2519 101 : oCore.Set("StartByte", pszSTARTBYTE_PLACEHOLDER);
2520 101 : oCore.Delete("^Core");
2521 : }
2522 :
2523 132 : if (m_poExternalDS && !m_bGeoTIFFAsRegularExternal)
2524 : {
2525 10 : oCore.Set("Format", "GeoTIFF");
2526 10 : oCore.Delete("TileSamples");
2527 10 : oCore.Delete("TileLines");
2528 : }
2529 122 : else if (m_bIsTiled)
2530 : {
2531 9 : oCore.Set("Format", "Tile");
2532 9 : int nBlockXSize = 1, nBlockYSize = 1;
2533 9 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
2534 9 : oCore.Set("TileSamples", nBlockXSize);
2535 9 : oCore.Set("TileLines", nBlockYSize);
2536 : }
2537 : else
2538 : {
2539 113 : oCore.Set("Format", "BandSequential");
2540 113 : oCore.Delete("TileSamples");
2541 113 : oCore.Delete("TileLines");
2542 : }
2543 :
2544 396 : CPLJSONObject oDimensions = GetOrCreateJSONObject(oCore, "Dimensions");
2545 132 : oDimensions.Set("_type", "group");
2546 132 : oDimensions.Set("Samples", nRasterXSize);
2547 132 : oDimensions.Set("Lines", nRasterYSize);
2548 132 : oDimensions.Set("Bands", nBands);
2549 :
2550 396 : CPLJSONObject oPixels = GetOrCreateJSONObject(oCore, "Pixels");
2551 132 : oPixels.Set("_type", "group");
2552 132 : const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType();
2553 159 : oPixels.Set("Type", (eDT == GDT_UInt8) ? "UnsignedByte"
2554 44 : : (eDT == GDT_UInt16) ? "UnsignedWord"
2555 17 : : (eDT == GDT_Int16) ? "SignedWord"
2556 : : "Real");
2557 :
2558 132 : oPixels.Set("ByteOrder", "Lsb");
2559 132 : oPixels.Set("Base", GetRasterBand(1)->GetOffset());
2560 132 : oPixels.Set("Multiplier", GetRasterBand(1)->GetScale());
2561 :
2562 132 : const OGRSpatialReference &oSRS = m_oSRS;
2563 :
2564 132 : if (!m_bUseSrcMapping)
2565 : {
2566 130 : oIsisCube.Delete("Mapping");
2567 : }
2568 :
2569 396 : CPLJSONObject oMapping = GetOrCreateJSONObject(oIsisCube, "Mapping");
2570 134 : if (m_bUseSrcMapping && oMapping.IsValid() &&
2571 2 : oMapping.GetType() == CPLJSONObject::Type::Object)
2572 : {
2573 2 : if (!m_osTargetName.empty())
2574 1 : oMapping.Set("TargetName", m_osTargetName);
2575 2 : if (!m_osLatitudeType.empty())
2576 1 : oMapping.Set("LatitudeType", m_osLatitudeType);
2577 2 : if (!m_osLongitudeDirection.empty())
2578 1 : oMapping.Set("LongitudeDirection", m_osLongitudeDirection);
2579 : }
2580 130 : else if (!m_bUseSrcMapping && !m_oSRS.IsEmpty())
2581 : {
2582 62 : oMapping.Add("_type", "group");
2583 :
2584 62 : if (oSRS.IsProjected() || oSRS.IsGeographic())
2585 : {
2586 62 : const char *pszDatum = oSRS.GetAttrValue("DATUM");
2587 124 : CPLString osTargetName(m_osTargetName);
2588 62 : if (osTargetName.empty())
2589 : {
2590 61 : if (pszDatum && STARTS_WITH(pszDatum, "D_"))
2591 : {
2592 24 : osTargetName = pszDatum + 2;
2593 : }
2594 37 : else if (pszDatum)
2595 : {
2596 37 : osTargetName = pszDatum;
2597 : }
2598 : }
2599 62 : if (!osTargetName.empty())
2600 62 : oMapping.Add("TargetName", osTargetName);
2601 :
2602 62 : oMapping.Add("EquatorialRadius/value", oSRS.GetSemiMajor());
2603 62 : oMapping.Add("EquatorialRadius/unit", "meters");
2604 62 : oMapping.Add("PolarRadius/value", oSRS.GetSemiMinor());
2605 62 : oMapping.Add("PolarRadius/unit", "meters");
2606 :
2607 62 : if (!m_osLatitudeType.empty())
2608 1 : oMapping.Add("LatitudeType", m_osLatitudeType);
2609 : else
2610 61 : oMapping.Add("LatitudeType", "Planetocentric");
2611 :
2612 62 : if (!m_osLongitudeDirection.empty())
2613 1 : oMapping.Add("LongitudeDirection", m_osLongitudeDirection);
2614 : else
2615 61 : oMapping.Add("LongitudeDirection", "PositiveEast");
2616 :
2617 62 : double adfX[4] = {0};
2618 62 : double adfY[4] = {0};
2619 62 : bool bLongLatCorners = false;
2620 62 : if (m_bGotTransform)
2621 : {
2622 270 : for (int i = 0; i < 4; i++)
2623 : {
2624 216 : adfX[i] = m_gt.xorig + (i % 2) * nRasterXSize * m_gt.xscale;
2625 216 : adfY[i] = m_gt.yorig + ((i == 0 || i == 3) ? 0 : 1) *
2626 216 : nRasterYSize * m_gt.yscale;
2627 : }
2628 54 : if (oSRS.IsGeographic())
2629 : {
2630 31 : bLongLatCorners = true;
2631 : }
2632 : else
2633 : {
2634 23 : OGRSpatialReference *poSRSLongLat = oSRS.CloneGeogCS();
2635 23 : if (poSRSLongLat)
2636 : {
2637 23 : poSRSLongLat->SetAxisMappingStrategy(
2638 : OAMS_TRADITIONAL_GIS_ORDER);
2639 : OGRCoordinateTransformation *poCT =
2640 23 : OGRCreateCoordinateTransformation(&oSRS,
2641 : poSRSLongLat);
2642 23 : if (poCT)
2643 : {
2644 23 : if (poCT->Transform(4, adfX, adfY))
2645 : {
2646 23 : bLongLatCorners = true;
2647 : }
2648 23 : delete poCT;
2649 : }
2650 23 : delete poSRSLongLat;
2651 : }
2652 : }
2653 : }
2654 62 : if (bLongLatCorners)
2655 : {
2656 270 : for (int i = 0; i < 4; i++)
2657 : {
2658 216 : adfX[i] = FixLong(adfX[i]);
2659 : }
2660 : }
2661 :
2662 62 : if (bLongLatCorners &&
2663 54 : (m_bForce360 || adfX[0] < -180.0 || adfX[3] > 180.0))
2664 : {
2665 1 : oMapping.Add("LongitudeDomain", 360);
2666 : }
2667 : else
2668 : {
2669 61 : oMapping.Add("LongitudeDomain", 180);
2670 : }
2671 :
2672 62 : if (m_bWriteBoundingDegrees && !m_osBoundingDegrees.empty())
2673 : {
2674 : char **papszTokens =
2675 1 : CSLTokenizeString2(m_osBoundingDegrees, ",", 0);
2676 1 : if (CSLCount(papszTokens) == 4)
2677 : {
2678 1 : oMapping.Add("MinimumLatitude", CPLAtof(papszTokens[1]));
2679 1 : oMapping.Add("MinimumLongitude", CPLAtof(papszTokens[0]));
2680 1 : oMapping.Add("MaximumLatitude", CPLAtof(papszTokens[3]));
2681 1 : oMapping.Add("MaximumLongitude", CPLAtof(papszTokens[2]));
2682 : }
2683 1 : CSLDestroy(papszTokens);
2684 : }
2685 61 : else if (m_bWriteBoundingDegrees && bLongLatCorners)
2686 : {
2687 52 : oMapping.Add("MinimumLatitude",
2688 : std::min(std::min(adfY[0], adfY[1]),
2689 52 : std::min(adfY[2], adfY[3])));
2690 52 : oMapping.Add("MinimumLongitude",
2691 : std::min(std::min(adfX[0], adfX[1]),
2692 52 : std::min(adfX[2], adfX[3])));
2693 52 : oMapping.Add("MaximumLatitude",
2694 : std::max(std::max(adfY[0], adfY[1]),
2695 52 : std::max(adfY[2], adfY[3])));
2696 52 : oMapping.Add("MaximumLongitude",
2697 : std::max(std::max(adfX[0], adfX[1]),
2698 52 : std::max(adfX[2], adfX[3])));
2699 : }
2700 :
2701 62 : const char *pszProjection = oSRS.GetAttrValue("PROJECTION");
2702 62 : if (pszProjection == nullptr)
2703 : {
2704 31 : oMapping.Add("ProjectionName", "SimpleCylindrical");
2705 31 : oMapping.Add("CenterLongitude", 0.0);
2706 31 : oMapping.Add("CenterLatitude", 0.0);
2707 31 : oMapping.Add("CenterLatitudeRadius", oSRS.GetSemiMajor());
2708 : }
2709 31 : else if (EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR))
2710 : {
2711 14 : oMapping.Add("ProjectionName", "Equirectangular");
2712 14 : if (oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) != 0.0)
2713 : {
2714 1 : CPLError(CE_Warning, CPLE_NotSupported,
2715 : "Ignoring %s. Only 0 value supported",
2716 : SRS_PP_LATITUDE_OF_ORIGIN);
2717 : }
2718 14 : oMapping.Add("CenterLongitude",
2719 : FixLong(oSRS.GetNormProjParm(
2720 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2721 : const double dfCenterLat =
2722 14 : oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0);
2723 14 : oMapping.Add("CenterLatitude", dfCenterLat);
2724 :
2725 : // in radians
2726 14 : const double radLat = dfCenterLat * M_PI / 180;
2727 14 : const double semi_major = oSRS.GetSemiMajor();
2728 14 : const double semi_minor = oSRS.GetSemiMinor();
2729 : const double localRadius =
2730 14 : semi_major * semi_minor /
2731 14 : sqrt(pow(semi_minor * cos(radLat), 2) +
2732 14 : pow(semi_major * sin(radLat), 2));
2733 14 : oMapping.Add("CenterLatitudeRadius", localRadius);
2734 : }
2735 :
2736 17 : else if (EQUAL(pszProjection, SRS_PT_ORTHOGRAPHIC))
2737 : {
2738 1 : oMapping.Add("ProjectionName", "Orthographic");
2739 1 : oMapping.Add("CenterLongitude",
2740 : FixLong(oSRS.GetNormProjParm(
2741 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2742 1 : oMapping.Add(
2743 : "CenterLatitude",
2744 : oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
2745 : }
2746 :
2747 16 : else if (EQUAL(pszProjection, SRS_PT_SINUSOIDAL))
2748 : {
2749 1 : oMapping.Add("ProjectionName", "Sinusoidal");
2750 1 : oMapping.Add("CenterLongitude",
2751 : FixLong(oSRS.GetNormProjParm(
2752 : SRS_PP_LONGITUDE_OF_CENTER, 0.0)));
2753 : }
2754 :
2755 15 : else if (EQUAL(pszProjection, SRS_PT_MERCATOR_1SP))
2756 : {
2757 1 : oMapping.Add("ProjectionName", "Mercator");
2758 1 : oMapping.Add("CenterLongitude",
2759 : FixLong(oSRS.GetNormProjParm(
2760 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2761 1 : oMapping.Add(
2762 : "CenterLatitude",
2763 : oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
2764 1 : oMapping.Add("scaleFactor",
2765 : oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
2766 : }
2767 :
2768 14 : else if (EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC))
2769 : {
2770 1 : oMapping.Add("ProjectionName", "PolarStereographic");
2771 1 : oMapping.Add("CenterLongitude",
2772 : FixLong(oSRS.GetNormProjParm(
2773 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2774 1 : oMapping.Add(
2775 : "CenterLatitude",
2776 : oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
2777 1 : oMapping.Add("scaleFactor",
2778 : oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
2779 : }
2780 :
2781 13 : else if (EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR))
2782 : {
2783 11 : oMapping.Add("ProjectionName", "TransverseMercator");
2784 11 : oMapping.Add("CenterLongitude",
2785 : FixLong(oSRS.GetNormProjParm(
2786 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2787 11 : oMapping.Add(
2788 : "CenterLatitude",
2789 : oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
2790 11 : oMapping.Add("scaleFactor",
2791 : oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
2792 : }
2793 :
2794 2 : else if (EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP))
2795 : {
2796 1 : oMapping.Add("ProjectionName", "LambertConformal");
2797 1 : oMapping.Add("CenterLongitude",
2798 : FixLong(oSRS.GetNormProjParm(
2799 : SRS_PP_CENTRAL_MERIDIAN, 0.0)));
2800 1 : oMapping.Add(
2801 : "CenterLatitude",
2802 : oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
2803 1 : oMapping.Add(
2804 : "FirstStandardParallel",
2805 : oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0));
2806 1 : oMapping.Add(
2807 : "SecondStandardParallel",
2808 : oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0));
2809 : }
2810 :
2811 1 : else if (EQUAL(pszProjection,
2812 : "Vertical Perspective")) // PROJ 7 required
2813 : {
2814 0 : oMapping.Add("ProjectionName", "PointPerspective");
2815 0 : oMapping.Add("CenterLongitude",
2816 : FixLong(oSRS.GetNormProjParm(
2817 : "Longitude of topocentric origin", 0.0)));
2818 0 : oMapping.Add("CenterLatitude",
2819 : oSRS.GetNormProjParm(
2820 : "Latitude of topocentric origin", 0.0));
2821 : // ISIS3 value is the distance from center of ellipsoid, in km
2822 0 : oMapping.Add("Distance",
2823 0 : (oSRS.GetNormProjParm("Viewpoint height", 0.0) +
2824 0 : oSRS.GetSemiMajor()) /
2825 : 1000.0);
2826 : }
2827 :
2828 1 : else if (EQUAL(pszProjection, "custom_proj4"))
2829 : {
2830 : const char *pszProj4 =
2831 1 : oSRS.GetExtension("PROJCS", "PROJ4", nullptr);
2832 1 : if (pszProj4 && strstr(pszProj4, "+proj=ob_tran") &&
2833 1 : strstr(pszProj4, "+o_proj=eqc"))
2834 : {
2835 : const auto FetchParam =
2836 3 : [](const char *pszProj4Str, const char *pszKey)
2837 : {
2838 6 : CPLString needle;
2839 3 : needle.Printf("+%s=", pszKey);
2840 : const char *pszVal =
2841 3 : strstr(pszProj4Str, needle.c_str());
2842 3 : if (pszVal)
2843 3 : return CPLAtof(pszVal + needle.size());
2844 0 : return 0.0;
2845 : };
2846 :
2847 1 : double dfLonP = FetchParam(pszProj4, "o_lon_p");
2848 1 : double dfLatP = FetchParam(pszProj4, "o_lat_p");
2849 1 : double dfLon0 = FetchParam(pszProj4, "lon_0");
2850 1 : double dfPoleRotation = -dfLonP;
2851 1 : double dfPoleLatitude = 180 - dfLatP;
2852 1 : double dfPoleLongitude = dfLon0;
2853 1 : oMapping.Add("ProjectionName", "ObliqueCylindrical");
2854 1 : oMapping.Add("PoleLatitude", dfPoleLatitude);
2855 1 : oMapping.Add("PoleLongitude", FixLong(dfPoleLongitude));
2856 1 : oMapping.Add("PoleRotation", dfPoleRotation);
2857 : }
2858 : else
2859 : {
2860 0 : CPLError(CE_Warning, CPLE_NotSupported,
2861 : "Projection %s not supported", pszProjection);
2862 : }
2863 : }
2864 : else
2865 : {
2866 0 : CPLError(CE_Warning, CPLE_NotSupported,
2867 : "Projection %s not supported", pszProjection);
2868 : }
2869 :
2870 62 : if (oMapping["ProjectionName"].IsValid())
2871 : {
2872 62 : if (oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0) != 0.0)
2873 : {
2874 9 : CPLError(CE_Warning, CPLE_NotSupported,
2875 : "Ignoring %s. Only 0 value supported",
2876 : SRS_PP_FALSE_EASTING);
2877 : }
2878 62 : if (oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0) != 0.0)
2879 : {
2880 1 : CPLError(CE_Warning, CPLE_AppDefined,
2881 : "Ignoring %s. Only 0 value supported",
2882 : SRS_PP_FALSE_NORTHING);
2883 : }
2884 : }
2885 : }
2886 : else
2887 : {
2888 0 : CPLError(CE_Warning, CPLE_NotSupported, "SRS not supported");
2889 : }
2890 : }
2891 :
2892 132 : if (!m_bUseSrcMapping && m_bGotTransform)
2893 : {
2894 54 : oMapping.Add("_type", "group");
2895 :
2896 54 : const double dfDegToMeter = oSRS.GetSemiMajor() * M_PI / 180.0;
2897 54 : if (!m_oSRS.IsEmpty() && oSRS.IsProjected())
2898 : {
2899 23 : const double dfLinearUnits = oSRS.GetLinearUnits();
2900 : // Maybe we should deal differently with non meter units ?
2901 23 : const double dfRes = m_gt.xscale * dfLinearUnits;
2902 23 : const double dfScale = dfDegToMeter / dfRes;
2903 23 : oMapping.Add("UpperLeftCornerX", m_gt.xorig);
2904 23 : oMapping.Add("UpperLeftCornerY", m_gt.yorig);
2905 23 : oMapping.Add("PixelResolution/value", dfRes);
2906 23 : oMapping.Add("PixelResolution/unit", "meters/pixel");
2907 23 : oMapping.Add("Scale/value", dfScale);
2908 23 : oMapping.Add("Scale/unit", "pixels/degree");
2909 : }
2910 31 : else if (!m_oSRS.IsEmpty() && oSRS.IsGeographic())
2911 : {
2912 31 : const double dfScale = 1.0 / m_gt.xscale;
2913 31 : const double dfRes = m_gt.xscale * dfDegToMeter;
2914 31 : oMapping.Add("UpperLeftCornerX", m_gt.xorig * dfDegToMeter);
2915 31 : oMapping.Add("UpperLeftCornerY", m_gt.yorig * dfDegToMeter);
2916 31 : oMapping.Add("PixelResolution/value", dfRes);
2917 31 : oMapping.Add("PixelResolution/unit", "meters/pixel");
2918 31 : oMapping.Add("Scale/value", dfScale);
2919 31 : oMapping.Add("Scale/unit", "pixels/degree");
2920 : }
2921 : else
2922 : {
2923 0 : oMapping.Add("UpperLeftCornerX", m_gt.xorig);
2924 0 : oMapping.Add("UpperLeftCornerY", m_gt.yorig);
2925 0 : oMapping.Add("PixelResolution", m_gt.xscale);
2926 : }
2927 : }
2928 :
2929 396 : CPLJSONObject oLabelLabel = GetOrCreateJSONObject(oLabel, "Label");
2930 132 : oLabelLabel.Set("_type", "object");
2931 132 : oLabelLabel.Set("Bytes", pszLABEL_BYTES_PLACEHOLDER);
2932 :
2933 : // Deal with History object
2934 132 : BuildHistory();
2935 :
2936 132 : oLabel.Delete("History_IsisCube");
2937 132 : if (!m_osHistory.empty())
2938 : {
2939 130 : CPLJSONObject oHistory;
2940 130 : oHistory.Add("_type", "object");
2941 130 : oHistory.Add("_container_name", "History");
2942 130 : oHistory.Add("Name", "IsisCube");
2943 130 : if (m_osExternalFilename.empty())
2944 100 : oHistory.Add("StartByte", pszHISTORY_STARTBYTE_PLACEHOLDER);
2945 : else
2946 30 : oHistory.Add("StartByte", 1);
2947 130 : oHistory.Add("Bytes", static_cast<GIntBig>(m_osHistory.size()));
2948 130 : if (!m_osExternalFilename.empty())
2949 : {
2950 30 : CPLString osFilename(CPLGetBasenameSafe(GetDescription()));
2951 30 : osFilename += ".History.IsisCube";
2952 30 : oHistory.Add("^History", osFilename);
2953 : }
2954 130 : oLabel.Add("History_IsisCube", oHistory);
2955 : }
2956 :
2957 : // Deal with other objects that have StartByte & Bytes
2958 132 : m_aoNonPixelSections.clear();
2959 132 : if (m_oSrcJSonLabel.IsValid())
2960 : {
2961 54 : CPLString osLabelSrcFilename;
2962 81 : CPLJSONObject oFilename = oLabel["_filename"];
2963 27 : if (oFilename.GetType() == CPLJSONObject::Type::String)
2964 : {
2965 22 : osLabelSrcFilename = oFilename.ToString();
2966 : }
2967 :
2968 148 : for (CPLJSONObject &oObj : oLabel.GetChildren())
2969 : {
2970 121 : CPLString osKey = oObj.GetName();
2971 121 : if (osKey == "History_IsisCube")
2972 : {
2973 25 : continue;
2974 : }
2975 :
2976 192 : CPLJSONObject oBytes = oObj.GetObj("Bytes");
2977 109 : if (oBytes.GetType() != CPLJSONObject::Type::Integer ||
2978 13 : oBytes.ToInteger() <= 0)
2979 : {
2980 83 : continue;
2981 : }
2982 :
2983 26 : CPLJSONObject oStartByte = oObj.GetObj("StartByte");
2984 26 : if (oStartByte.GetType() != CPLJSONObject::Type::Integer ||
2985 13 : oStartByte.ToInteger() <= 0)
2986 : {
2987 0 : continue;
2988 : }
2989 :
2990 13 : if (osLabelSrcFilename.empty())
2991 : {
2992 0 : CPLError(CE_Warning, CPLE_AppDefined,
2993 : "Cannot find _filename attribute in "
2994 : "source ISIS3 metadata. Removing object "
2995 : "%s from the label.",
2996 : osKey.c_str());
2997 0 : oLabel.Delete(osKey);
2998 0 : continue;
2999 : }
3000 :
3001 13 : NonPixelSection oSection;
3002 13 : oSection.osSrcFilename = osLabelSrcFilename;
3003 13 : oSection.nSrcOffset =
3004 13 : static_cast<vsi_l_offset>(oObj.GetInteger("StartByte")) - 1U;
3005 13 : oSection.nSize =
3006 13 : static_cast<vsi_l_offset>(oObj.GetInteger("Bytes"));
3007 :
3008 13 : CPLString osName;
3009 26 : CPLJSONObject oName = oObj.GetObj("Name");
3010 13 : if (oName.GetType() == CPLJSONObject::Type::String)
3011 : {
3012 13 : osName = oName.ToString();
3013 : }
3014 :
3015 13 : CPLString osContainerName(osKey);
3016 26 : CPLJSONObject oContainerName = oObj.GetObj("_container_name");
3017 13 : if (oContainerName.GetType() == CPLJSONObject::Type::String)
3018 : {
3019 13 : osContainerName = oContainerName.ToString();
3020 : }
3021 :
3022 13 : const CPLString osKeyFilename("^" + osContainerName);
3023 13 : CPLJSONObject oFilenameCap = oObj.GetObj(osKeyFilename);
3024 13 : if (oFilenameCap.GetType() == CPLJSONObject::Type::String)
3025 : {
3026 : VSIStatBufL sStat;
3027 30 : CPLString osSrcFilename(CPLFormFilenameSafe(
3028 20 : CPLGetPathSafe(osLabelSrcFilename).c_str(),
3029 30 : oFilenameCap.ToString().c_str(), nullptr));
3030 :
3031 10 : if (CPLHasPathTraversal(oFilenameCap.ToString().c_str()))
3032 : {
3033 0 : CPLError(CE_Warning, CPLE_AppDefined,
3034 : "Path traversal detected for %s: %s. Removing "
3035 : "this section from the label",
3036 0 : osKey.c_str(), oFilenameCap.ToString().c_str());
3037 0 : oLabel.Delete(osKey);
3038 0 : continue;
3039 : }
3040 10 : else if (VSIStatL(osSrcFilename, &sStat) == 0)
3041 : {
3042 4 : oSection.osSrcFilename = std::move(osSrcFilename);
3043 : }
3044 : else
3045 : {
3046 6 : CPLError(CE_Warning, CPLE_AppDefined,
3047 : "Object %s points to %s, which does "
3048 : "not exist. Removing this section "
3049 : "from the label",
3050 : osKey.c_str(), osSrcFilename.c_str());
3051 6 : oLabel.Delete(osKey);
3052 6 : continue;
3053 : }
3054 : }
3055 :
3056 7 : if (!m_osExternalFilename.empty())
3057 : {
3058 2 : oObj.Set("StartByte", 1);
3059 : }
3060 : else
3061 : {
3062 10 : CPLString osPlaceHolder;
3063 : osPlaceHolder.Printf(
3064 : "!*^PLACEHOLDER_%d_STARTBYTE^*!",
3065 5 : static_cast<int>(m_aoNonPixelSections.size()) + 1);
3066 5 : oObj.Set("StartByte", osPlaceHolder);
3067 5 : oSection.osPlaceHolder = std::move(osPlaceHolder);
3068 : }
3069 :
3070 7 : if (!m_osExternalFilename.empty())
3071 : {
3072 4 : CPLString osDstFilename(CPLGetBasenameSafe(GetDescription()));
3073 2 : osDstFilename += ".";
3074 2 : osDstFilename += osContainerName;
3075 2 : if (!osName.empty())
3076 : {
3077 2 : osDstFilename += ".";
3078 2 : osDstFilename += osName;
3079 : }
3080 :
3081 4 : oSection.osDstFilename = CPLFormFilenameSafe(
3082 4 : CPLGetPathSafe(GetDescription()).c_str(), osDstFilename,
3083 2 : nullptr);
3084 :
3085 2 : oObj.Set(osKeyFilename, osDstFilename);
3086 : }
3087 : else
3088 : {
3089 5 : oObj.Delete(osKeyFilename);
3090 : }
3091 :
3092 7 : m_aoNonPixelSections.push_back(std::move(oSection));
3093 : }
3094 : }
3095 132 : m_oJSonLabel = std::move(oLabel);
3096 132 : }
3097 :
3098 : /************************************************************************/
3099 : /* BuildHistory() */
3100 : /************************************************************************/
3101 :
3102 132 : void ISIS3Dataset::BuildHistory()
3103 : {
3104 264 : CPLString osHistory;
3105 :
3106 132 : if (m_oSrcJSonLabel.IsValid() && m_bUseSrcHistory)
3107 : {
3108 25 : vsi_l_offset nHistoryOffset = 0;
3109 25 : int nHistorySize = 0;
3110 50 : CPLString osSrcFilename;
3111 :
3112 75 : CPLJSONObject oFilename = m_oSrcJSonLabel["_filename"];
3113 25 : if (oFilename.GetType() == CPLJSONObject::Type::String)
3114 : {
3115 20 : osSrcFilename = oFilename.ToString();
3116 : }
3117 50 : CPLString osHistoryFilename(osSrcFilename);
3118 75 : CPLJSONObject oHistory = m_oSrcJSonLabel["History_IsisCube"];
3119 25 : if (oHistory.GetType() == CPLJSONObject::Type::Object)
3120 : {
3121 33 : CPLJSONObject oHistoryFilename = oHistory["^History"];
3122 11 : if (oHistoryFilename.GetType() == CPLJSONObject::Type::String)
3123 : {
3124 14 : osHistoryFilename = CPLFormFilenameSafe(
3125 14 : CPLGetPathSafe(osSrcFilename).c_str(),
3126 21 : oHistoryFilename.ToString().c_str(), nullptr);
3127 7 : if (CPLHasPathTraversal(oHistoryFilename.ToString().c_str()))
3128 : {
3129 0 : CPLError(CE_Warning, CPLE_AppDefined,
3130 : "Path traversal detected for History: %s. Not "
3131 : "including it in the label",
3132 0 : oHistoryFilename.ToString().c_str());
3133 0 : osHistoryFilename.clear();
3134 : }
3135 : }
3136 :
3137 33 : CPLJSONObject oStartByte = oHistory["StartByte"];
3138 11 : if (oStartByte.GetType() == CPLJSONObject::Type::Integer)
3139 : {
3140 11 : if (oStartByte.ToInteger() > 0)
3141 : {
3142 11 : nHistoryOffset =
3143 11 : static_cast<vsi_l_offset>(oStartByte.ToInteger()) - 1U;
3144 : }
3145 : }
3146 :
3147 33 : CPLJSONObject oBytes = oHistory["Bytes"];
3148 11 : if (oBytes.GetType() == CPLJSONObject::Type::Integer)
3149 : {
3150 11 : nHistorySize = static_cast<int>(oBytes.ToInteger());
3151 : }
3152 : }
3153 :
3154 25 : if (osHistoryFilename.empty())
3155 : {
3156 5 : CPLDebug("ISIS3", "Cannot find filename for source history");
3157 : }
3158 20 : else if (nHistorySize <= 0 || nHistorySize > 1000000)
3159 : {
3160 9 : CPLDebug("ISIS3", "Invalid or missing value for History.Bytes "
3161 : "for source history");
3162 : }
3163 : else
3164 : {
3165 11 : VSILFILE *fpHistory = VSIFOpenL(osHistoryFilename, "rb");
3166 11 : if (fpHistory != nullptr)
3167 : {
3168 6 : VSIFSeekL(fpHistory, nHistoryOffset, SEEK_SET);
3169 6 : osHistory.resize(nHistorySize);
3170 6 : if (VSIFReadL(&osHistory[0], nHistorySize, 1, fpHistory) != 1)
3171 : {
3172 0 : CPLError(CE_Warning, CPLE_FileIO,
3173 : "Cannot read %d bytes at offset " CPL_FRMT_GUIB
3174 : "of %s: history will not be preserved",
3175 : nHistorySize, nHistoryOffset,
3176 : osHistoryFilename.c_str());
3177 0 : osHistory.clear();
3178 : }
3179 6 : VSIFCloseL(fpHistory);
3180 : }
3181 : else
3182 : {
3183 5 : CPLError(CE_Warning, CPLE_FileIO,
3184 : "Cannot open %s: history will not be preserved",
3185 : osHistoryFilename.c_str());
3186 : }
3187 : }
3188 : }
3189 :
3190 132 : if (m_bAddGDALHistory && !m_osGDALHistory.empty())
3191 : {
3192 1 : if (!osHistory.empty())
3193 0 : osHistory += "\n";
3194 1 : osHistory += m_osGDALHistory;
3195 : }
3196 131 : else if (m_bAddGDALHistory)
3197 : {
3198 129 : if (!osHistory.empty())
3199 6 : osHistory += "\n";
3200 :
3201 258 : CPLJSONObject oHistoryObj;
3202 129 : char szFullFilename[2048] = {0};
3203 129 : if (!CPLGetExecPath(szFullFilename, sizeof(szFullFilename) - 1))
3204 0 : strcpy(szFullFilename, "unknown_program");
3205 258 : const CPLString osProgram(CPLGetBasenameSafe(szFullFilename));
3206 258 : const CPLString osPath(CPLGetPathSafe(szFullFilename));
3207 :
3208 258 : CPLJSONObject oObj;
3209 129 : oHistoryObj.Add(osProgram, oObj);
3210 :
3211 129 : oObj.Add("_type", "object");
3212 129 : oObj.Add("GdalVersion", GDALVersionInfo("RELEASE_NAME"));
3213 129 : if (osPath != ".")
3214 129 : oObj.Add("ProgramPath", osPath);
3215 129 : time_t nCurTime = time(nullptr);
3216 129 : if (nCurTime != -1)
3217 : {
3218 : struct tm mytm;
3219 129 : CPLUnixTimeToYMDHMS(nCurTime, &mytm);
3220 129 : oObj.Add("ExecutionDateTime",
3221 : CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
3222 129 : mytm.tm_year + 1900, mytm.tm_mon + 1,
3223 : mytm.tm_mday, mytm.tm_hour, mytm.tm_min,
3224 : mytm.tm_sec));
3225 : }
3226 129 : char szHostname[256] = {0};
3227 129 : if (gethostname(szHostname, sizeof(szHostname) - 1) == 0)
3228 : {
3229 129 : oObj.Add("HostName", std::string(szHostname));
3230 : }
3231 129 : const char *pszUsername = CPLGetConfigOption("USERNAME", nullptr);
3232 129 : if (pszUsername == nullptr)
3233 129 : pszUsername = CPLGetConfigOption("USER", nullptr);
3234 129 : if (pszUsername != nullptr)
3235 : {
3236 0 : oObj.Add("UserName", pszUsername);
3237 : }
3238 129 : oObj.Add("Description", "GDAL conversion");
3239 :
3240 129 : CPLJSONObject oUserParameters;
3241 129 : oObj.Add("UserParameters", oUserParameters);
3242 :
3243 129 : oUserParameters.Add("_type", "group");
3244 129 : if (!m_osFromFilename.empty())
3245 : {
3246 38 : const CPLString osFromFilename = CPLGetFilename(m_osFromFilename);
3247 38 : oUserParameters.Add("FROM", osFromFilename);
3248 : }
3249 129 : if (nullptr != GetDescription())
3250 : {
3251 129 : const CPLString osToFileName = CPLGetFilename(GetDescription());
3252 129 : oUserParameters.Add("TO", osToFileName);
3253 : }
3254 129 : if (m_bForce360)
3255 1 : oUserParameters.Add("Force_360", "true");
3256 :
3257 129 : osHistory += SerializeAsPDL(oHistoryObj);
3258 : }
3259 :
3260 132 : m_osHistory = std::move(osHistory);
3261 132 : }
3262 :
3263 : /************************************************************************/
3264 : /* WriteLabel() */
3265 : /************************************************************************/
3266 :
3267 131 : void ISIS3Dataset::WriteLabel()
3268 : {
3269 131 : m_bIsLabelWritten = true;
3270 :
3271 131 : if (!m_oJSonLabel.IsValid())
3272 131 : BuildLabel();
3273 :
3274 : // Serialize label
3275 262 : CPLString osLabel(SerializeAsPDL(m_oJSonLabel));
3276 131 : osLabel += "End\n";
3277 131 : if (m_osExternalFilename.empty() && osLabel.size() < 65536)
3278 : {
3279 : // In-line labels have conventionally a minimize size of 65536 bytes
3280 : // See #2741
3281 100 : osLabel.resize(65536);
3282 : }
3283 131 : char *pszLabel = &osLabel[0];
3284 131 : const int nLabelSize = static_cast<int>(osLabel.size());
3285 :
3286 : // Hack back StartByte value
3287 : {
3288 131 : char *pszStartByte = strstr(pszLabel, pszSTARTBYTE_PLACEHOLDER);
3289 131 : if (pszStartByte != nullptr)
3290 : {
3291 100 : const char *pszOffset = CPLSPrintf("%d", 1 + nLabelSize);
3292 100 : memcpy(pszStartByte, pszOffset, strlen(pszOffset));
3293 100 : memset(pszStartByte + strlen(pszOffset), ' ',
3294 100 : strlen(pszSTARTBYTE_PLACEHOLDER) - strlen(pszOffset));
3295 : }
3296 : }
3297 :
3298 : // Hack back Label.Bytes value
3299 : {
3300 131 : char *pszLabelBytes = strstr(pszLabel, pszLABEL_BYTES_PLACEHOLDER);
3301 131 : if (pszLabelBytes != nullptr)
3302 : {
3303 131 : const char *pszBytes = CPLSPrintf("%d", nLabelSize);
3304 131 : memcpy(pszLabelBytes, pszBytes, strlen(pszBytes));
3305 131 : memset(pszLabelBytes + strlen(pszBytes), ' ',
3306 131 : strlen(pszLABEL_BYTES_PLACEHOLDER) - strlen(pszBytes));
3307 : }
3308 : }
3309 :
3310 131 : const GDALDataType eType = GetRasterBand(1)->GetRasterDataType();
3311 131 : const int nDTSize = GDALGetDataTypeSizeBytes(eType);
3312 131 : vsi_l_offset nImagePixels = 0;
3313 131 : if (m_poExternalDS == nullptr)
3314 : {
3315 113 : if (m_bIsTiled)
3316 : {
3317 7 : int nBlockXSize = 1, nBlockYSize = 1;
3318 7 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
3319 7 : nImagePixels = static_cast<vsi_l_offset>(nBlockXSize) *
3320 14 : nBlockYSize * nBands *
3321 7 : DIV_ROUND_UP(nRasterXSize, nBlockXSize) *
3322 7 : DIV_ROUND_UP(nRasterYSize, nBlockYSize);
3323 : }
3324 : else
3325 : {
3326 106 : nImagePixels =
3327 106 : static_cast<vsi_l_offset>(nRasterXSize) * nRasterYSize * nBands;
3328 : }
3329 : }
3330 :
3331 : // Hack back History.StartBytes value
3332 : char *pszHistoryStartByte =
3333 131 : strstr(pszLabel, pszHISTORY_STARTBYTE_PLACEHOLDER);
3334 :
3335 131 : vsi_l_offset nHistoryOffset = 0;
3336 131 : vsi_l_offset nLastOffset = 0;
3337 131 : if (pszHistoryStartByte != nullptr)
3338 : {
3339 99 : CPLAssert(m_osExternalFilename.empty());
3340 99 : nHistoryOffset = nLabelSize + nImagePixels * nDTSize;
3341 99 : nLastOffset = nHistoryOffset + m_osHistory.size();
3342 : const char *pszStartByte =
3343 99 : CPLSPrintf(CPL_FRMT_GUIB, nHistoryOffset + 1);
3344 99 : CPLAssert(strlen(pszStartByte) <
3345 : strlen(pszHISTORY_STARTBYTE_PLACEHOLDER));
3346 99 : memcpy(pszHistoryStartByte, pszStartByte, strlen(pszStartByte));
3347 99 : memset(pszHistoryStartByte + strlen(pszStartByte), ' ',
3348 99 : strlen(pszHISTORY_STARTBYTE_PLACEHOLDER) - strlen(pszStartByte));
3349 : }
3350 :
3351 : // Replace placeholders in other sections
3352 138 : for (size_t i = 0; i < m_aoNonPixelSections.size(); ++i)
3353 : {
3354 7 : if (!m_aoNonPixelSections[i].osPlaceHolder.empty())
3355 : {
3356 : char *pszPlaceHolder =
3357 5 : strstr(pszLabel, m_aoNonPixelSections[i].osPlaceHolder.c_str());
3358 5 : CPLAssert(pszPlaceHolder != nullptr);
3359 : const char *pszStartByte =
3360 5 : CPLSPrintf(CPL_FRMT_GUIB, nLastOffset + 1);
3361 5 : nLastOffset += m_aoNonPixelSections[i].nSize;
3362 5 : CPLAssert(strlen(pszStartByte) <
3363 : m_aoNonPixelSections[i].osPlaceHolder.size());
3364 :
3365 5 : memcpy(pszPlaceHolder, pszStartByte, strlen(pszStartByte));
3366 5 : memset(pszPlaceHolder + strlen(pszStartByte), ' ',
3367 5 : m_aoNonPixelSections[i].osPlaceHolder.size() -
3368 5 : strlen(pszStartByte));
3369 : }
3370 : }
3371 :
3372 : // Write to final file
3373 131 : VSIFSeekL(m_fpLabel, 0, SEEK_SET);
3374 131 : VSIFWriteL(pszLabel, 1, osLabel.size(), m_fpLabel);
3375 :
3376 131 : if (m_osExternalFilename.empty())
3377 : {
3378 : // Update image offset in bands
3379 100 : if (m_bIsTiled)
3380 : {
3381 15 : for (int i = 0; i < nBands; i++)
3382 : {
3383 : ISISTiledBand *poBand =
3384 9 : reinterpret_cast<ISISTiledBand *>(GetRasterBand(i + 1));
3385 9 : poBand->m_nFirstTileOffset += nLabelSize;
3386 : }
3387 : }
3388 : else
3389 : {
3390 218 : for (int i = 0; i < nBands; i++)
3391 : {
3392 : ISIS3RawRasterBand *poBand =
3393 : reinterpret_cast<ISIS3RawRasterBand *>(
3394 124 : GetRasterBand(i + 1));
3395 124 : poBand->nImgOffset += nLabelSize;
3396 : }
3397 : }
3398 : }
3399 :
3400 131 : if (m_bInitToNodata)
3401 : {
3402 : // Initialize the image to nodata
3403 55 : const double dfNoData = GetRasterBand(1)->GetNoDataValue();
3404 55 : if (dfNoData == 0.0)
3405 : {
3406 43 : VSIFTruncateL(m_fpImage,
3407 43 : VSIFTellL(m_fpImage) + nImagePixels * nDTSize);
3408 : }
3409 12 : else if (nDTSize != 0) // to make Coverity not warn about div by 0
3410 : {
3411 12 : const int nPageSize = 4096; // Must be multiple of 4 since
3412 : // Float32 is the largest type
3413 12 : CPLAssert((nPageSize % nDTSize) == 0);
3414 12 : const int nMaxPerPage = nPageSize / nDTSize;
3415 12 : GByte *pabyTemp = static_cast<GByte *>(CPLMalloc(nPageSize));
3416 12 : GDALCopyWords(&dfNoData, GDT_Float64, 0, pabyTemp, eType, nDTSize,
3417 : nMaxPerPage);
3418 : #ifdef CPL_MSB
3419 : GDALSwapWords(pabyTemp, nDTSize, nMaxPerPage, nDTSize);
3420 : #endif
3421 80 : for (vsi_l_offset i = 0; i < nImagePixels; i += nMaxPerPage)
3422 : {
3423 : int n;
3424 68 : if (i + nMaxPerPage <= nImagePixels)
3425 56 : n = nMaxPerPage;
3426 : else
3427 12 : n = static_cast<int>(nImagePixels - i);
3428 68 : if (VSIFWriteL(pabyTemp, static_cast<size_t>(n) * nDTSize, 1,
3429 68 : m_fpImage) != 1)
3430 : {
3431 0 : CPLError(CE_Failure, CPLE_FileIO,
3432 : "Cannot initialize imagery to null");
3433 0 : break;
3434 : }
3435 : }
3436 :
3437 12 : CPLFree(pabyTemp);
3438 : }
3439 : }
3440 :
3441 : // Write history
3442 131 : if (!m_osHistory.empty())
3443 : {
3444 129 : if (m_osExternalFilename.empty())
3445 : {
3446 99 : VSIFSeekL(m_fpLabel, nHistoryOffset, SEEK_SET);
3447 99 : VSIFWriteL(m_osHistory.c_str(), 1, m_osHistory.size(), m_fpLabel);
3448 : }
3449 : else
3450 : {
3451 60 : CPLString osFilename(CPLGetBasenameSafe(GetDescription()));
3452 30 : osFilename += ".History.IsisCube";
3453 60 : osFilename = CPLFormFilenameSafe(
3454 60 : CPLGetPathSafe(GetDescription()).c_str(), osFilename, nullptr);
3455 30 : VSILFILE *fp = VSIFOpenL(osFilename, "wb");
3456 30 : if (fp)
3457 : {
3458 30 : m_aosAdditionalFiles.AddString(osFilename);
3459 :
3460 30 : VSIFWriteL(m_osHistory.c_str(), 1, m_osHistory.size(), fp);
3461 30 : VSIFCloseL(fp);
3462 : }
3463 : else
3464 : {
3465 0 : CPLError(CE_Warning, CPLE_FileIO, "Cannot write %s",
3466 : osFilename.c_str());
3467 : }
3468 : }
3469 : }
3470 :
3471 : // Write other non pixel sections
3472 138 : for (size_t i = 0; i < m_aoNonPixelSections.size(); ++i)
3473 : {
3474 : VSILFILE *fpSrc =
3475 7 : VSIFOpenL(m_aoNonPixelSections[i].osSrcFilename, "rb");
3476 7 : if (fpSrc == nullptr)
3477 : {
3478 0 : CPLError(CE_Warning, CPLE_FileIO, "Cannot open %s",
3479 0 : m_aoNonPixelSections[i].osSrcFilename.c_str());
3480 0 : continue;
3481 : }
3482 :
3483 7 : VSILFILE *fpDest = m_fpLabel;
3484 7 : if (!m_aoNonPixelSections[i].osDstFilename.empty())
3485 : {
3486 2 : fpDest = VSIFOpenL(m_aoNonPixelSections[i].osDstFilename, "wb");
3487 2 : if (fpDest == nullptr)
3488 : {
3489 0 : CPLError(CE_Warning, CPLE_FileIO, "Cannot create %s",
3490 0 : m_aoNonPixelSections[i].osDstFilename.c_str());
3491 0 : VSIFCloseL(fpSrc);
3492 0 : continue;
3493 : }
3494 :
3495 : m_aosAdditionalFiles.AddString(
3496 2 : m_aoNonPixelSections[i].osDstFilename);
3497 : }
3498 :
3499 7 : VSIFSeekL(fpSrc, m_aoNonPixelSections[i].nSrcOffset, SEEK_SET);
3500 : GByte abyBuffer[4096];
3501 7 : vsi_l_offset nRemaining = m_aoNonPixelSections[i].nSize;
3502 14 : while (nRemaining)
3503 : {
3504 7 : size_t nToRead = 4096;
3505 7 : if (nRemaining < nToRead)
3506 7 : nToRead = static_cast<size_t>(nRemaining);
3507 7 : size_t nRead = VSIFReadL(abyBuffer, 1, nToRead, fpSrc);
3508 7 : if (nRead != nToRead)
3509 : {
3510 0 : CPLError(CE_Warning, CPLE_FileIO,
3511 : "Could not read " CPL_FRMT_GUIB " bytes from %s",
3512 0 : m_aoNonPixelSections[i].nSize,
3513 0 : m_aoNonPixelSections[i].osSrcFilename.c_str());
3514 0 : break;
3515 : }
3516 7 : VSIFWriteL(abyBuffer, 1, nRead, fpDest);
3517 7 : nRemaining -= nRead;
3518 : }
3519 :
3520 7 : VSIFCloseL(fpSrc);
3521 7 : if (fpDest != m_fpLabel)
3522 2 : VSIFCloseL(fpDest);
3523 : }
3524 131 : }
3525 :
3526 : /************************************************************************/
3527 : /* SerializeAsPDL() */
3528 : /************************************************************************/
3529 :
3530 260 : CPLString ISIS3Dataset::SerializeAsPDL(const CPLJSONObject &oObj)
3531 : {
3532 520 : const CPLString osTmpFile(VSIMemGenerateHiddenFilename("isis3_pdl"));
3533 260 : VSILFILE *fpTmp = VSIFOpenL(osTmpFile, "wb+");
3534 260 : SerializeAsPDL(fpTmp, oObj);
3535 260 : VSIFCloseL(fpTmp);
3536 : CPLString osContent(reinterpret_cast<char *>(
3537 260 : VSIGetMemFileBuffer(osTmpFile, nullptr, FALSE)));
3538 260 : VSIUnlink(osTmpFile);
3539 520 : return osContent;
3540 : }
3541 :
3542 : /************************************************************************/
3543 : /* SerializeAsPDL() */
3544 : /************************************************************************/
3545 :
3546 : constexpr size_t WIDTH = 79;
3547 :
3548 1398 : void ISIS3Dataset::SerializeAsPDL(VSILFILE *fp, const CPLJSONObject &oObj,
3549 : int nDepth)
3550 : {
3551 2796 : CPLString osIndentation;
3552 3402 : for (int i = 0; i < nDepth; i++)
3553 2004 : osIndentation += " ";
3554 :
3555 2796 : std::vector<CPLJSONObject> aoChildren = oObj.GetChildren();
3556 1398 : size_t nMaxKeyLength = 0;
3557 2796 : std::vector<std::pair<CPLString, CPLJSONObject>> aoChildren2;
3558 7697 : for (const CPLJSONObject &oChild : aoChildren)
3559 : {
3560 6299 : const CPLString osKey = oChild.GetName();
3561 11460 : if (EQUAL(osKey, "_type") || EQUAL(osKey, "_container_name") ||
3562 11460 : EQUAL(osKey, "_filename") || EQUAL(osKey, "_data"))
3563 : {
3564 1307 : continue;
3565 : }
3566 :
3567 4992 : const auto eType = oChild.GetType();
3568 4992 : if (eType == CPLJSONObject::Type::String ||
3569 2256 : eType == CPLJSONObject::Type::Integer ||
3570 1462 : eType == CPLJSONObject::Type::Double ||
3571 : eType == CPLJSONObject::Type::Array)
3572 : {
3573 3540 : aoChildren2.emplace_back(osKey, oChild);
3574 3540 : if (osKey.size() > nMaxKeyLength)
3575 : {
3576 1680 : nMaxKeyLength = osKey.size();
3577 : }
3578 : }
3579 1452 : else if (eType == CPLJSONObject::Type::Object)
3580 : {
3581 4356 : CPLJSONObject oValue = oChild.GetObj("value");
3582 4356 : CPLJSONObject oUnit = oChild.GetObj("unit");
3583 1695 : if (oValue.IsValid() &&
3584 243 : oUnit.GetType() == CPLJSONObject::Type::String)
3585 : {
3586 243 : aoChildren2.emplace_back(osKey, oChild);
3587 243 : if (osKey.size() > nMaxKeyLength)
3588 : {
3589 64 : nMaxKeyLength = osKey.size();
3590 : }
3591 : }
3592 1209 : else if (oChild.GetObj("values").GetType() ==
3593 : CPLJSONObject::Type::Array)
3594 : {
3595 4 : if (osKey.size() > nMaxKeyLength)
3596 : {
3597 1 : nMaxKeyLength = osKey.size();
3598 : }
3599 13 : for (const auto &oSubChild : oChild.GetObj("values").ToArray())
3600 : {
3601 9 : aoChildren2.emplace_back(osKey, oSubChild);
3602 : }
3603 : }
3604 : else
3605 : {
3606 1205 : aoChildren2.emplace_back(osKey, oChild);
3607 : }
3608 : }
3609 : else
3610 : {
3611 0 : aoChildren2.emplace_back(osKey, oChild);
3612 : }
3613 : }
3614 :
3615 6395 : for (const auto &[osKey, oChild] : aoChildren2)
3616 : {
3617 4997 : if (STARTS_WITH(osKey, "_comment"))
3618 : {
3619 1 : if (oChild.GetType() == CPLJSONObject::Type::String)
3620 : {
3621 1 : VSIFPrintfL(fp, "#%s\n", oChild.ToString().c_str());
3622 : }
3623 1 : continue;
3624 : }
3625 9992 : CPLString osPadding;
3626 4996 : size_t nLen = osKey.size();
3627 4996 : if (nLen < nMaxKeyLength)
3628 : {
3629 3047 : osPadding.append(nMaxKeyLength - nLen, ' ');
3630 : }
3631 :
3632 4996 : const auto eType = oChild.GetType();
3633 4996 : if (eType == CPLJSONObject::Type::Object)
3634 : {
3635 4350 : CPLJSONObject oType = oChild.GetObj("_type");
3636 4350 : CPLJSONObject oContainerName = oChild.GetObj("_container_name");
3637 2900 : CPLString osContainerName = osKey;
3638 1450 : if (oContainerName.GetType() == CPLJSONObject::Type::String)
3639 : {
3640 140 : osContainerName = oContainerName.ToString();
3641 : }
3642 1450 : if (oType.GetType() == CPLJSONObject::Type::String)
3643 : {
3644 3414 : const CPLString osType = oType.ToString();
3645 1138 : if (EQUAL(osType, "Object"))
3646 : {
3647 665 : if (nDepth == 0 && VSIFTellL(fp) != 0)
3648 274 : VSIFPrintfL(fp, "\n");
3649 665 : VSIFPrintfL(fp, "%sObject = %s\n", osIndentation.c_str(),
3650 : osContainerName.c_str());
3651 665 : SerializeAsPDL(fp, oChild, nDepth + 1);
3652 665 : VSIFPrintfL(fp, "%sEnd_Object\n", osIndentation.c_str());
3653 : }
3654 473 : else if (EQUAL(osType, "Group"))
3655 : {
3656 473 : VSIFPrintfL(fp, "\n");
3657 473 : VSIFPrintfL(fp, "%sGroup = %s\n", osIndentation.c_str(),
3658 : osContainerName.c_str());
3659 473 : SerializeAsPDL(fp, oChild, nDepth + 1);
3660 473 : VSIFPrintfL(fp, "%sEnd_Group\n", osIndentation.c_str());
3661 : }
3662 : }
3663 : else
3664 : {
3665 936 : CPLJSONObject oValue = oChild.GetObj("value");
3666 936 : CPLJSONObject oUnit = oChild.GetObj("unit");
3667 557 : if (oValue.IsValid() &&
3668 245 : oUnit.GetType() == CPLJSONObject::Type::String)
3669 : {
3670 735 : const CPLString osUnit = oUnit.ToString();
3671 245 : const auto eValueType = oValue.GetType();
3672 245 : if (eValueType == CPLJSONObject::Type::Integer)
3673 : {
3674 3 : VSIFPrintfL(fp, "%s%s%s = %d <%s>\n",
3675 : osIndentation.c_str(), osKey.c_str(),
3676 : osPadding.c_str(), oValue.ToInteger(),
3677 : osUnit.c_str());
3678 : }
3679 242 : else if (eValueType == CPLJSONObject::Type::Double)
3680 : {
3681 241 : const double dfVal = oValue.ToDouble();
3682 241 : if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
3683 241 : static_cast<int>(dfVal) == dfVal)
3684 : {
3685 90 : VSIFPrintfL(fp, "%s%s%s = %d.0 <%s>\n",
3686 : osIndentation.c_str(), osKey.c_str(),
3687 : osPadding.c_str(),
3688 : static_cast<int>(dfVal),
3689 : osUnit.c_str());
3690 : }
3691 : else
3692 : {
3693 151 : VSIFPrintfL(fp, "%s%s%s = %.17g <%s>\n",
3694 : osIndentation.c_str(), osKey.c_str(),
3695 : osPadding.c_str(), dfVal,
3696 : osUnit.c_str());
3697 : }
3698 : }
3699 : }
3700 : }
3701 : }
3702 3546 : else if (eType == CPLJSONObject::Type::String)
3703 : {
3704 6141 : CPLString osVal = oChild.ToString();
3705 2047 : const char *pszVal = osVal.c_str();
3706 2047 : if (pszVal[0] == '\0' || strchr(pszVal, ' ') ||
3707 1909 : strstr(pszVal, "\\n") || strstr(pszVal, "\\r"))
3708 : {
3709 138 : osVal.replaceAll("\\n", "\n");
3710 138 : osVal.replaceAll("\\r", "\r");
3711 138 : VSIFPrintfL(fp, "%s%s%s = \"%s\"\n", osIndentation.c_str(),
3712 : osKey.c_str(), osPadding.c_str(), osVal.c_str());
3713 : }
3714 : else
3715 : {
3716 1909 : if (osIndentation.size() + osKey.size() + osPadding.size() +
3717 1909 : strlen(" = ") + strlen(pszVal) >
3718 1910 : WIDTH &&
3719 1 : osIndentation.size() + osKey.size() + osPadding.size() +
3720 : strlen(" = ") <
3721 : WIDTH)
3722 : {
3723 1 : size_t nFirstPos = osIndentation.size() + osKey.size() +
3724 1 : osPadding.size() + strlen(" = ");
3725 1 : VSIFPrintfL(fp, "%s%s%s = ", osIndentation.c_str(),
3726 : osKey.c_str(), osPadding.c_str());
3727 1 : size_t nCurPos = nFirstPos;
3728 96 : for (int j = 0; pszVal[j] != '\0'; j++)
3729 : {
3730 95 : nCurPos++;
3731 95 : if (nCurPos == WIDTH && pszVal[j + 1] != '\0')
3732 : {
3733 1 : VSIFPrintfL(fp, "-\n");
3734 15 : for (size_t k = 0; k < nFirstPos; k++)
3735 : {
3736 14 : const char chSpace = ' ';
3737 14 : VSIFWriteL(&chSpace, 1, 1, fp);
3738 : }
3739 1 : nCurPos = nFirstPos + 1;
3740 : }
3741 95 : VSIFWriteL(&pszVal[j], 1, 1, fp);
3742 : }
3743 1 : VSIFPrintfL(fp, "\n");
3744 : }
3745 : else
3746 : {
3747 1908 : VSIFPrintfL(fp, "%s%s%s = %s\n", osIndentation.c_str(),
3748 : osKey.c_str(), osPadding.c_str(), pszVal);
3749 : }
3750 : }
3751 : }
3752 1499 : else if (eType == CPLJSONObject::Type::Integer)
3753 : {
3754 693 : const int nVal = oChild.ToInteger();
3755 693 : VSIFPrintfL(fp, "%s%s%s = %d\n", osIndentation.c_str(),
3756 : osKey.c_str(), osPadding.c_str(), nVal);
3757 : }
3758 806 : else if (eType == CPLJSONObject::Type::Double)
3759 : {
3760 794 : const double dfVal = oChild.ToDouble();
3761 794 : if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
3762 794 : static_cast<int>(dfVal) == dfVal)
3763 : {
3764 550 : VSIFPrintfL(fp, "%s%s%s = %d.0\n", osIndentation.c_str(),
3765 : osKey.c_str(), osPadding.c_str(),
3766 : static_cast<int>(dfVal));
3767 : }
3768 : else
3769 : {
3770 244 : VSIFPrintfL(fp, "%s%s%s = %.17g\n", osIndentation.c_str(),
3771 : osKey.c_str(), osPadding.c_str(), dfVal);
3772 : }
3773 : }
3774 12 : else if (eType == CPLJSONObject::Type::Array)
3775 : {
3776 24 : CPLJSONArray oArrayItem(oChild);
3777 12 : const int nLength = oArrayItem.Size();
3778 12 : size_t nFirstPos = osIndentation.size() + osKey.size() +
3779 12 : osPadding.size() + strlen(" = (");
3780 12 : VSIFPrintfL(fp, "%s%s%s = (", osIndentation.c_str(), osKey.c_str(),
3781 : osPadding.c_str());
3782 12 : size_t nCurPos = nFirstPos;
3783 :
3784 57 : for (int idx = 0; idx < nLength; idx++)
3785 : {
3786 90 : CPLJSONObject oItem = oArrayItem[idx];
3787 45 : const auto eArrayItemType = oItem.GetType();
3788 :
3789 : const auto outputArrayVal =
3790 244 : [fp, idx, nFirstPos, &nCurPos](const std::string &osVal)
3791 : {
3792 31 : const size_t nValLen = osVal.size();
3793 31 : if (nFirstPos < WIDTH && idx > 0 &&
3794 23 : nCurPos + nValLen > WIDTH)
3795 : {
3796 2 : VSIFPrintfL(fp, "\n");
3797 32 : for (size_t j = 0; j < nFirstPos; j++)
3798 : {
3799 30 : constexpr char chSpace = ' ';
3800 30 : VSIFWriteL(&chSpace, 1, 1, fp);
3801 : }
3802 2 : nCurPos = nFirstPos;
3803 : }
3804 31 : VSIFPrintfL(fp, "%s", osVal.c_str());
3805 31 : nCurPos += nValLen;
3806 31 : };
3807 :
3808 45 : if (eArrayItemType == CPLJSONObject::Type::Object)
3809 : {
3810 9 : const auto oValue = oItem["value"];
3811 9 : const auto oUnit = oItem["unit"];
3812 6 : if (oValue.IsValid() && oUnit.IsValid() &&
3813 3 : (oValue.GetType() == CPLJSONObject::Type::Integer ||
3814 1 : oValue.GetType() == CPLJSONObject::Type::Double))
3815 : {
3816 3 : if (oValue.GetType() == CPLJSONObject::Type::Integer)
3817 : {
3818 2 : const int nVal = oValue.ToInteger();
3819 6 : outputArrayVal(CPLSPrintf(
3820 4 : "%d <%s>", nVal, oUnit.ToString().c_str()));
3821 : }
3822 : else
3823 : {
3824 1 : const double dfVal = oValue.ToDouble();
3825 1 : if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
3826 1 : static_cast<int>(dfVal) == dfVal)
3827 : {
3828 0 : outputArrayVal(CPLSPrintf(
3829 : "%d.0 <%s>", static_cast<int>(dfVal),
3830 0 : oUnit.ToString().c_str()));
3831 : }
3832 : else
3833 : {
3834 3 : outputArrayVal(
3835 : CPLSPrintf("%.17g <%s>", dfVal,
3836 2 : oUnit.ToString().c_str()));
3837 : }
3838 : }
3839 : }
3840 : else
3841 : {
3842 0 : CPLError(CE_Warning, CPLE_AppDefined,
3843 : "Invalid JSON object");
3844 : }
3845 : }
3846 42 : else if (eArrayItemType == CPLJSONObject::Type::String)
3847 : {
3848 42 : CPLString osVal = oItem.ToString();
3849 14 : const char *pszVal = osVal.c_str();
3850 14 : if (pszVal[0] == '\0' || strchr(pszVal, ' ') ||
3851 7 : strstr(pszVal, "\\n") || strstr(pszVal, "\\r"))
3852 : {
3853 7 : osVal.replaceAll("\\n", "\n");
3854 7 : osVal.replaceAll("\\r", "\r");
3855 7 : VSIFPrintfL(fp, "\"%s\"", osVal.c_str());
3856 : }
3857 7 : else if (nFirstPos < WIDTH &&
3858 7 : nCurPos + strlen(pszVal) > WIDTH)
3859 : {
3860 1 : if (idx > 0)
3861 : {
3862 1 : VSIFPrintfL(fp, "\n");
3863 16 : for (size_t j = 0; j < nFirstPos; j++)
3864 : {
3865 15 : const char chSpace = ' ';
3866 15 : VSIFWriteL(&chSpace, 1, 1, fp);
3867 : }
3868 1 : nCurPos = nFirstPos;
3869 : }
3870 :
3871 102 : for (int j = 0; pszVal[j] != '\0'; j++)
3872 : {
3873 101 : nCurPos++;
3874 101 : if (nCurPos == WIDTH && pszVal[j + 1] != '\0')
3875 : {
3876 1 : VSIFPrintfL(fp, "-\n");
3877 16 : for (size_t k = 0; k < nFirstPos; k++)
3878 : {
3879 15 : const char chSpace = ' ';
3880 15 : VSIFWriteL(&chSpace, 1, 1, fp);
3881 : }
3882 1 : nCurPos = nFirstPos + 1;
3883 : }
3884 101 : VSIFWriteL(&pszVal[j], 1, 1, fp);
3885 1 : }
3886 : }
3887 : else
3888 : {
3889 6 : VSIFPrintfL(fp, "%s", pszVal);
3890 6 : nCurPos += strlen(pszVal);
3891 : }
3892 : }
3893 28 : else if (eArrayItemType == CPLJSONObject::Type::Integer)
3894 : {
3895 19 : const int nVal = oItem.ToInteger();
3896 19 : outputArrayVal(CPLSPrintf("%d", nVal));
3897 : }
3898 9 : else if (eArrayItemType == CPLJSONObject::Type::Double)
3899 : {
3900 9 : const double dfVal = oItem.ToDouble();
3901 18 : CPLString osVal;
3902 9 : if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
3903 9 : static_cast<int>(dfVal) == dfVal)
3904 : {
3905 8 : osVal = CPLSPrintf("%d.0", static_cast<int>(dfVal));
3906 : }
3907 : else
3908 : {
3909 1 : osVal = CPLSPrintf("%.17g", dfVal);
3910 : }
3911 9 : outputArrayVal(osVal);
3912 : }
3913 45 : if (idx < nLength - 1)
3914 : {
3915 33 : VSIFPrintfL(fp, ", ");
3916 33 : nCurPos += 2;
3917 : }
3918 : }
3919 12 : VSIFPrintfL(fp, ")\n");
3920 : }
3921 : }
3922 1398 : }
3923 :
3924 : /************************************************************************/
3925 : /* Create() */
3926 : /************************************************************************/
3927 :
3928 165 : GDALDataset *ISIS3Dataset::Create(const char *pszFilename, int nXSize,
3929 : int nYSize, int nBandsIn, GDALDataType eType,
3930 : CSLConstList papszOptions)
3931 : {
3932 165 : if (eType != GDT_UInt8 && eType != GDT_UInt16 && eType != GDT_Int16 &&
3933 : eType != GDT_Float32)
3934 : {
3935 27 : CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type");
3936 27 : return nullptr;
3937 : }
3938 138 : if (nBandsIn == 0 || nBandsIn > 32767)
3939 : {
3940 1 : CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
3941 1 : return nullptr;
3942 : }
3943 :
3944 : const char *pszDataLocation =
3945 137 : CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL");
3946 137 : const bool bIsTiled = CPLFetchBool(papszOptions, "TILED", false);
3947 : const int nBlockXSize = std::max(
3948 137 : 1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256")));
3949 : const int nBlockYSize = std::max(
3950 137 : 1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256")));
3951 171 : if (!EQUAL(pszDataLocation, "LABEL") &&
3952 171 : !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "LBL"))
3953 : {
3954 1 : CPLError(CE_Failure, CPLE_NotSupported,
3955 : "For DATA_LOCATION=%s, "
3956 : "the main filename should have a .lbl extension",
3957 : pszDataLocation);
3958 1 : return nullptr;
3959 : }
3960 :
3961 : const char *pszPermission =
3962 136 : VSISupportsRandomWrite(pszFilename, true) ? "wb+" : "wb";
3963 :
3964 136 : VSILFILE *fp = VSIFOpenExL(pszFilename, pszPermission, true);
3965 136 : if (fp == nullptr)
3966 : {
3967 3 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s: %s", pszFilename,
3968 : VSIGetLastErrorMsg());
3969 3 : return nullptr;
3970 : }
3971 133 : VSILFILE *fpImage = nullptr;
3972 266 : std::string osExternalFilename;
3973 133 : GDALDataset *poExternalDS = nullptr;
3974 133 : bool bGeoTIFFAsRegularExternal = false;
3975 133 : if (EQUAL(pszDataLocation, "EXTERNAL"))
3976 : {
3977 : osExternalFilename = CSLFetchNameValueDef(
3978 : papszOptions, "EXTERNAL_FILENAME",
3979 14 : CPLResetExtensionSafe(pszFilename, "cub").c_str());
3980 14 : fpImage = VSIFOpenExL(osExternalFilename.c_str(), pszPermission, true);
3981 14 : if (fpImage == nullptr)
3982 : {
3983 1 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s: %s",
3984 : osExternalFilename.c_str(), VSIGetLastErrorMsg());
3985 1 : VSIFCloseL(fp);
3986 1 : return nullptr;
3987 : }
3988 : }
3989 119 : else if (EQUAL(pszDataLocation, "GEOTIFF"))
3990 : {
3991 : osExternalFilename = CSLFetchNameValueDef(
3992 : papszOptions, "EXTERNAL_FILENAME",
3993 19 : CPLResetExtensionSafe(pszFilename, "tif").c_str());
3994 : GDALDriver *poDrv =
3995 19 : static_cast<GDALDriver *>(GDALGetDriverByName("GTiff"));
3996 19 : if (poDrv == nullptr)
3997 : {
3998 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GTiff driver");
3999 0 : VSIFCloseL(fp);
4000 0 : return nullptr;
4001 : }
4002 19 : char **papszGTiffOptions = nullptr;
4003 : papszGTiffOptions =
4004 19 : CSLSetNameValue(papszGTiffOptions, "ENDIANNESS", "LITTLE");
4005 19 : if (bIsTiled)
4006 : {
4007 : papszGTiffOptions =
4008 3 : CSLSetNameValue(papszGTiffOptions, "TILED", "YES");
4009 3 : papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKXSIZE",
4010 : CPLSPrintf("%d", nBlockXSize));
4011 3 : papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE",
4012 : CPLSPrintf("%d", nBlockYSize));
4013 : }
4014 : const char *pszGTiffOptions =
4015 19 : CSLFetchNameValueDef(papszOptions, "GEOTIFF_OPTIONS", "");
4016 19 : char **papszTokens = CSLTokenizeString2(pszGTiffOptions, ",", 0);
4017 28 : for (int i = 0; papszTokens[i] != nullptr; i++)
4018 : {
4019 9 : papszGTiffOptions = CSLAddString(papszGTiffOptions, papszTokens[i]);
4020 : }
4021 19 : CSLDestroy(papszTokens);
4022 :
4023 : // If the user didn't specify any compression and
4024 : // GEOTIFF_AS_REGULAR_EXTERNAL is set (or unspecified), then the
4025 : // GeoTIFF file can be seen as a regular external raw file, provided
4026 : // we make some provision on its organization.
4027 29 : if (CSLFetchNameValue(papszGTiffOptions, "COMPRESS") == nullptr &&
4028 10 : CPLFetchBool(papszOptions, "GEOTIFF_AS_REGULAR_EXTERNAL", true))
4029 : {
4030 9 : bGeoTIFFAsRegularExternal = true;
4031 : papszGTiffOptions =
4032 9 : CSLSetNameValue(papszGTiffOptions, GDALMD_INTERLEAVE, "BAND");
4033 : // Will make sure that our blocks at nodata are not optimized
4034 : // away but indeed well written
4035 9 : papszGTiffOptions = CSLSetNameValue(
4036 : papszGTiffOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "YES");
4037 9 : if (!bIsTiled && nBandsIn > 1)
4038 : {
4039 : papszGTiffOptions =
4040 1 : CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE", "1");
4041 : }
4042 : }
4043 :
4044 19 : poExternalDS = poDrv->Create(osExternalFilename.c_str(), nXSize, nYSize,
4045 : nBandsIn, eType, papszGTiffOptions);
4046 19 : CSLDestroy(papszGTiffOptions);
4047 19 : if (poExternalDS == nullptr)
4048 : {
4049 1 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s",
4050 : osExternalFilename.c_str());
4051 1 : VSIFCloseL(fp);
4052 1 : return nullptr;
4053 : }
4054 : }
4055 :
4056 131 : ISIS3Dataset *poDS = new ISIS3Dataset();
4057 131 : poDS->SetDescription(pszFilename);
4058 131 : poDS->eAccess = GA_Update;
4059 131 : poDS->nRasterXSize = nXSize;
4060 131 : poDS->nRasterYSize = nYSize;
4061 131 : poDS->m_osExternalFilename = std::move(osExternalFilename);
4062 131 : poDS->m_poExternalDS = poExternalDS;
4063 131 : poDS->m_bGeoTIFFAsRegularExternal = bGeoTIFFAsRegularExternal;
4064 131 : if (bGeoTIFFAsRegularExternal)
4065 8 : poDS->m_bGeoTIFFInitDone = false;
4066 131 : poDS->m_fpLabel = fp;
4067 131 : poDS->m_fpImage = fpImage ? fpImage : fp;
4068 131 : poDS->m_bIsLabelWritten = false;
4069 131 : poDS->m_bIsTiled = bIsTiled;
4070 131 : poDS->m_bInitToNodata = (poDS->m_poExternalDS == nullptr);
4071 131 : poDS->m_osComment = CSLFetchNameValueDef(papszOptions, "COMMENT", "");
4072 : poDS->m_osLatitudeType =
4073 131 : CSLFetchNameValueDef(papszOptions, "LATITUDE_TYPE", "");
4074 : poDS->m_osLongitudeDirection =
4075 131 : CSLFetchNameValueDef(papszOptions, "LONGITUDE_DIRECTION", "");
4076 : poDS->m_osTargetName =
4077 131 : CSLFetchNameValueDef(papszOptions, "TARGET_NAME", "");
4078 131 : poDS->m_bForce360 = CPLFetchBool(papszOptions, "FORCE_360", false);
4079 131 : poDS->m_bWriteBoundingDegrees =
4080 131 : CPLFetchBool(papszOptions, "WRITE_BOUNDING_DEGREES", true);
4081 : poDS->m_osBoundingDegrees =
4082 131 : CSLFetchNameValueDef(papszOptions, "BOUNDING_DEGREES", "");
4083 131 : poDS->m_bUseSrcLabel = CPLFetchBool(papszOptions, "USE_SRC_LABEL", true);
4084 131 : poDS->m_bUseSrcMapping =
4085 131 : CPLFetchBool(papszOptions, "USE_SRC_MAPPING", false);
4086 131 : poDS->m_bUseSrcHistory =
4087 131 : CPLFetchBool(papszOptions, "USE_SRC_HISTORY", true);
4088 131 : poDS->m_bAddGDALHistory =
4089 131 : CPLFetchBool(papszOptions, "ADD_GDAL_HISTORY", true);
4090 131 : if (poDS->m_bAddGDALHistory)
4091 : {
4092 : poDS->m_osGDALHistory =
4093 129 : CSLFetchNameValueDef(papszOptions, "GDAL_HISTORY", "");
4094 : }
4095 131 : const double dfNoData = (eType == GDT_UInt8) ? ISIS3_NULL1
4096 : : (eType == GDT_UInt16) ? ISIS3_NULLU2
4097 : : (eType == GDT_Int16)
4098 : ? ISIS3_NULL2
4099 : :
4100 : /*(eType == GDT_Float32) ?*/ ISIS3_NULL4;
4101 :
4102 303 : for (int i = 0; i < nBandsIn; i++)
4103 : {
4104 172 : GDALRasterBand *poBand = nullptr;
4105 :
4106 172 : if (poDS->m_poExternalDS != nullptr)
4107 : {
4108 : ISIS3WrapperRasterBand *poISISBand = new ISIS3WrapperRasterBand(
4109 24 : poDS->m_poExternalDS->GetRasterBand(i + 1));
4110 24 : poBand = poISISBand;
4111 : }
4112 148 : else if (bIsTiled)
4113 : {
4114 : ISISTiledBand *poISISBand = new ISISTiledBand(
4115 : poDS, poDS->m_fpImage, i + 1, eType, nBlockXSize, nBlockYSize,
4116 : 0, // nSkipBytes, to be hacked
4117 : // afterwards for in-label imagery
4118 10 : 0, 0, CPL_IS_LSB);
4119 :
4120 10 : poBand = poISISBand;
4121 : }
4122 : else
4123 : {
4124 138 : const int nPixelOffset = GDALGetDataTypeSizeBytes(eType);
4125 138 : const int nLineOffset = nPixelOffset * nXSize;
4126 138 : const vsi_l_offset nBandOffset =
4127 138 : static_cast<vsi_l_offset>(nLineOffset) * nYSize;
4128 : ISIS3RawRasterBand *poISISBand = new ISIS3RawRasterBand(
4129 : poDS, i + 1, poDS->m_fpImage,
4130 138 : nBandOffset * i, // nImgOffset, to be
4131 : // hacked afterwards for in-label imagery
4132 138 : nPixelOffset, nLineOffset, eType, CPL_IS_LSB);
4133 :
4134 138 : poBand = poISISBand;
4135 : }
4136 172 : poDS->SetBand(i + 1, poBand);
4137 172 : poBand->SetNoDataValue(dfNoData);
4138 : }
4139 :
4140 131 : return poDS;
4141 : }
4142 :
4143 : /************************************************************************/
4144 : /* GetUnderlyingDataset() */
4145 : /************************************************************************/
4146 :
4147 79 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
4148 : {
4149 158 : if (poSrcDS->GetDriver() != nullptr &&
4150 79 : poSrcDS->GetDriver() == GDALGetDriverByName("VRT"))
4151 : {
4152 2 : VRTDataset *poVRTDS = cpl::down_cast<VRTDataset *>(poSrcDS);
4153 2 : poSrcDS = poVRTDS->GetSingleSimpleSource();
4154 : }
4155 :
4156 79 : return poSrcDS;
4157 : }
4158 :
4159 : /************************************************************************/
4160 : /* CreateCopy() */
4161 : /************************************************************************/
4162 :
4163 79 : GDALDataset *ISIS3Dataset::CreateCopy(const char *pszFilename,
4164 : GDALDataset *poSrcDS, int /*bStrict*/,
4165 : CSLConstList papszOptions,
4166 : GDALProgressFunc pfnProgress,
4167 : void *pProgressData)
4168 : {
4169 : const char *pszDataLocation =
4170 79 : CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL");
4171 79 : GDALDataset *poSrcUnderlyingDS = GetUnderlyingDataset(poSrcDS);
4172 79 : if (poSrcUnderlyingDS == nullptr)
4173 2 : poSrcUnderlyingDS = poSrcDS;
4174 89 : if (EQUAL(pszDataLocation, "GEOTIFF") &&
4175 10 : strcmp(poSrcUnderlyingDS->GetDescription(),
4176 : CSLFetchNameValueDef(
4177 : papszOptions, "EXTERNAL_FILENAME",
4178 89 : CPLResetExtensionSafe(pszFilename, "tif").c_str())) == 0)
4179 : {
4180 1 : CPLError(CE_Failure, CPLE_NotSupported,
4181 : "Output file has same name as input file");
4182 1 : return nullptr;
4183 : }
4184 78 : if (poSrcDS->GetRasterCount() == 0)
4185 : {
4186 1 : CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
4187 1 : return nullptr;
4188 : }
4189 :
4190 77 : const int nXSize = poSrcDS->GetRasterXSize();
4191 77 : const int nYSize = poSrcDS->GetRasterYSize();
4192 77 : const int nBands = poSrcDS->GetRasterCount();
4193 77 : GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
4194 : ISIS3Dataset *poDS = reinterpret_cast<ISIS3Dataset *>(
4195 77 : Create(pszFilename, nXSize, nYSize, nBands, eType, papszOptions));
4196 77 : if (poDS == nullptr)
4197 10 : return nullptr;
4198 67 : poDS->m_osFromFilename = poSrcUnderlyingDS->GetDescription();
4199 :
4200 67 : GDALGeoTransform gt;
4201 67 : if (poSrcDS->GetGeoTransform(gt) == CE_None && gt != GDALGeoTransform())
4202 : {
4203 40 : poDS->SetGeoTransform(gt);
4204 : }
4205 :
4206 67 : auto poSrcSRS = poSrcDS->GetSpatialRef();
4207 67 : if (poSrcSRS)
4208 : {
4209 40 : poDS->SetSpatialRef(poSrcSRS);
4210 : }
4211 :
4212 159 : for (int i = 1; i <= nBands; i++)
4213 : {
4214 92 : const double dfOffset = poSrcDS->GetRasterBand(i)->GetOffset();
4215 92 : if (dfOffset != 0.0)
4216 1 : poDS->GetRasterBand(i)->SetOffset(dfOffset);
4217 :
4218 92 : const double dfScale = poSrcDS->GetRasterBand(i)->GetScale();
4219 92 : if (dfScale != 1.0)
4220 1 : poDS->GetRasterBand(i)->SetScale(dfScale);
4221 : }
4222 :
4223 : // Do we need to remap nodata ?
4224 67 : int bHasNoData = FALSE;
4225 67 : poDS->m_dfSrcNoData =
4226 67 : poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
4227 67 : poDS->m_bHasSrcNoData = CPL_TO_BOOL(bHasNoData);
4228 :
4229 67 : if (poDS->m_bUseSrcLabel)
4230 : {
4231 59 : CSLConstList papszMD_ISIS3 = poSrcDS->GetMetadata("json:ISIS3");
4232 59 : if (papszMD_ISIS3 != nullptr)
4233 : {
4234 21 : poDS->SetMetadata(papszMD_ISIS3, "json:ISIS3");
4235 : }
4236 : }
4237 :
4238 : // We don't need to initialize the imagery as we are going to copy it
4239 : // completely
4240 67 : poDS->m_bInitToNodata = false;
4241 67 : CPLErr eErr = GDALDatasetCopyWholeRaster(poSrcDS, poDS, nullptr,
4242 : pfnProgress, pProgressData);
4243 67 : poDS->FlushCache(false);
4244 67 : poDS->m_bHasSrcNoData = false;
4245 67 : if (eErr != CE_None)
4246 : {
4247 11 : delete poDS;
4248 11 : return nullptr;
4249 : }
4250 :
4251 56 : return poDS;
4252 : }
4253 :
4254 : /************************************************************************/
4255 : /* GDALRegister_ISIS3() */
4256 : /************************************************************************/
4257 :
4258 2138 : void GDALRegister_ISIS3()
4259 :
4260 : {
4261 2138 : if (GDALGetDriverByName(ISIS3_DRIVER_NAME) != nullptr)
4262 263 : return;
4263 :
4264 1875 : GDALDriver *poDriver = new GDALDriver();
4265 1875 : ISIS3DriverSetCommonMetadata(poDriver);
4266 :
4267 1875 : poDriver->pfnOpen = ISIS3Dataset::Open;
4268 1875 : poDriver->pfnCreate = ISIS3Dataset::Create;
4269 1875 : poDriver->pfnCreateCopy = ISIS3Dataset::CreateCopy;
4270 :
4271 1875 : GetGDALDriverManager()->RegisterDriver(poDriver);
4272 : }
|