Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: ESRI .hdr Driver
4 : * Purpose: Implementation of EHdrDataset
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 1999, Frank Warmerdam <warmerdam@pobox.com>
9 : * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "cpl_port.h"
15 : #include "ehdrdataset.h"
16 : #include "rawdataset.h"
17 :
18 : #include <algorithm>
19 : #include <cctype>
20 : #include <cerrno>
21 : #include <climits>
22 : #include <cmath>
23 : #include <cstddef>
24 : #include <cstdio>
25 : #include <cstdlib>
26 : #include <cstring>
27 : #if HAVE_FCNTL_H
28 : #include <fcntl.h>
29 : #endif
30 :
31 : #include <limits>
32 :
33 : #include "cpl_conv.h"
34 : #include "cpl_error.h"
35 : #include "cpl_progress.h"
36 : #include "cpl_string.h"
37 : #include "cpl_vsi.h"
38 : #include "gdal.h"
39 : #include "gdal_frmts.h"
40 : #include "gdal_pam.h"
41 : #include "gdal_priv.h"
42 : #include "ogr_core.h"
43 : #include "ogr_spatialref.h"
44 :
45 : constexpr int HAS_MIN_FLAG = 0x1;
46 : constexpr int HAS_MAX_FLAG = 0x2;
47 : constexpr int HAS_MEAN_FLAG = 0x4;
48 : constexpr int HAS_STDDEV_FLAG = 0x8;
49 : constexpr int HAS_ALL_FLAGS =
50 : HAS_MIN_FLAG | HAS_MAX_FLAG | HAS_MEAN_FLAG | HAS_STDDEV_FLAG;
51 :
52 : /************************************************************************/
53 : /* EHdrRasterBand() */
54 : /************************************************************************/
55 :
56 188 : EHdrRasterBand::EHdrRasterBand(GDALDataset *poDSIn, int nBandIn,
57 : VSILFILE *fpRawIn, vsi_l_offset nImgOffsetIn,
58 : int nPixelOffsetIn, int nLineOffsetIn,
59 : GDALDataType eDataTypeIn,
60 : RawRasterBand::ByteOrder eByteOrderIn,
61 188 : int nBitsIn)
62 : : RawRasterBand(poDSIn, nBandIn, fpRawIn, nImgOffsetIn, nPixelOffsetIn,
63 : nLineOffsetIn, eDataTypeIn, eByteOrderIn,
64 : RawRasterBand::OwnFP::NO),
65 : nBits(nBitsIn), nStartBit(0), nPixelOffsetBits(0), nLineOffsetBits(0),
66 : bNoDataSet(FALSE), dfNoData(0.0), dfMin(0.0), dfMax(0.0), dfMean(0.0),
67 188 : dfStdDev(0.0), minmaxmeanstddev(0)
68 : {
69 188 : m_bValid = RawRasterBand::IsValid();
70 :
71 188 : EHdrDataset *poEDS = reinterpret_cast<EHdrDataset *>(poDS);
72 :
73 188 : if (nBits < 8)
74 : {
75 0 : const int nSkipBytes = atoi(poEDS->GetKeyValue("SKIPBYTES"));
76 0 : if (nSkipBytes < 0 || nSkipBytes > std::numeric_limits<int>::max() / 8)
77 : {
78 0 : m_bValid = false;
79 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid SKIPBYTES: %d",
80 : nSkipBytes);
81 0 : nStartBit = 0;
82 : }
83 : else
84 : {
85 0 : nStartBit = static_cast<vsi_l_offset>(nSkipBytes) * 8;
86 : }
87 0 : if (nBand >= 2)
88 : {
89 : GIntBig nBandRowBytes =
90 0 : CPLAtoGIntBig(poEDS->GetKeyValue("BANDROWBYTES"));
91 0 : if (nBandRowBytes < 0)
92 : {
93 0 : m_bValid = false;
94 0 : CPLError(CE_Failure, CPLE_AppDefined,
95 : "Invalid BANDROWBYTES: " CPL_FRMT_GIB, nBandRowBytes);
96 0 : nBandRowBytes = 0;
97 : }
98 0 : vsi_l_offset nRowBytes = 0;
99 0 : if (nBandRowBytes == 0)
100 0 : nRowBytes =
101 0 : (static_cast<vsi_l_offset>(nBits) * poDS->GetRasterXSize() +
102 : 7) /
103 : 8;
104 : else
105 0 : nRowBytes = static_cast<vsi_l_offset>(nBandRowBytes);
106 :
107 0 : nStartBit += nRowBytes * (nBand - 1) * 8;
108 : }
109 :
110 0 : nPixelOffsetBits = nBits;
111 : GIntBig nTotalRowBytes =
112 0 : CPLAtoGIntBig(poEDS->GetKeyValue("TOTALROWBYTES"));
113 0 : if (nTotalRowBytes < 0 ||
114 0 : nTotalRowBytes > GINTBIG_MAX / 8 / poDS->GetRasterYSize())
115 : {
116 0 : m_bValid = false;
117 0 : CPLError(CE_Failure, CPLE_AppDefined,
118 : "Invalid TOTALROWBYTES: " CPL_FRMT_GIB, nTotalRowBytes);
119 0 : nTotalRowBytes = 0;
120 : }
121 0 : if (nTotalRowBytes > 0)
122 0 : nLineOffsetBits = static_cast<vsi_l_offset>(nTotalRowBytes * 8);
123 : else
124 0 : nLineOffsetBits = static_cast<vsi_l_offset>(nPixelOffsetBits) *
125 0 : poDS->GetRasterXSize();
126 :
127 0 : nBlockXSize = poDS->GetRasterXSize();
128 0 : nBlockYSize = 1;
129 :
130 0 : SetMetadataItem("NBITS", CPLString().Printf("%d", nBits),
131 : "IMAGE_STRUCTURE");
132 : }
133 188 : }
134 :
135 : /************************************************************************/
136 : /* IReadBlock() */
137 : /************************************************************************/
138 :
139 5351 : CPLErr EHdrRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
140 :
141 : {
142 5351 : if (nBits >= 8)
143 5351 : return RawRasterBand::IReadBlock(nBlockXOff, nBlockYOff, pImage);
144 :
145 : // Establish desired position.
146 0 : const vsi_l_offset nLineStart =
147 0 : (nStartBit + nLineOffsetBits * nBlockYOff) / 8;
148 0 : int iBitOffset =
149 0 : static_cast<int>((nStartBit + nLineOffsetBits * nBlockYOff) % 8);
150 0 : const vsi_l_offset nLineEnd =
151 0 : (nStartBit + nLineOffsetBits * nBlockYOff +
152 0 : static_cast<vsi_l_offset>(nPixelOffsetBits) * nBlockXSize - 1) /
153 : 8;
154 0 : const vsi_l_offset nLineBytesBig = nLineEnd - nLineStart + 1;
155 0 : if (nLineBytesBig >
156 0 : static_cast<vsi_l_offset>(std::numeric_limits<int>::max()))
157 0 : return CE_Failure;
158 0 : const unsigned int nLineBytes = static_cast<unsigned int>(nLineBytesBig);
159 :
160 : // Read data into buffer.
161 0 : GByte *pabyBuffer = static_cast<GByte *>(VSI_MALLOC_VERBOSE(nLineBytes));
162 0 : if (pabyBuffer == nullptr)
163 0 : return CE_Failure;
164 :
165 0 : if (VSIFSeekL(GetFPL(), nLineStart, SEEK_SET) != 0 ||
166 0 : VSIFReadL(pabyBuffer, 1, nLineBytes, GetFPL()) != nLineBytes)
167 : {
168 0 : CPLError(CE_Failure, CPLE_FileIO,
169 : "Failed to read %u bytes at offset %lu.\n%s", nLineBytes,
170 0 : static_cast<unsigned long>(nLineStart), VSIStrerror(errno));
171 0 : CPLFree(pabyBuffer);
172 0 : return CE_Failure;
173 : }
174 :
175 : // Copy data, promoting to 8bit.
176 0 : for (int iX = 0, iPixel = 0; iX < nBlockXSize; iX++)
177 : {
178 0 : int nOutWord = 0;
179 :
180 0 : for (int iBit = 0; iBit < nBits; iBit++)
181 : {
182 0 : if (pabyBuffer[iBitOffset >> 3] & (0x80 >> (iBitOffset & 7)))
183 0 : nOutWord |= (1 << (nBits - 1 - iBit));
184 0 : iBitOffset++;
185 : }
186 :
187 0 : iBitOffset = iBitOffset + nPixelOffsetBits - nBits;
188 :
189 0 : reinterpret_cast<GByte *>(pImage)[iPixel++] =
190 : static_cast<GByte>(nOutWord);
191 : }
192 :
193 0 : CPLFree(pabyBuffer);
194 :
195 0 : return CE_None;
196 : }
197 :
198 : /************************************************************************/
199 : /* IWriteBlock() */
200 : /************************************************************************/
201 :
202 3429 : CPLErr EHdrRasterBand::IWriteBlock(int nBlockXOff, int nBlockYOff, void *pImage)
203 :
204 : {
205 3429 : if (nBits >= 8)
206 3429 : return RawRasterBand::IWriteBlock(nBlockXOff, nBlockYOff, pImage);
207 :
208 : // Establish desired position.
209 0 : const vsi_l_offset nLineStart =
210 0 : (nStartBit + nLineOffsetBits * nBlockYOff) / 8;
211 0 : int iBitOffset =
212 0 : static_cast<int>((nStartBit + nLineOffsetBits * nBlockYOff) % 8);
213 0 : const vsi_l_offset nLineEnd =
214 0 : (nStartBit + nLineOffsetBits * nBlockYOff +
215 0 : static_cast<vsi_l_offset>(nPixelOffsetBits) * nBlockXSize - 1) /
216 : 8;
217 0 : const vsi_l_offset nLineBytesBig = nLineEnd - nLineStart + 1;
218 0 : if (nLineBytesBig >
219 0 : static_cast<vsi_l_offset>(std::numeric_limits<int>::max()))
220 0 : return CE_Failure;
221 0 : const unsigned int nLineBytes = static_cast<unsigned int>(nLineBytesBig);
222 :
223 : // Read data into buffer.
224 0 : GByte *pabyBuffer = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nLineBytes, 1));
225 0 : if (pabyBuffer == nullptr)
226 0 : return CE_Failure;
227 :
228 0 : if (VSIFSeekL(GetFPL(), nLineStart, SEEK_SET) != 0)
229 : {
230 0 : CPLError(CE_Failure, CPLE_FileIO,
231 : "Failed to read %u bytes at offset %lu.\n%s", nLineBytes,
232 0 : static_cast<unsigned long>(nLineStart), VSIStrerror(errno));
233 0 : CPLFree(pabyBuffer);
234 0 : return CE_Failure;
235 : }
236 :
237 0 : CPL_IGNORE_RET_VAL(VSIFReadL(pabyBuffer, nLineBytes, 1, GetFPL()));
238 :
239 : // Copy data, promoting to 8bit.
240 0 : for (int iX = 0, iPixel = 0; iX < nBlockXSize; iX++)
241 : {
242 0 : const int nOutWord = reinterpret_cast<GByte *>(pImage)[iPixel++];
243 :
244 0 : for (int iBit = 0; iBit < nBits; iBit++)
245 : {
246 0 : if (nOutWord & (1 << (nBits - 1 - iBit)))
247 0 : pabyBuffer[iBitOffset >> 3] |= (0x80 >> (iBitOffset & 7));
248 : else
249 0 : pabyBuffer[iBitOffset >> 3] &= ~((0x80 >> (iBitOffset & 7)));
250 :
251 0 : iBitOffset++;
252 : }
253 :
254 0 : iBitOffset = iBitOffset + nPixelOffsetBits - nBits;
255 : }
256 :
257 : // Write the data back out.
258 0 : if (VSIFSeekL(GetFPL(), nLineStart, SEEK_SET) != 0 ||
259 0 : VSIFWriteL(pabyBuffer, 1, nLineBytes, GetFPL()) != nLineBytes)
260 : {
261 0 : CPLError(CE_Failure, CPLE_FileIO,
262 : "Failed to write %u bytes at offset %lu.\n%s", nLineBytes,
263 0 : static_cast<unsigned long>(nLineStart), VSIStrerror(errno));
264 0 : return CE_Failure;
265 : }
266 :
267 0 : CPLFree(pabyBuffer);
268 :
269 0 : return CE_None;
270 : }
271 :
272 : /************************************************************************/
273 : /* IRasterIO() */
274 : /************************************************************************/
275 :
276 1744 : CPLErr EHdrRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
277 : int nXSize, int nYSize, void *pData,
278 : int nBufXSize, int nBufYSize,
279 : GDALDataType eBufType, GSpacing nPixelSpace,
280 : GSpacing nLineSpace,
281 : GDALRasterIOExtraArg *psExtraArg)
282 :
283 : {
284 : // Defer to RawRasterBand
285 1744 : if (nBits >= 8)
286 1744 : return RawRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
287 : pData, nBufXSize, nBufYSize, eBufType,
288 1744 : nPixelSpace, nLineSpace, psExtraArg);
289 :
290 : // Force use of IReadBlock() and IWriteBlock()
291 0 : return GDALRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
292 : pData, nBufXSize, nBufYSize, eBufType,
293 0 : nPixelSpace, nLineSpace, psExtraArg);
294 : }
295 :
296 : /************************************************************************/
297 : /* OSR_GDS() */
298 : /************************************************************************/
299 :
300 19 : static const char *OSR_GDS(char *pszResult, int nResultLen, char **papszNV,
301 : const char *pszField, const char *pszDefaultValue)
302 :
303 : {
304 19 : if (papszNV == nullptr || papszNV[0] == nullptr)
305 0 : return pszDefaultValue;
306 :
307 19 : int iLine = 0; // Used after for.
308 68 : for (; papszNV[iLine] != nullptr &&
309 50 : !EQUALN(papszNV[iLine], pszField, strlen(pszField));
310 : iLine++)
311 : {
312 : }
313 :
314 19 : if (papszNV[iLine] == nullptr)
315 18 : return pszDefaultValue;
316 :
317 1 : char **papszTokens = CSLTokenizeString(papszNV[iLine]);
318 :
319 1 : if (CSLCount(papszTokens) > 1)
320 1 : strncpy(pszResult, papszTokens[1], nResultLen - 1);
321 : else
322 0 : strncpy(pszResult, pszDefaultValue, nResultLen - 1);
323 1 : pszResult[nResultLen - 1] = '\0';
324 :
325 1 : CSLDestroy(papszTokens);
326 1 : return pszResult;
327 : }
328 :
329 : /************************************************************************/
330 : /* ==================================================================== */
331 : /* EHdrDataset */
332 : /* ==================================================================== */
333 : /************************************************************************/
334 :
335 : /************************************************************************/
336 : /* EHdrDataset() */
337 : /************************************************************************/
338 :
339 120 : EHdrDataset::EHdrDataset()
340 : : fpImage(nullptr), osHeaderExt("hdr"), bGotTransform(false),
341 120 : bHDRDirty(false), papszHDR(nullptr), bCLRDirty(false)
342 : {
343 120 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
344 120 : adfGeoTransform[0] = 0.0;
345 120 : adfGeoTransform[1] = 1.0;
346 120 : adfGeoTransform[2] = 0.0;
347 120 : adfGeoTransform[3] = 0.0;
348 120 : adfGeoTransform[4] = 0.0;
349 120 : adfGeoTransform[5] = 1.0;
350 120 : }
351 :
352 : /************************************************************************/
353 : /* ~EHdrDataset() */
354 : /************************************************************************/
355 :
356 240 : EHdrDataset::~EHdrDataset()
357 :
358 : {
359 120 : EHdrDataset::Close();
360 240 : }
361 :
362 : /************************************************************************/
363 : /* Close() */
364 : /************************************************************************/
365 :
366 235 : CPLErr EHdrDataset::Close()
367 : {
368 235 : CPLErr eErr = CE_None;
369 235 : if (nOpenFlags != OPEN_FLAGS_CLOSED)
370 : {
371 120 : if (EHdrDataset::FlushCache(true) != CE_None)
372 0 : eErr = CE_Failure;
373 :
374 120 : if (nBands > 0 && GetAccess() == GA_Update)
375 : {
376 : int bNoDataSet;
377 : RawRasterBand *poBand =
378 53 : reinterpret_cast<RawRasterBand *>(GetRasterBand(1));
379 :
380 53 : const double dfNoData = poBand->GetNoDataValue(&bNoDataSet);
381 53 : if (bNoDataSet)
382 : {
383 2 : ResetKeyValue("NODATA", CPLString().Printf("%.8g", dfNoData));
384 : }
385 :
386 53 : if (bCLRDirty)
387 4 : RewriteCLR(poBand);
388 :
389 53 : if (bHDRDirty)
390 : {
391 40 : if (RewriteHDR() != CE_None)
392 2 : eErr = CE_Failure;
393 : }
394 : }
395 :
396 120 : if (fpImage)
397 : {
398 120 : if (VSIFCloseL(fpImage) != 0)
399 : {
400 0 : CPLError(CE_Failure, CPLE_FileIO, "I/O error");
401 0 : eErr = CE_Failure;
402 : }
403 : }
404 :
405 120 : CSLDestroy(papszHDR);
406 120 : if (GDALPamDataset::Close() != CE_None)
407 0 : eErr = CE_Failure;
408 : }
409 235 : return eErr;
410 : }
411 :
412 : /************************************************************************/
413 : /* GetKeyValue() */
414 : /************************************************************************/
415 :
416 0 : const char *EHdrDataset::GetKeyValue(const char *pszKey, const char *pszDefault)
417 :
418 : {
419 0 : for (int i = 0; papszHDR[i] != nullptr; i++)
420 : {
421 0 : if (EQUALN(pszKey, papszHDR[i], strlen(pszKey)) &&
422 0 : isspace(static_cast<unsigned char>(papszHDR[i][strlen(pszKey)])))
423 : {
424 0 : const char *pszValue = papszHDR[i] + strlen(pszKey);
425 0 : while (isspace(static_cast<unsigned char>(*pszValue)))
426 0 : pszValue++;
427 :
428 0 : return pszValue;
429 : }
430 : }
431 :
432 0 : return pszDefault;
433 : }
434 :
435 : /************************************************************************/
436 : /* ResetKeyValue() */
437 : /* */
438 : /* Replace or add the keyword with the indicated value in the */
439 : /* papszHDR list. */
440 : /************************************************************************/
441 :
442 158 : void EHdrDataset::ResetKeyValue(const char *pszKey, const char *pszValue)
443 :
444 : {
445 158 : if (strlen(pszValue) > 65)
446 : {
447 0 : CPLAssert(strlen(pszValue) <= 65);
448 0 : return;
449 : }
450 :
451 158 : char szNewLine[82] = {'\0'};
452 158 : snprintf(szNewLine, sizeof(szNewLine), "%-15s%s", pszKey, pszValue);
453 :
454 1782 : for (int i = CSLCount(papszHDR) - 1; i >= 0; i--)
455 : {
456 1624 : if (EQUALN(papszHDR[i], szNewLine, strlen(pszKey) + 1))
457 : {
458 0 : if (strcmp(papszHDR[i], szNewLine) != 0)
459 : {
460 0 : CPLFree(papszHDR[i]);
461 0 : papszHDR[i] = CPLStrdup(szNewLine);
462 0 : bHDRDirty = true;
463 : }
464 0 : return;
465 : }
466 : }
467 :
468 158 : bHDRDirty = true;
469 158 : papszHDR = CSLAddString(papszHDR, szNewLine);
470 : }
471 :
472 : /************************************************************************/
473 : /* RewriteCLR() */
474 : /************************************************************************/
475 :
476 4 : void EHdrDataset::RewriteCLR(GDALRasterBand *poBand) const
477 :
478 : {
479 4 : CPLString osCLRFilename = CPLResetExtensionSafe(GetDescription(), "clr");
480 4 : GDALColorTable *poTable = poBand->GetColorTable();
481 4 : GDALRasterAttributeTable *poRAT = poBand->GetDefaultRAT();
482 4 : if (poTable || poRAT)
483 : {
484 3 : VSILFILE *fp = VSIFOpenL(osCLRFilename, "wt");
485 3 : if (fp != nullptr)
486 : {
487 : // Write RAT in priority if both are defined
488 3 : if (poRAT)
489 : {
490 26 : for (int iEntry = 0; iEntry < poRAT->GetRowCount(); iEntry++)
491 : {
492 25 : CPLString oLine;
493 : oLine.Printf("%3d %3d %3d %3d\n",
494 25 : poRAT->GetValueAsInt(iEntry, 0),
495 25 : poRAT->GetValueAsInt(iEntry, 1),
496 25 : poRAT->GetValueAsInt(iEntry, 2),
497 25 : poRAT->GetValueAsInt(iEntry, 3));
498 50 : if (VSIFWriteL(reinterpret_cast<void *>(
499 25 : const_cast<char *>(oLine.c_str())),
500 25 : strlen(oLine), 1, fp) != 1)
501 : {
502 0 : CPLError(CE_Failure, CPLE_FileIO,
503 : "Error while write color table");
504 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
505 0 : return;
506 : }
507 : }
508 : }
509 : else
510 : {
511 8 : for (int iColor = 0; iColor < poTable->GetColorEntryCount();
512 : iColor++)
513 : {
514 : GDALColorEntry sEntry;
515 6 : poTable->GetColorEntryAsRGB(iColor, &sEntry);
516 :
517 : // I wish we had a way to mark transparency.
518 6 : CPLString oLine;
519 6 : oLine.Printf("%3d %3d %3d %3d\n", iColor, sEntry.c1,
520 6 : sEntry.c2, sEntry.c3);
521 12 : if (VSIFWriteL(reinterpret_cast<void *>(
522 6 : const_cast<char *>(oLine.c_str())),
523 6 : strlen(oLine), 1, fp) != 1)
524 : {
525 0 : CPLError(CE_Failure, CPLE_FileIO,
526 : "Error while write color table");
527 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
528 0 : return;
529 : }
530 : }
531 : }
532 3 : if (VSIFCloseL(fp) != 0)
533 : {
534 0 : CPLError(CE_Failure, CPLE_FileIO,
535 : "Error while write color table");
536 : }
537 : }
538 : else
539 : {
540 0 : CPLError(CE_Failure, CPLE_OpenFailed,
541 : "Unable to create color file %s.", osCLRFilename.c_str());
542 3 : }
543 : }
544 : else
545 : {
546 1 : VSIUnlink(osCLRFilename);
547 : }
548 : }
549 :
550 : /************************************************************************/
551 : /* SetSpatialRef() */
552 : /************************************************************************/
553 :
554 37 : CPLErr EHdrDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
555 :
556 : {
557 : // Reset coordinate system on the dataset.
558 37 : m_oSRS.Clear();
559 37 : if (poSRS == nullptr)
560 0 : return CE_None;
561 :
562 37 : m_oSRS = *poSRS;
563 : // Convert to ESRI WKT.
564 37 : char *pszESRI_SRS = nullptr;
565 37 : const char *const apszOptions[] = {"FORMAT=WKT1_ESRI", nullptr};
566 37 : m_oSRS.exportToWkt(&pszESRI_SRS, apszOptions);
567 :
568 37 : if (pszESRI_SRS)
569 : {
570 : // Write to .prj file.
571 : CPLString osPrjFilename =
572 37 : CPLResetExtensionSafe(GetDescription(), "prj");
573 37 : VSILFILE *fp = VSIFOpenL(osPrjFilename.c_str(), "wt");
574 37 : if (fp != nullptr)
575 : {
576 37 : size_t nCount = VSIFWriteL(pszESRI_SRS, strlen(pszESRI_SRS), 1, fp);
577 37 : nCount += VSIFWriteL("\n", 1, 1, fp);
578 37 : if (VSIFCloseL(fp) != 0 || nCount != 2)
579 : {
580 2 : CPLFree(pszESRI_SRS);
581 2 : return CE_Failure;
582 : }
583 : }
584 :
585 35 : CPLFree(pszESRI_SRS);
586 : }
587 :
588 35 : return CE_None;
589 : }
590 :
591 : /************************************************************************/
592 : /* GetGeoTransform() */
593 : /************************************************************************/
594 :
595 29 : CPLErr EHdrDataset::GetGeoTransform(double *padfTransform)
596 :
597 : {
598 29 : if (bGotTransform)
599 : {
600 29 : memcpy(padfTransform, adfGeoTransform, sizeof(double) * 6);
601 29 : return CE_None;
602 : }
603 :
604 0 : return GDALPamDataset::GetGeoTransform(padfTransform);
605 : }
606 :
607 : /************************************************************************/
608 : /* SetGeoTransform() */
609 : /************************************************************************/
610 :
611 39 : CPLErr EHdrDataset::SetGeoTransform(double *padfGeoTransform)
612 :
613 : {
614 : // We only support non-rotated images with info in the .HDR file.
615 39 : if (padfGeoTransform[2] != 0.0 || padfGeoTransform[4] != 0.0)
616 : {
617 0 : return GDALPamDataset::SetGeoTransform(padfGeoTransform);
618 : }
619 :
620 : // Record new geotransform.
621 39 : bGotTransform = true;
622 39 : memcpy(adfGeoTransform, padfGeoTransform, sizeof(double) * 6);
623 :
624 : // Strip out all old geotransform keywords from HDR records.
625 385 : for (int i = CSLCount(papszHDR) - 1; i >= 0; i--)
626 : {
627 346 : if (STARTS_WITH_CI(papszHDR[i], "ul") ||
628 344 : STARTS_WITH_CI(papszHDR[i] + 1, "ll") ||
629 344 : STARTS_WITH_CI(papszHDR[i], "cell") ||
630 344 : STARTS_WITH_CI(papszHDR[i] + 1, "dim"))
631 : {
632 4 : papszHDR = CSLRemoveStrings(papszHDR, i, 1, nullptr);
633 : }
634 : }
635 :
636 : // Set the transformation information.
637 39 : CPLString oValue;
638 :
639 39 : oValue.Printf("%.15g", adfGeoTransform[0] + adfGeoTransform[1] * 0.5);
640 39 : ResetKeyValue("ULXMAP", oValue);
641 :
642 39 : oValue.Printf("%.15g", adfGeoTransform[3] + adfGeoTransform[5] * 0.5);
643 39 : ResetKeyValue("ULYMAP", oValue);
644 :
645 39 : oValue.Printf("%.15g", adfGeoTransform[1]);
646 39 : ResetKeyValue("XDIM", oValue);
647 :
648 39 : oValue.Printf("%.15g", fabs(adfGeoTransform[5]));
649 39 : ResetKeyValue("YDIM", oValue);
650 :
651 39 : return CE_None;
652 : }
653 :
654 : /************************************************************************/
655 : /* RewriteHDR() */
656 : /************************************************************************/
657 :
658 40 : CPLErr EHdrDataset::RewriteHDR()
659 :
660 : {
661 80 : const CPLString osPath = CPLGetPathSafe(GetDescription());
662 80 : const CPLString osName = CPLGetBasenameSafe(GetDescription());
663 : CPLString osHDRFilename =
664 80 : CPLFormCIFilenameSafe(osPath, osName, osHeaderExt);
665 :
666 : // Write .hdr file.
667 40 : VSILFILE *fp = VSIFOpenL(osHDRFilename, "wt");
668 :
669 40 : if (fp == nullptr)
670 : {
671 0 : CPLError(CE_Failure, CPLE_OpenFailed, "Failed to rewrite .hdr file %s.",
672 : osHDRFilename.c_str());
673 0 : return CE_Failure;
674 : }
675 :
676 541 : for (int i = 0; papszHDR[i] != nullptr; i++)
677 : {
678 503 : size_t nCount = VSIFWriteL(papszHDR[i], strlen(papszHDR[i]), 1, fp);
679 503 : nCount += VSIFWriteL("\n", 1, 1, fp);
680 503 : if (nCount != 2)
681 : {
682 2 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
683 2 : return CE_Failure;
684 : }
685 : }
686 :
687 38 : bHDRDirty = false;
688 :
689 38 : if (VSIFCloseL(fp) != 0)
690 0 : return CE_Failure;
691 :
692 38 : return CE_None;
693 : }
694 :
695 : /************************************************************************/
696 : /* RewriteSTX() */
697 : /************************************************************************/
698 :
699 4 : CPLErr EHdrDataset::RewriteSTX() const
700 : {
701 8 : const CPLString osPath = CPLGetPathSafe(GetDescription());
702 8 : const CPLString osName = CPLGetBasenameSafe(GetDescription());
703 : const CPLString osSTXFilename =
704 8 : CPLFormCIFilenameSafe(osPath, osName, "stx");
705 :
706 4 : VSILFILE *fp = VSIFOpenL(osSTXFilename, "wt");
707 4 : if (fp == nullptr)
708 : {
709 0 : CPLDebug("EHDR", "Failed to rewrite .stx file %s.",
710 : osSTXFilename.c_str());
711 0 : return CE_Failure;
712 : }
713 :
714 4 : bool bOK = true;
715 8 : for (int i = 0; bOK && i < nBands; ++i)
716 : {
717 4 : EHdrRasterBand *poBand =
718 4 : reinterpret_cast<EHdrRasterBand *>(papoBands[i]);
719 4 : bOK &= VSIFPrintfL(fp, "%d %.10f %.10f ", i + 1, poBand->dfMin,
720 4 : poBand->dfMax) >= 0;
721 4 : if (poBand->minmaxmeanstddev & HAS_MEAN_FLAG)
722 4 : bOK &= VSIFPrintfL(fp, "%.10f ", poBand->dfMean) >= 0;
723 : else
724 0 : bOK &= VSIFPrintfL(fp, "# ") >= 0;
725 :
726 4 : if (poBand->minmaxmeanstddev & HAS_STDDEV_FLAG)
727 4 : bOK &= VSIFPrintfL(fp, "%.10f\n", poBand->dfStdDev) >= 0;
728 : else
729 0 : bOK &= VSIFPrintfL(fp, "#\n") >= 0;
730 : }
731 :
732 4 : if (VSIFCloseL(fp) != 0)
733 0 : bOK = false;
734 :
735 4 : return bOK ? CE_None : CE_Failure;
736 : }
737 :
738 : /************************************************************************/
739 : /* ReadSTX() */
740 : /************************************************************************/
741 :
742 120 : CPLErr EHdrDataset::ReadSTX() const
743 : {
744 240 : const CPLString osPath = CPLGetPathSafe(GetDescription());
745 240 : const CPLString osName = CPLGetBasenameSafe(GetDescription());
746 : const CPLString osSTXFilename =
747 240 : CPLFormCIFilenameSafe(osPath, osName, "stx");
748 :
749 120 : VSILFILE *fp = VSIFOpenL(osSTXFilename, "rt");
750 120 : if (fp == nullptr)
751 117 : return CE_None;
752 :
753 3 : const char *pszLine = nullptr;
754 6 : while ((pszLine = CPLReadLineL(fp)) != nullptr)
755 : {
756 : char **papszTokens =
757 3 : CSLTokenizeStringComplex(pszLine, " \t", TRUE, FALSE);
758 3 : const int nTokens = CSLCount(papszTokens);
759 3 : if (nTokens >= 5)
760 : {
761 3 : const int i = atoi(papszTokens[0]);
762 3 : if (i > 0 && i <= nBands)
763 : {
764 3 : EHdrRasterBand *poBand =
765 3 : reinterpret_cast<EHdrRasterBand *>(papoBands[i - 1]);
766 3 : poBand->dfMin = CPLAtof(papszTokens[1]);
767 3 : poBand->dfMax = CPLAtof(papszTokens[2]);
768 :
769 3 : int bNoDataSet = FALSE;
770 3 : const double dfNoData = poBand->GetNoDataValue(&bNoDataSet);
771 3 : if (bNoDataSet && dfNoData == poBand->dfMin)
772 : {
773 : // Triggered by
774 : // /vsicurl/http://eros.usgs.gov/archive/nslrsda/GeoTowns/HongKong/srtm/n22e113.zip/n22e113.bil
775 0 : CPLDebug(
776 : "EHDr",
777 : "Ignoring .stx file where min == nodata. "
778 : "The nodata value should not be taken into account "
779 : "in minimum value computation.");
780 0 : CSLDestroy(papszTokens);
781 0 : papszTokens = nullptr;
782 0 : break;
783 : }
784 :
785 3 : poBand->minmaxmeanstddev = HAS_MIN_FLAG | HAS_MAX_FLAG;
786 : // Reads optional mean and stddev.
787 3 : if (!EQUAL(papszTokens[3], "#"))
788 : {
789 3 : poBand->dfMean = CPLAtof(papszTokens[3]);
790 3 : poBand->minmaxmeanstddev |= HAS_MEAN_FLAG;
791 : }
792 3 : if (!EQUAL(papszTokens[4], "#"))
793 : {
794 3 : poBand->dfStdDev = CPLAtof(papszTokens[4]);
795 3 : poBand->minmaxmeanstddev |= HAS_STDDEV_FLAG;
796 : }
797 :
798 3 : if (nTokens >= 6 && !EQUAL(papszTokens[5], "#"))
799 0 : poBand->SetMetadataItem("STRETCHMIN", papszTokens[5],
800 0 : "RENDERING_HINTS");
801 :
802 3 : if (nTokens >= 7 && !EQUAL(papszTokens[6], "#"))
803 0 : poBand->SetMetadataItem("STRETCHMAX", papszTokens[6],
804 0 : "RENDERING_HINTS");
805 : }
806 : }
807 :
808 3 : CSLDestroy(papszTokens);
809 : }
810 :
811 3 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
812 :
813 3 : return CE_None;
814 : }
815 :
816 : /************************************************************************/
817 : /* GetImageRepFilename() */
818 : /************************************************************************/
819 :
820 : // Check for IMAGE.REP (Spatiocarte Defense 1.0) or name_of_image.rep
821 : // if it is a GIS-GeoSPOT image.
822 : // For the specification of SPDF (in French), see
823 : // http://eden.ign.fr/download/pub/doc/emabgi/spdf10.pdf/download
824 :
825 103 : CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename)
826 : {
827 :
828 206 : const CPLString osPath = CPLGetPathSafe(pszFilename);
829 206 : const CPLString osName = CPLGetBasenameSafe(pszFilename);
830 206 : CPLString osREPFilename = CPLFormCIFilenameSafe(osPath, osName, "rep");
831 :
832 : VSIStatBufL sStatBuf;
833 103 : if (VSIStatExL(osREPFilename.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
834 0 : return osREPFilename;
835 :
836 206 : if (EQUAL(CPLGetFilename(pszFilename), "imspatio.bil") ||
837 103 : EQUAL(CPLGetFilename(pszFilename), "haspatio.bil"))
838 : {
839 : CPLString osImageRepFilename(
840 0 : CPLFormCIFilenameSafe(osPath, "image", "rep"));
841 0 : if (VSIStatExL(osImageRepFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) ==
842 : 0)
843 0 : return osImageRepFilename;
844 :
845 : // Try in the upper directories if not found in the BIL image directory.
846 0 : CPLString dirName(CPLGetDirnameSafe(osPath));
847 0 : if (CPLIsFilenameRelative(osPath.c_str()))
848 : {
849 0 : char *cwd = CPLGetCurrentDir();
850 0 : if (cwd)
851 : {
852 0 : dirName = CPLFormFilenameSafe(cwd, dirName.c_str(), nullptr);
853 0 : CPLFree(cwd);
854 : }
855 : }
856 0 : while (dirName[0] != 0 && EQUAL(dirName, ".") == FALSE &&
857 0 : EQUAL(dirName, "/") == FALSE)
858 : {
859 : osImageRepFilename =
860 0 : CPLFormCIFilenameSafe(dirName.c_str(), "image", "rep");
861 0 : if (VSIStatExL(osImageRepFilename.c_str(), &sStatBuf,
862 0 : VSI_STAT_EXISTS_FLAG) == 0)
863 0 : return osImageRepFilename;
864 :
865 : // Don't try to recurse above the 'image' subdirectory.
866 0 : if (EQUAL(dirName, "image"))
867 : {
868 0 : break;
869 : }
870 0 : dirName = CPLString(CPLGetDirnameSafe(dirName));
871 : }
872 : }
873 103 : return CPLString();
874 : }
875 :
876 : /************************************************************************/
877 : /* GetFileList() */
878 : /************************************************************************/
879 :
880 22 : char **EHdrDataset::GetFileList()
881 :
882 : {
883 44 : const CPLString osPath = CPLGetPathSafe(GetDescription());
884 44 : const CPLString osName = CPLGetBasenameSafe(GetDescription());
885 :
886 : // Main data file, etc.
887 22 : char **papszFileList = GDALPamDataset::GetFileList();
888 :
889 : // Header file.
890 44 : CPLString osFilename = CPLFormCIFilenameSafe(osPath, osName, osHeaderExt);
891 22 : papszFileList = CSLAddString(papszFileList, osFilename);
892 :
893 : // Statistics file
894 22 : osFilename = CPLFormCIFilenameSafe(osPath, osName, "stx");
895 : VSIStatBufL sStatBuf;
896 22 : if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
897 2 : papszFileList = CSLAddString(papszFileList, osFilename);
898 :
899 : // color table file.
900 22 : osFilename = CPLFormCIFilenameSafe(osPath, osName, "clr");
901 22 : if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
902 2 : papszFileList = CSLAddString(papszFileList, osFilename);
903 :
904 : // projections file.
905 22 : osFilename = CPLFormCIFilenameSafe(osPath, osName, "prj");
906 22 : if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0)
907 8 : papszFileList = CSLAddString(papszFileList, osFilename);
908 :
909 22 : const CPLString imageRepFilename = GetImageRepFilename(GetDescription());
910 22 : if (!imageRepFilename.empty())
911 0 : papszFileList = CSLAddString(papszFileList, imageRepFilename.c_str());
912 :
913 44 : return papszFileList;
914 : }
915 :
916 : /************************************************************************/
917 : /* Open() */
918 : /************************************************************************/
919 :
920 30313 : GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo)
921 :
922 : {
923 30313 : return Open(poOpenInfo, true);
924 : }
925 :
926 30362 : GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck)
927 :
928 : {
929 : // Assume the caller is pointing to the binary (i.e. .bil) file.
930 30362 : if (poOpenInfo->nHeaderBytes < 2 || poOpenInfo->fpL == nullptr)
931 29015 : return nullptr;
932 :
933 : // Tear apart the filename to form a .HDR filename.
934 2694 : const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename);
935 2694 : const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename);
936 :
937 1347 : const char *pszHeaderExt = "hdr";
938 1347 : if (poOpenInfo->IsExtensionEqualToCI("SRC") && osName.size() == 7 &&
939 0 : (osName[0] == 'e' || osName[0] == 'E' || osName[0] == 'w' ||
940 1347 : osName[0] == 'W') &&
941 0 : (osName[4] == 'n' || osName[4] == 'N' || osName[4] == 's' ||
942 0 : osName[4] == 'S'))
943 : {
944 : // It is a GTOPO30 or SRTM30 source file, whose header extension is .sch
945 : // see http://dds.cr.usgs.gov/srtm/version1/SRTM30/GTOPO30_Documentation
946 0 : pszHeaderExt = "sch";
947 : }
948 :
949 1347 : char **papszSiblingFiles = poOpenInfo->GetSiblingFiles();
950 2694 : CPLString osHDRFilename;
951 1347 : if (papszSiblingFiles)
952 : {
953 1342 : const int iFile = CSLFindString(
954 : papszSiblingFiles,
955 2684 : CPLFormFilenameSafe(nullptr, osName, pszHeaderExt).c_str());
956 1342 : if (iFile < 0) // Return if there is no corresponding .hdr file.
957 1200 : return nullptr;
958 :
959 : osHDRFilename =
960 142 : CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr);
961 : }
962 : else
963 : {
964 5 : osHDRFilename = CPLFormCIFilenameSafe(osPath, osName, pszHeaderExt);
965 : }
966 :
967 147 : const bool bSelectedHDR = EQUAL(osHDRFilename, poOpenInfo->pszFilename);
968 :
969 : // Do we have a .hdr file?
970 147 : VSILFILE *fp = VSIFOpenL(osHDRFilename, "r");
971 147 : if (fp == nullptr)
972 : {
973 5 : return nullptr;
974 : }
975 :
976 : // Is this file an ESRI header file? Read a few lines of text
977 : // searching for something starting with nrows or ncols.
978 142 : int nRows = -1;
979 142 : int nCols = -1;
980 142 : int l_nBands = 1;
981 142 : int nSkipBytes = 0;
982 142 : double dfULXMap = 0.5;
983 142 : double dfULYMap = 0.5;
984 142 : double dfYLLCorner = -123.456;
985 142 : int bCenter = TRUE;
986 142 : double dfXDim = 1.0;
987 142 : double dfYDim = 1.0;
988 142 : double dfNoData = 0.0;
989 142 : int nLineCount = 0;
990 142 : int bNoDataSet = FALSE;
991 142 : GDALDataType eDataType = GDT_Byte;
992 142 : int nBits = -1;
993 142 : char chByteOrder = 'M';
994 142 : char chPixelType = 'N'; // Not defined.
995 142 : char szLayout[10] = "BIL";
996 142 : char **papszHDR = nullptr;
997 142 : int bHasInternalProjection = FALSE;
998 142 : int bHasMin = FALSE;
999 142 : int bHasMax = FALSE;
1000 142 : double dfMin = 0;
1001 142 : double dfMax = 0;
1002 :
1003 142 : const char *pszLine = nullptr;
1004 1643 : while ((pszLine = CPLReadLineL(fp)) != nullptr)
1005 : {
1006 1502 : nLineCount++;
1007 :
1008 1502 : if (nLineCount > 50 || strlen(pszLine) > 1000)
1009 : break;
1010 :
1011 1501 : papszHDR = CSLAddString(papszHDR, pszLine);
1012 :
1013 : char **papszTokens =
1014 1501 : CSLTokenizeStringComplex(pszLine, " \t", TRUE, FALSE);
1015 1501 : if (CSLCount(papszTokens) < 2)
1016 : {
1017 45 : CSLDestroy(papszTokens);
1018 45 : continue;
1019 : }
1020 :
1021 1456 : if (EQUAL(papszTokens[0], "ncols"))
1022 : {
1023 120 : nCols = atoi(papszTokens[1]);
1024 : }
1025 1336 : else if (EQUAL(papszTokens[0], "nrows"))
1026 : {
1027 122 : nRows = atoi(papszTokens[1]);
1028 : }
1029 1214 : else if (EQUAL(papszTokens[0], "skipbytes"))
1030 : {
1031 0 : nSkipBytes = atoi(papszTokens[1]);
1032 : }
1033 1214 : else if (EQUAL(papszTokens[0], "ulxmap") ||
1034 1170 : EQUAL(papszTokens[0], "xllcorner") ||
1035 1166 : EQUAL(papszTokens[0], "xllcenter"))
1036 : {
1037 48 : dfULXMap = CPLAtofM(papszTokens[1]);
1038 48 : if (EQUAL(papszTokens[0], "xllcorner"))
1039 4 : bCenter = FALSE;
1040 : }
1041 1166 : else if (EQUAL(papszTokens[0], "ulymap"))
1042 : {
1043 44 : dfULYMap = CPLAtofM(papszTokens[1]);
1044 : }
1045 1122 : else if (EQUAL(papszTokens[0], "yllcorner") ||
1046 1118 : EQUAL(papszTokens[0], "yllcenter"))
1047 : {
1048 4 : dfYLLCorner = CPLAtofM(papszTokens[1]);
1049 4 : if (EQUAL(papszTokens[0], "yllcorner"))
1050 4 : bCenter = FALSE;
1051 : }
1052 1118 : else if (EQUAL(papszTokens[0], "xdim"))
1053 : {
1054 44 : dfXDim = CPLAtofM(papszTokens[1]);
1055 : }
1056 1074 : else if (EQUAL(papszTokens[0], "ydim"))
1057 : {
1058 44 : dfYDim = CPLAtofM(papszTokens[1]);
1059 : }
1060 1030 : else if (EQUAL(papszTokens[0], "cellsize"))
1061 : {
1062 4 : dfXDim = CPLAtofM(papszTokens[1]);
1063 4 : dfYDim = dfXDim;
1064 : }
1065 1026 : else if (EQUAL(papszTokens[0], "nbands"))
1066 : {
1067 114 : l_nBands = atoi(papszTokens[1]);
1068 : }
1069 912 : else if (EQUAL(papszTokens[0], "layout"))
1070 : {
1071 120 : snprintf(szLayout, sizeof(szLayout), "%s", papszTokens[1]);
1072 : }
1073 792 : else if (EQUAL(papszTokens[0], "NODATA_value") ||
1074 792 : EQUAL(papszTokens[0], "NODATA"))
1075 : {
1076 4 : dfNoData = CPLAtofM(papszTokens[1]);
1077 4 : bNoDataSet = TRUE;
1078 : }
1079 788 : else if (EQUAL(papszTokens[0], "NBITS"))
1080 : {
1081 114 : nBits = atoi(papszTokens[1]);
1082 : }
1083 674 : else if (EQUAL(papszTokens[0], "PIXELTYPE"))
1084 : {
1085 110 : chPixelType = static_cast<char>(
1086 110 : toupper(static_cast<unsigned char>(papszTokens[1][0])));
1087 : }
1088 564 : else if (EQUAL(papszTokens[0], "byteorder"))
1089 : {
1090 126 : chByteOrder = static_cast<char>(
1091 126 : toupper(static_cast<unsigned char>(papszTokens[1][0])));
1092 : }
1093 :
1094 : // http://www.worldclim.org/futdown.htm have the projection extensions
1095 438 : else if (EQUAL(papszTokens[0], "Projection"))
1096 : {
1097 3 : bHasInternalProjection = TRUE;
1098 : }
1099 435 : else if (EQUAL(papszTokens[0], "MinValue") ||
1100 434 : EQUAL(papszTokens[0], "MIN_VALUE"))
1101 : {
1102 1 : dfMin = CPLAtofM(papszTokens[1]);
1103 1 : bHasMin = TRUE;
1104 : }
1105 434 : else if (EQUAL(papszTokens[0], "MaxValue") ||
1106 433 : EQUAL(papszTokens[0], "MAX_VALUE"))
1107 : {
1108 1 : dfMax = CPLAtofM(papszTokens[1]);
1109 1 : bHasMax = TRUE;
1110 : }
1111 :
1112 1456 : CSLDestroy(papszTokens);
1113 : }
1114 :
1115 142 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
1116 :
1117 : // Did we get the required keywords? If not, return with this never having
1118 : // been considered to be a match. This isn't an error!
1119 142 : if (nRows == -1 || nCols == -1)
1120 : {
1121 22 : CSLDestroy(papszHDR);
1122 22 : return nullptr;
1123 : }
1124 :
1125 240 : if (!GDALCheckDatasetDimensions(nCols, nRows) ||
1126 120 : !GDALCheckBandCount(l_nBands, FALSE))
1127 : {
1128 0 : CSLDestroy(papszHDR);
1129 0 : return nullptr;
1130 : }
1131 :
1132 : // Has the caller selected the .hdr file to open?
1133 120 : if (bSelectedHDR)
1134 : {
1135 0 : CPLError(CE_Failure, CPLE_AppDefined,
1136 : "The selected file is an ESRI BIL header file, but to "
1137 : "open ESRI BIL datasets, the data file should be selected "
1138 : "instead of the .hdr file. Please try again selecting "
1139 : "the data file (often with the extension .bil) corresponding "
1140 : "to the header file: %s",
1141 : poOpenInfo->pszFilename);
1142 0 : CSLDestroy(papszHDR);
1143 0 : return nullptr;
1144 : }
1145 :
1146 : // If we aren't sure of the file type, check the data file size. If it is 4
1147 : // bytes or more per pixel then we assume it is floating point data.
1148 120 : if (nBits == -1 && chPixelType == 'N')
1149 : {
1150 : VSIStatBufL sStatBuf;
1151 6 : if (VSIStatL(poOpenInfo->pszFilename, &sStatBuf) == 0)
1152 : {
1153 6 : const size_t nBytes = static_cast<size_t>(sStatBuf.st_size / nCols /
1154 6 : nRows / l_nBands);
1155 6 : if (nBytes > 0 && nBytes != 3)
1156 2 : nBits = static_cast<int>(nBytes * 8);
1157 :
1158 6 : if (nBytes == 4)
1159 2 : chPixelType = 'F';
1160 : }
1161 : }
1162 :
1163 : // If the extension is FLT it is likely a floating point file.
1164 120 : if (chPixelType == 'N')
1165 : {
1166 8 : if (poOpenInfo->IsExtensionEqualToCI("FLT"))
1167 2 : chPixelType = 'F';
1168 : }
1169 :
1170 : // If we have a negative nodata value, assume that the
1171 : // pixel type is signed. This is necessary for datasets from
1172 : // http://www.worldclim.org/futdown.htm
1173 :
1174 120 : if (bNoDataSet && dfNoData < 0 && chPixelType == 'N')
1175 : {
1176 2 : chPixelType = 'S';
1177 : }
1178 :
1179 240 : auto poDS = std::make_unique<EHdrDataset>();
1180 :
1181 120 : poDS->osHeaderExt = pszHeaderExt;
1182 :
1183 120 : poDS->nRasterXSize = nCols;
1184 120 : poDS->nRasterYSize = nRows;
1185 120 : poDS->papszHDR = papszHDR;
1186 120 : std::swap(poDS->fpImage, poOpenInfo->fpL);
1187 120 : poDS->eAccess = poOpenInfo->eAccess;
1188 :
1189 : // Figure out the data type.
1190 120 : if (nBits == 16)
1191 : {
1192 21 : if (chPixelType == 'S')
1193 13 : eDataType = GDT_Int16;
1194 : else
1195 8 : eDataType = GDT_UInt16; // Default
1196 : }
1197 99 : else if (nBits == 32)
1198 : {
1199 34 : if (chPixelType == 'S')
1200 8 : eDataType = GDT_Int32;
1201 26 : else if (chPixelType == 'F')
1202 21 : eDataType = GDT_Float32;
1203 : else
1204 5 : eDataType = GDT_UInt32; // Default
1205 : }
1206 65 : else if (nBits >= 1 && nBits <= 8)
1207 : {
1208 61 : if (chPixelType == 'S')
1209 6 : eDataType = GDT_Int8;
1210 : else
1211 55 : eDataType = GDT_Byte;
1212 61 : nBits = 8;
1213 : }
1214 4 : else if (nBits == -1)
1215 : {
1216 4 : if (chPixelType == 'F')
1217 : {
1218 0 : eDataType = GDT_Float32;
1219 0 : nBits = 32;
1220 : }
1221 : else
1222 : {
1223 4 : eDataType = GDT_Byte;
1224 4 : nBits = 8;
1225 : }
1226 : }
1227 : else
1228 : {
1229 0 : CPLError(CE_Failure, CPLE_NotSupported,
1230 : "EHdr driver does not support %d NBITS value.", nBits);
1231 0 : return nullptr;
1232 : }
1233 :
1234 : // Compute the line offset.
1235 120 : const int nItemSize = GDALGetDataTypeSizeBytes(eDataType);
1236 120 : CPLAssert(nItemSize != 0);
1237 120 : CPLAssert(l_nBands != 0);
1238 :
1239 120 : int nPixelOffset = 0;
1240 120 : int nLineOffset = 0;
1241 120 : vsi_l_offset nBandOffset = 0;
1242 :
1243 120 : if (EQUAL(szLayout, "BIP"))
1244 : {
1245 0 : if (nCols > std::numeric_limits<int>::max() / (nItemSize * l_nBands))
1246 : {
1247 0 : CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
1248 0 : return nullptr;
1249 : }
1250 0 : nPixelOffset = nItemSize * l_nBands;
1251 0 : nLineOffset = nPixelOffset * nCols;
1252 0 : nBandOffset = static_cast<vsi_l_offset>(nItemSize);
1253 : }
1254 120 : else if (EQUAL(szLayout, "BSQ"))
1255 : {
1256 0 : if (nCols > std::numeric_limits<int>::max() / nItemSize)
1257 : {
1258 0 : CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
1259 0 : return nullptr;
1260 : }
1261 0 : nPixelOffset = nItemSize;
1262 0 : nLineOffset = nPixelOffset * nCols;
1263 0 : nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nRows;
1264 : }
1265 : else
1266 : {
1267 : // Assume BIL.
1268 120 : if (nCols > std::numeric_limits<int>::max() / (nItemSize * l_nBands))
1269 : {
1270 0 : CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
1271 0 : return nullptr;
1272 : }
1273 120 : nPixelOffset = nItemSize;
1274 120 : nLineOffset = nItemSize * l_nBands * nCols;
1275 120 : nBandOffset = static_cast<vsi_l_offset>(nItemSize) * nCols;
1276 : }
1277 :
1278 192 : if (nBits >= 8 && bFileSizeCheck &&
1279 72 : !RAWDatasetCheckMemoryUsage(
1280 72 : poDS->nRasterXSize, poDS->nRasterYSize, l_nBands, nItemSize,
1281 72 : nPixelOffset, nLineOffset, nSkipBytes, nBandOffset, poDS->fpImage))
1282 : {
1283 0 : return nullptr;
1284 : }
1285 :
1286 120 : poDS->SetDescription(poOpenInfo->pszFilename);
1287 120 : poDS->PamInitialize();
1288 :
1289 : // Create band information objects.
1290 308 : for (int i = 0; i < l_nBands; i++)
1291 : {
1292 : auto poBand = std::make_unique<EHdrRasterBand>(
1293 188 : poDS.get(), i + 1, poDS->fpImage, nSkipBytes + nBandOffset * i,
1294 : nPixelOffset, nLineOffset, eDataType,
1295 : chByteOrder == 'I' || chByteOrder == 'L'
1296 188 : ? RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN
1297 : : RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN,
1298 188 : nBits);
1299 188 : if (!poBand->IsValid())
1300 0 : return nullptr;
1301 :
1302 188 : poBand->bNoDataSet = bNoDataSet;
1303 188 : poBand->dfNoData = dfNoData;
1304 :
1305 188 : if (bHasMin && bHasMax)
1306 : {
1307 1 : poBand->dfMin = dfMin;
1308 1 : poBand->dfMax = dfMax;
1309 1 : poBand->minmaxmeanstddev = HAS_MIN_FLAG | HAS_MAX_FLAG;
1310 : }
1311 :
1312 188 : poDS->SetBand(i + 1, std::move(poBand));
1313 : }
1314 :
1315 : // If we didn't get bounds in the .hdr, look for a worldfile.
1316 120 : if (dfYLLCorner != -123.456)
1317 : {
1318 4 : if (bCenter)
1319 0 : dfULYMap = dfYLLCorner + (nRows - 1) * dfYDim;
1320 : else
1321 4 : dfULYMap = dfYLLCorner + nRows * dfYDim;
1322 : }
1323 :
1324 120 : if (dfULXMap != 0.5 || dfULYMap != 0.5 || dfXDim != 1.0 || dfYDim != 1.0)
1325 : {
1326 48 : poDS->bGotTransform = true;
1327 :
1328 48 : if (bCenter)
1329 : {
1330 44 : poDS->adfGeoTransform[0] = dfULXMap - dfXDim * 0.5;
1331 44 : poDS->adfGeoTransform[1] = dfXDim;
1332 44 : poDS->adfGeoTransform[2] = 0.0;
1333 44 : poDS->adfGeoTransform[3] = dfULYMap + dfYDim * 0.5;
1334 44 : poDS->adfGeoTransform[4] = 0.0;
1335 44 : poDS->adfGeoTransform[5] = -dfYDim;
1336 : }
1337 : else
1338 : {
1339 4 : poDS->adfGeoTransform[0] = dfULXMap;
1340 4 : poDS->adfGeoTransform[1] = dfXDim;
1341 4 : poDS->adfGeoTransform[2] = 0.0;
1342 4 : poDS->adfGeoTransform[3] = dfULYMap;
1343 4 : poDS->adfGeoTransform[4] = 0.0;
1344 4 : poDS->adfGeoTransform[5] = -dfYDim;
1345 : }
1346 : }
1347 :
1348 120 : if (!poDS->bGotTransform)
1349 72 : poDS->bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
1350 72 : poOpenInfo->pszFilename, nullptr, poDS->adfGeoTransform));
1351 :
1352 120 : if (!poDS->bGotTransform)
1353 72 : poDS->bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
1354 72 : poOpenInfo->pszFilename, "wld", poDS->adfGeoTransform));
1355 :
1356 : // Check for a .prj file.
1357 240 : std::string osPrjFilename = CPLFormCIFilenameSafe(osPath, osName, "prj");
1358 :
1359 120 : fp = VSIFOpenL(osPrjFilename.c_str(), "r");
1360 :
1361 : // .hdr files from http://www.worldclim.org/futdown.htm have the projection
1362 : // info in the .hdr file itself.
1363 120 : if (fp == nullptr && bHasInternalProjection)
1364 : {
1365 1 : osPrjFilename = std::move(osHDRFilename);
1366 1 : fp = VSIFOpenL(osPrjFilename.c_str(), "r");
1367 : }
1368 :
1369 120 : if (fp != nullptr)
1370 : {
1371 39 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
1372 39 : fp = nullptr;
1373 :
1374 39 : char **papszLines = CSLLoad(osPrjFilename.c_str());
1375 :
1376 39 : if (poDS->m_oSRS.importFromESRI(papszLines) == OGRERR_NONE)
1377 : {
1378 : // If geographic values are in seconds, we must transform.
1379 : // Is there a code for minutes too?
1380 37 : char szResult[80] = {'\0'};
1381 56 : if (poDS->m_oSRS.IsGeographic() &&
1382 19 : EQUAL(OSR_GDS(szResult, sizeof(szResult), papszLines, "Units",
1383 : ""),
1384 : "DS"))
1385 : {
1386 0 : poDS->adfGeoTransform[0] /= 3600.0;
1387 0 : poDS->adfGeoTransform[1] /= 3600.0;
1388 0 : poDS->adfGeoTransform[2] /= 3600.0;
1389 0 : poDS->adfGeoTransform[3] /= 3600.0;
1390 0 : poDS->adfGeoTransform[4] /= 3600.0;
1391 0 : poDS->adfGeoTransform[5] /= 3600.0;
1392 : }
1393 : }
1394 : else
1395 : {
1396 2 : poDS->m_oSRS.Clear();
1397 : }
1398 :
1399 39 : CSLDestroy(papszLines);
1400 : }
1401 : else
1402 : {
1403 : // Check for IMAGE.REP (Spatiocarte Defense 1.0) or name_of_image.rep
1404 : // if it is a GIS-GeoSPOT image
1405 : // For the specification of SPDF (in French), see
1406 : // http://eden.ign.fr/download/pub/doc/emabgi/spdf10.pdf/download
1407 : const CPLString szImageRepFilename =
1408 162 : GetImageRepFilename(poOpenInfo->pszFilename);
1409 81 : if (!szImageRepFilename.empty())
1410 : {
1411 0 : fp = VSIFOpenL(szImageRepFilename.c_str(), "r");
1412 : }
1413 81 : if (fp != nullptr)
1414 : {
1415 0 : bool bUTM = false;
1416 0 : bool bWGS84 = false;
1417 0 : int bNorth = FALSE;
1418 0 : bool bSouth = false;
1419 0 : int utmZone = 0;
1420 :
1421 0 : while ((pszLine = CPLReadLineL(fp)) != nullptr)
1422 : {
1423 0 : if (STARTS_WITH(pszLine, "PROJ_ID") && strstr(pszLine, "UTM"))
1424 : {
1425 0 : bUTM = true;
1426 : }
1427 0 : else if (STARTS_WITH(pszLine, "PROJ_ZONE"))
1428 : {
1429 0 : const char *c = strchr(pszLine, '"');
1430 0 : if (c)
1431 : {
1432 0 : c++;
1433 0 : if (*c >= '0' && *c <= '9')
1434 : {
1435 0 : utmZone = atoi(c);
1436 0 : if (utmZone >= 1 && utmZone <= 60)
1437 : {
1438 0 : if (strstr(pszLine, "Nord") ||
1439 0 : strstr(pszLine, "NORD"))
1440 : {
1441 0 : bNorth = TRUE;
1442 : }
1443 0 : else if (strstr(pszLine, "Sud") ||
1444 0 : strstr(pszLine, "SUD"))
1445 : {
1446 0 : bSouth = true;
1447 : }
1448 : }
1449 : }
1450 : }
1451 : }
1452 0 : else if (STARTS_WITH(pszLine, "PROJ_CODE") &&
1453 0 : strstr(pszLine, "FR-MINDEF"))
1454 : {
1455 0 : const char *c = strchr(pszLine, 'A');
1456 0 : if (c)
1457 : {
1458 0 : c++;
1459 0 : if (*c >= '0' && *c <= '9')
1460 : {
1461 0 : utmZone = atoi(c);
1462 0 : if (utmZone >= 1 && utmZone <= 60)
1463 : {
1464 0 : if (c[1] == 'N' ||
1465 0 : (c[1] != '\0' && c[2] == 'N'))
1466 : {
1467 0 : bNorth = TRUE;
1468 : }
1469 0 : else if (c[1] == 'S' ||
1470 0 : (c[1] != '\0' && c[2] == 'S'))
1471 : {
1472 0 : bSouth = true;
1473 : }
1474 : }
1475 : }
1476 0 : }
1477 : }
1478 0 : else if (STARTS_WITH(pszLine, "HORIZ_DATUM") &&
1479 0 : (strstr(pszLine, "WGS 84") ||
1480 0 : strstr(pszLine, "WGS84")))
1481 : {
1482 0 : bWGS84 = true;
1483 : }
1484 0 : else if (STARTS_WITH(pszLine, "MAP_NUMBER"))
1485 : {
1486 0 : const char *c = strchr(pszLine, '"');
1487 0 : if (c)
1488 : {
1489 0 : char *pszMapNumber = CPLStrdup(c + 1);
1490 0 : char *c2 = strchr(pszMapNumber, '"');
1491 0 : if (c2)
1492 0 : *c2 = 0;
1493 0 : poDS->SetMetadataItem("SPDF_MAP_NUMBER", pszMapNumber);
1494 0 : CPLFree(pszMapNumber);
1495 : }
1496 : }
1497 0 : else if (STARTS_WITH(pszLine, "PRODUCTION_DATE"))
1498 : {
1499 0 : const char *c = pszLine + strlen("PRODUCTION_DATE");
1500 0 : while (*c == ' ')
1501 0 : c++;
1502 0 : if (*c)
1503 : {
1504 0 : poDS->SetMetadataItem("SPDF_PRODUCTION_DATE", c);
1505 : }
1506 : }
1507 : }
1508 :
1509 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
1510 :
1511 0 : if (utmZone >= 1 && utmZone <= 60 && bUTM && bWGS84 &&
1512 0 : (bNorth || bSouth))
1513 : {
1514 0 : char projCSStr[64] = {'\0'};
1515 0 : snprintf(projCSStr, sizeof(projCSStr), "WGS 84 / UTM zone %d%c",
1516 : utmZone, (bNorth) ? 'N' : 'S');
1517 :
1518 0 : poDS->m_oSRS.SetProjCS(projCSStr);
1519 0 : poDS->m_oSRS.SetWellKnownGeogCS("WGS84");
1520 0 : poDS->m_oSRS.SetUTM(utmZone, bNorth);
1521 0 : poDS->m_oSRS.SetAuthority("PROJCS", "EPSG",
1522 0 : (bNorth ? 32600 : 32700) + utmZone);
1523 0 : poDS->m_oSRS.AutoIdentifyEPSG();
1524 : }
1525 : else
1526 : {
1527 0 : CPLError(CE_Warning, CPLE_NotSupported,
1528 : "Cannot retrieve projection from IMAGE.REP");
1529 : }
1530 : }
1531 : }
1532 :
1533 : // Check for a color table.
1534 : const std::string osCLRFilename =
1535 240 : CPLFormCIFilenameSafe(osPath, osName, "clr");
1536 :
1537 : // Only read the .clr for byte, int16 or uint16 bands.
1538 120 : if (nItemSize <= 2)
1539 86 : fp = VSIFOpenL(osCLRFilename.c_str(), "r");
1540 : else
1541 34 : fp = nullptr;
1542 :
1543 120 : if (fp != nullptr)
1544 : {
1545 : std::shared_ptr<GDALRasterAttributeTable> poRat(
1546 7 : new GDALDefaultRasterAttributeTable());
1547 7 : poRat->CreateColumn("Value", GFT_Integer, GFU_Generic);
1548 7 : poRat->CreateColumn("Red", GFT_Integer, GFU_Red);
1549 7 : poRat->CreateColumn("Green", GFT_Integer, GFU_Green);
1550 7 : poRat->CreateColumn("Blue", GFT_Integer, GFU_Blue);
1551 :
1552 7 : poDS->m_poColorTable.reset(new GDALColorTable());
1553 :
1554 7 : bool bHasFoundNonCTValues = false;
1555 7 : int nRatRow = 0;
1556 :
1557 : while (true)
1558 : {
1559 94 : pszLine = CPLReadLineL(fp);
1560 94 : if (!pszLine)
1561 7 : break;
1562 :
1563 87 : if (*pszLine == '#' || *pszLine == '!')
1564 0 : continue;
1565 :
1566 : char **papszValues =
1567 87 : CSLTokenizeString2(pszLine, "\t ", CSLT_HONOURSTRINGS);
1568 :
1569 87 : if (CSLCount(papszValues) >= 4)
1570 : {
1571 87 : const int nIndex = atoi(papszValues[0]);
1572 87 : poRat->SetValue(nRatRow, 0, nIndex);
1573 87 : poRat->SetValue(nRatRow, 1, atoi(papszValues[1]));
1574 87 : poRat->SetValue(nRatRow, 2, atoi(papszValues[2]));
1575 87 : poRat->SetValue(nRatRow, 3, atoi(papszValues[3]));
1576 87 : nRatRow++;
1577 :
1578 87 : if (nIndex >= 0 && nIndex < 65536)
1579 : {
1580 72 : const GDALColorEntry oEntry = {
1581 72 : static_cast<short>(atoi(papszValues[1])), // Red
1582 72 : static_cast<short>(atoi(papszValues[2])), // Green
1583 72 : static_cast<short>(atoi(papszValues[3])), // Blue
1584 72 : 255};
1585 :
1586 72 : poDS->m_poColorTable->SetColorEntry(nIndex, &oEntry);
1587 : }
1588 : else
1589 : {
1590 : // Negative values are valid. At least we can find use of
1591 : // them here:
1592 : // http://www.ngdc.noaa.gov/mgg/topo/elev/esri/clr/
1593 : // But, there's no way of representing them with GDAL color
1594 : // table model.
1595 15 : if (!bHasFoundNonCTValues)
1596 3 : CPLDebug("EHdr", "Ignoring color index : %d", nIndex);
1597 15 : bHasFoundNonCTValues = true;
1598 : }
1599 : }
1600 :
1601 87 : CSLDestroy(papszValues);
1602 87 : }
1603 :
1604 7 : CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
1605 :
1606 7 : if (bHasFoundNonCTValues)
1607 : {
1608 3 : poDS->m_poRAT.swap(poRat);
1609 : }
1610 :
1611 14 : for (int i = 1; i <= poDS->nBands; i++)
1612 : {
1613 : EHdrRasterBand *poBand =
1614 7 : cpl::down_cast<EHdrRasterBand *>(poDS->GetRasterBand(i));
1615 7 : poBand->m_poColorTable = poDS->m_poColorTable;
1616 7 : poBand->m_poRAT = poDS->m_poRAT;
1617 7 : poBand->SetColorInterpretation(GCI_PaletteIndex);
1618 : }
1619 :
1620 7 : poDS->bCLRDirty = false;
1621 : }
1622 :
1623 : // Read statistics (.STX).
1624 120 : poDS->ReadSTX();
1625 :
1626 : // Initialize any PAM information.
1627 120 : poDS->TryLoadXML();
1628 :
1629 : // Check for overviews.
1630 120 : poDS->oOvManager.Initialize(poDS.get(), poOpenInfo->pszFilename);
1631 :
1632 120 : return poDS.release();
1633 : }
1634 :
1635 : /************************************************************************/
1636 : /* Create() */
1637 : /************************************************************************/
1638 :
1639 79 : GDALDataset *EHdrDataset::Create(const char *pszFilename, int nXSize,
1640 : int nYSize, int nBandsIn, GDALDataType eType,
1641 : char **papszParamList)
1642 :
1643 : {
1644 : // Verify input options.
1645 79 : if (nBandsIn <= 0)
1646 : {
1647 1 : CPLError(CE_Failure, CPLE_NotSupported,
1648 : "EHdr driver does not support %d bands.", nBandsIn);
1649 1 : return nullptr;
1650 : }
1651 :
1652 78 : if (eType != GDT_Byte && eType != GDT_Int8 && eType != GDT_Float32 &&
1653 30 : eType != GDT_UInt16 && eType != GDT_Int16 && eType != GDT_Int32 &&
1654 : eType != GDT_UInt32)
1655 : {
1656 19 : CPLError(CE_Failure, CPLE_AppDefined,
1657 : "Attempt to create ESRI .hdr labelled dataset with an illegal"
1658 : "data type (%s).",
1659 : GDALGetDataTypeName(eType));
1660 :
1661 19 : return nullptr;
1662 : }
1663 :
1664 : // Try to create the file.
1665 59 : VSILFILE *fp = VSIFOpenL(pszFilename, "wb");
1666 :
1667 59 : if (fp == nullptr)
1668 : {
1669 3 : CPLError(CE_Failure, CPLE_OpenFailed,
1670 : "Attempt to create file `%s' failed.", pszFilename);
1671 3 : return nullptr;
1672 : }
1673 :
1674 : // Just write out a couple of bytes to establish the binary
1675 : // file, and then close it.
1676 56 : bool bOK = VSIFWriteL(reinterpret_cast<void *>(const_cast<char *>("\0\0")),
1677 56 : 2, 1, fp) == 1;
1678 56 : if (VSIFCloseL(fp) != 0)
1679 0 : bOK = false;
1680 56 : fp = nullptr;
1681 56 : if (!bOK)
1682 1 : return nullptr;
1683 :
1684 : // Create the hdr filename.
1685 : char *const pszHdrFilename =
1686 55 : CPLStrdup(CPLResetExtensionSafe(pszFilename, "hdr").c_str());
1687 :
1688 : // Open the file.
1689 55 : fp = VSIFOpenL(pszHdrFilename, "wt");
1690 55 : if (fp == nullptr)
1691 : {
1692 0 : CPLError(CE_Failure, CPLE_OpenFailed,
1693 : "Attempt to create file `%s' failed.", pszHdrFilename);
1694 0 : CPLFree(pszHdrFilename);
1695 0 : return nullptr;
1696 : }
1697 :
1698 : // Decide how many bits the file should have.
1699 55 : int nBits = GDALGetDataTypeSize(eType);
1700 :
1701 55 : if (CSLFetchNameValue(papszParamList, "NBITS") != nullptr)
1702 1 : nBits = atoi(CSLFetchNameValue(papszParamList, "NBITS"));
1703 :
1704 55 : const int nRowBytes = (nBits * nXSize + 7) / 8;
1705 :
1706 : // Check for signed byte.
1707 55 : const char *pszPixelType = CSLFetchNameValue(papszParamList, "PIXELTYPE");
1708 55 : if (pszPixelType == nullptr)
1709 54 : pszPixelType = "";
1710 :
1711 : // Write out the raw definition for the dataset as a whole.
1712 55 : bOK &= VSIFPrintfL(fp, "BYTEORDER I\n") >= 0;
1713 55 : bOK &= VSIFPrintfL(fp, "LAYOUT BIL\n") >= 0;
1714 55 : bOK &= VSIFPrintfL(fp, "NROWS %d\n", nYSize) >= 0;
1715 55 : bOK &= VSIFPrintfL(fp, "NCOLS %d\n", nXSize) >= 0;
1716 55 : bOK &= VSIFPrintfL(fp, "NBANDS %d\n", nBandsIn) >= 0;
1717 55 : bOK &= VSIFPrintfL(fp, "NBITS %d\n", nBits) >= 0;
1718 55 : bOK &= VSIFPrintfL(fp, "BANDROWBYTES %d\n", nRowBytes) >= 0;
1719 55 : bOK &= VSIFPrintfL(fp, "TOTALROWBYTES %d\n", nRowBytes * nBandsIn) >= 0;
1720 :
1721 55 : if (eType == GDT_Float32)
1722 5 : bOK &= VSIFPrintfL(fp, "PIXELTYPE FLOAT\n") >= 0;
1723 50 : else if (eType == GDT_Int8 || eType == GDT_Int16 || eType == GDT_Int32)
1724 10 : bOK &= VSIFPrintfL(fp, "PIXELTYPE SIGNEDINT\n") >= 0;
1725 40 : else if (eType == GDT_Byte && EQUAL(pszPixelType, "SIGNEDBYTE"))
1726 1 : bOK &= VSIFPrintfL(fp, "PIXELTYPE SIGNEDINT\n") >= 0;
1727 : else
1728 39 : bOK &= VSIFPrintfL(fp, "PIXELTYPE UNSIGNEDINT\n") >= 0;
1729 :
1730 55 : if (VSIFCloseL(fp) != 0)
1731 0 : bOK = false;
1732 :
1733 55 : CPLFree(pszHdrFilename);
1734 :
1735 55 : if (!bOK)
1736 0 : return nullptr;
1737 :
1738 110 : GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
1739 55 : return Open(&oOpenInfo, false);
1740 : }
1741 :
1742 : /************************************************************************/
1743 : /* CreateCopy() */
1744 : /************************************************************************/
1745 :
1746 40 : GDALDataset *EHdrDataset::CreateCopy(const char *pszFilename,
1747 : GDALDataset *poSrcDS, int bStrict,
1748 : char **papszOptions,
1749 : GDALProgressFunc pfnProgress,
1750 : void *pProgressData)
1751 :
1752 : {
1753 40 : const int nBands = poSrcDS->GetRasterCount();
1754 40 : if (nBands == 0)
1755 : {
1756 1 : CPLError(CE_Failure, CPLE_NotSupported,
1757 : "EHdr driver does not support source dataset without any "
1758 : "bands.");
1759 1 : return nullptr;
1760 : }
1761 :
1762 39 : char **papszAdjustedOptions = CSLDuplicate(papszOptions);
1763 :
1764 : // Ensure we pass on NBITS and PIXELTYPE structure information.
1765 39 : auto poSrcBand = poSrcDS->GetRasterBand(1);
1766 39 : if (poSrcBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE") != nullptr &&
1767 0 : CSLFetchNameValue(papszOptions, "NBITS") == nullptr)
1768 : {
1769 0 : papszAdjustedOptions = CSLSetNameValue(
1770 : papszAdjustedOptions, "NBITS",
1771 0 : poSrcBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"));
1772 : }
1773 :
1774 64 : if (poSrcBand->GetRasterDataType() == GDT_Byte &&
1775 25 : CSLFetchNameValue(papszOptions, "PIXELTYPE") == nullptr)
1776 : {
1777 25 : poSrcBand->EnablePixelTypeSignedByteWarning(false);
1778 : const char *pszPixelType =
1779 25 : poSrcBand->GetMetadataItem("PIXELTYPE", "IMAGE_STRUCTURE");
1780 25 : poSrcBand->EnablePixelTypeSignedByteWarning(true);
1781 25 : if (pszPixelType != nullptr)
1782 : {
1783 1 : papszAdjustedOptions = CSLSetNameValue(papszAdjustedOptions,
1784 : "PIXELTYPE", pszPixelType);
1785 : }
1786 : }
1787 :
1788 : // Proceed with normal copying using the default createcopy operators.
1789 : GDALDriver *poDriver =
1790 39 : reinterpret_cast<GDALDriver *>(GDALGetDriverByName("EHdr"));
1791 :
1792 39 : GDALDataset *poOutDS = poDriver->DefaultCreateCopy(
1793 : pszFilename, poSrcDS, bStrict, papszAdjustedOptions, pfnProgress,
1794 : pProgressData);
1795 39 : CSLDestroy(papszAdjustedOptions);
1796 :
1797 39 : if (poOutDS != nullptr)
1798 21 : poOutDS->FlushCache(false);
1799 :
1800 39 : return poOutDS;
1801 : }
1802 :
1803 : /************************************************************************/
1804 : /* GetNoDataValue() */
1805 : /************************************************************************/
1806 :
1807 102 : double EHdrRasterBand::GetNoDataValue(int *pbSuccess)
1808 : {
1809 102 : if (pbSuccess)
1810 102 : *pbSuccess = bNoDataSet;
1811 :
1812 102 : if (bNoDataSet)
1813 1 : return dfNoData;
1814 :
1815 101 : return RawRasterBand::GetNoDataValue(pbSuccess);
1816 : }
1817 :
1818 : /************************************************************************/
1819 : /* GetMinimum() */
1820 : /************************************************************************/
1821 :
1822 3 : double EHdrRasterBand::GetMinimum(int *pbSuccess)
1823 : {
1824 3 : if (pbSuccess != nullptr)
1825 3 : *pbSuccess = (minmaxmeanstddev & HAS_MIN_FLAG) != 0;
1826 :
1827 3 : if (minmaxmeanstddev & HAS_MIN_FLAG)
1828 2 : return dfMin;
1829 :
1830 1 : return RawRasterBand::GetMinimum(pbSuccess);
1831 : }
1832 :
1833 : /************************************************************************/
1834 : /* GetMaximum() */
1835 : /************************************************************************/
1836 :
1837 2 : double EHdrRasterBand::GetMaximum(int *pbSuccess)
1838 : {
1839 2 : if (pbSuccess != nullptr)
1840 2 : *pbSuccess = (minmaxmeanstddev & HAS_MAX_FLAG) != 0;
1841 :
1842 2 : if (minmaxmeanstddev & HAS_MAX_FLAG)
1843 1 : return dfMax;
1844 :
1845 1 : return RawRasterBand::GetMaximum(pbSuccess);
1846 : }
1847 :
1848 : /************************************************************************/
1849 : /* GetStatistics() */
1850 : /************************************************************************/
1851 :
1852 6 : CPLErr EHdrRasterBand::GetStatistics(int bApproxOK, int bForce, double *pdfMin,
1853 : double *pdfMax, double *pdfMean,
1854 : double *pdfStdDev)
1855 : {
1856 6 : if (!(GetMetadataItem("STATISTICS_APPROXIMATE") && !bApproxOK))
1857 : {
1858 5 : if ((minmaxmeanstddev & HAS_ALL_FLAGS) == HAS_ALL_FLAGS)
1859 : {
1860 1 : if (pdfMin)
1861 1 : *pdfMin = dfMin;
1862 1 : if (pdfMax)
1863 1 : *pdfMax = dfMax;
1864 1 : if (pdfMean)
1865 1 : *pdfMean = dfMean;
1866 1 : if (pdfStdDev)
1867 1 : *pdfStdDev = dfStdDev;
1868 1 : return CE_None;
1869 : }
1870 : }
1871 :
1872 5 : const CPLErr eErr = RawRasterBand::GetStatistics(
1873 : bApproxOK, bForce, &dfMin, &dfMax, &dfMean, &dfStdDev);
1874 5 : if (eErr != CE_None)
1875 2 : return eErr;
1876 :
1877 3 : EHdrDataset *poEDS = reinterpret_cast<EHdrDataset *>(poDS);
1878 :
1879 3 : minmaxmeanstddev = HAS_ALL_FLAGS;
1880 :
1881 3 : if (!bApproxOK && poEDS->RewriteSTX() != CE_None)
1882 0 : RawRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev);
1883 :
1884 3 : if (pdfMin)
1885 3 : *pdfMin = dfMin;
1886 3 : if (pdfMax)
1887 3 : *pdfMax = dfMax;
1888 3 : if (pdfMean)
1889 3 : *pdfMean = dfMean;
1890 3 : if (pdfStdDev)
1891 3 : *pdfStdDev = dfStdDev;
1892 :
1893 3 : return CE_None;
1894 : }
1895 :
1896 : /************************************************************************/
1897 : /* SetStatistics() */
1898 : /************************************************************************/
1899 :
1900 3 : CPLErr EHdrRasterBand::SetStatistics(double dfMinIn, double dfMaxIn,
1901 : double dfMeanIn, double dfStdDevIn)
1902 : {
1903 : // Avoid churn if nothing is changing.
1904 3 : if (dfMin == dfMinIn && dfMax == dfMaxIn && dfMean == dfMeanIn &&
1905 1 : dfStdDev == dfStdDevIn)
1906 1 : return CE_None;
1907 :
1908 2 : dfMin = dfMinIn;
1909 2 : dfMax = dfMaxIn;
1910 2 : dfMean = dfMeanIn;
1911 2 : dfStdDev = dfStdDevIn;
1912 :
1913 : // marks stats valid
1914 2 : minmaxmeanstddev = HAS_ALL_FLAGS;
1915 :
1916 2 : EHdrDataset *poEDS = reinterpret_cast<EHdrDataset *>(poDS);
1917 :
1918 2 : if (GetMetadataItem("STATISTICS_APPROXIMATE") == nullptr)
1919 : {
1920 2 : if (GetMetadataItem("STATISTICS_MINIMUM"))
1921 : {
1922 0 : SetMetadataItem("STATISTICS_MINIMUM", nullptr);
1923 0 : SetMetadataItem("STATISTICS_MAXIMUM", nullptr);
1924 0 : SetMetadataItem("STATISTICS_MEAN", nullptr);
1925 0 : SetMetadataItem("STATISTICS_STDDEV", nullptr);
1926 : }
1927 2 : return poEDS->RewriteSTX();
1928 : }
1929 :
1930 0 : return RawRasterBand::SetStatistics(dfMinIn, dfMaxIn, dfMeanIn, dfStdDevIn);
1931 : }
1932 :
1933 : /************************************************************************/
1934 : /* GetColorTable() */
1935 : /************************************************************************/
1936 :
1937 13 : GDALColorTable *EHdrRasterBand::GetColorTable()
1938 : {
1939 13 : return m_poColorTable.get();
1940 : }
1941 :
1942 : /************************************************************************/
1943 : /* SetColorTable() */
1944 : /************************************************************************/
1945 :
1946 6 : CPLErr EHdrRasterBand::SetColorTable(GDALColorTable *poNewCT)
1947 : {
1948 6 : if (poNewCT == nullptr)
1949 2 : m_poColorTable.reset();
1950 : else
1951 4 : m_poColorTable.reset(poNewCT->Clone());
1952 :
1953 6 : reinterpret_cast<EHdrDataset *>(poDS)->bCLRDirty = true;
1954 :
1955 6 : return CE_None;
1956 : }
1957 :
1958 : /************************************************************************/
1959 : /* GetDefaultRAT() */
1960 : /************************************************************************/
1961 :
1962 13 : GDALRasterAttributeTable *EHdrRasterBand::GetDefaultRAT()
1963 : {
1964 13 : return m_poRAT.get();
1965 : }
1966 :
1967 : /************************************************************************/
1968 : /* SetDefaultRAT() */
1969 : /************************************************************************/
1970 :
1971 3 : CPLErr EHdrRasterBand::SetDefaultRAT(const GDALRasterAttributeTable *poRAT)
1972 : {
1973 3 : if (poRAT)
1974 : {
1975 3 : if (!(poRAT->GetColumnCount() == 4 &&
1976 1 : poRAT->GetTypeOfCol(0) == GFT_Integer &&
1977 1 : poRAT->GetTypeOfCol(1) == GFT_Integer &&
1978 1 : poRAT->GetTypeOfCol(2) == GFT_Integer &&
1979 1 : poRAT->GetTypeOfCol(3) == GFT_Integer &&
1980 1 : poRAT->GetUsageOfCol(0) == GFU_Generic &&
1981 1 : poRAT->GetUsageOfCol(1) == GFU_Red &&
1982 1 : poRAT->GetUsageOfCol(2) == GFU_Green &&
1983 1 : poRAT->GetUsageOfCol(3) == GFU_Blue))
1984 : {
1985 1 : CPLError(CE_Warning, CPLE_NotSupported,
1986 : "Unsupported type of RAT: "
1987 : "only value,R,G,B ones are supported");
1988 1 : return CE_Failure;
1989 : }
1990 : }
1991 :
1992 2 : if (poRAT == nullptr)
1993 1 : m_poRAT.reset();
1994 : else
1995 1 : m_poRAT.reset(poRAT->Clone());
1996 :
1997 2 : reinterpret_cast<EHdrDataset *>(poDS)->bCLRDirty = true;
1998 :
1999 2 : return CE_None;
2000 : }
2001 :
2002 : /************************************************************************/
2003 : /* GDALRegister_EHdr() */
2004 : /************************************************************************/
2005 :
2006 1889 : void GDALRegister_EHdr()
2007 :
2008 : {
2009 1889 : if (GDALGetDriverByName("EHdr") != nullptr)
2010 282 : return;
2011 :
2012 1607 : GDALDriver *poDriver = new GDALDriver();
2013 :
2014 1607 : poDriver->SetDescription("EHdr");
2015 1607 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
2016 1607 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "ESRI .hdr Labelled");
2017 1607 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/ehdr.html");
2018 1607 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "bil");
2019 1607 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES,
2020 1607 : "Byte Int8 Int16 UInt16 Int32 UInt32 Float32");
2021 :
2022 1607 : poDriver->SetMetadataItem(
2023 : GDAL_DMD_CREATIONOPTIONLIST,
2024 : "<CreationOptionList>"
2025 : " <Option name='NBITS' type='int' description='Special pixel bits "
2026 : "(1-7)'/>"
2027 : " <Option name='PIXELTYPE' type='string' description='By setting "
2028 : "this to SIGNEDBYTE, a new Byte file can be forced to be written as "
2029 : "signed byte'/>"
2030 1607 : "</CreationOptionList>");
2031 :
2032 1607 : poDriver->SetMetadataItem(GDAL_DCAP_UPDATE, "YES");
2033 1607 : poDriver->SetMetadataItem(GDAL_DMD_UPDATE_ITEMS, "GeoTransform SRS NoData "
2034 1607 : "RasterValues");
2035 :
2036 1607 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
2037 1607 : poDriver->pfnOpen = EHdrDataset::Open;
2038 1607 : poDriver->pfnCreate = EHdrDataset::Create;
2039 1607 : poDriver->pfnCreateCopy = EHdrDataset::CreateCopy;
2040 :
2041 1607 : GetGDALDriverManager()->RegisterDriver(poDriver);
2042 : }
|