Debian Codegraph @

src/LercLib/Lerc.cpp

raw symbols SCIP
1 /*
2 Copyright 2015 - 2026 Esri
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 A local copy of the license and additional notices are located with the
17 source distribution at:
18
19 http://github.com/Esri/lerc/
20
21 Contributors: Thomas Maurer
22 */
23
24 #include "Defines.h"
25 #include "Lerc.h"
26 #include "Lerc2.h"
27 #include <cstring>
28 #include <functional>
29 #include <limits>
30 #include <typeinfo>
31
32 #ifdef HAVE_LERC1_DECODE
33 #include "Lerc1Decode/CntZImage.h"
34 #endif
35
36 using namespace std;
37 USING_NAMESPACE_LERC
38
39 // -------------------------------------------------------------------------- ;
40
41 ErrCode Lerc::ComputeCompressedSize(const void* pData, int version, DataType dt, int nDepth, int nCols, int nRows, int nBands,
42 int nMasks, const Byte* pValidBytes, double maxZErr, unsigned int& numBytesNeeded, const unsigned char* pUsesNoData, const double* noDataValues)
43 {
44 #define LERC_ARG_1 version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr, numBytesNeeded, pUsesNoData, noDataValues
45
46 switch (dt)
47 {
48 case DT_Char: return ComputeCompressedSizeTempl((const signed char*)pData, LERC_ARG_1);
49 case DT_Byte: return ComputeCompressedSizeTempl((const Byte*)pData, LERC_ARG_1);
50 case DT_Short: return ComputeCompressedSizeTempl((const short*)pData, LERC_ARG_1);
51 case DT_UShort: return ComputeCompressedSizeTempl((const unsigned short*)pData, LERC_ARG_1);
52 case DT_Int: return ComputeCompressedSizeTempl((const int*)pData, LERC_ARG_1);
53 case DT_UInt: return ComputeCompressedSizeTempl((const unsigned int*)pData, LERC_ARG_1);
54 case DT_Float: return ComputeCompressedSizeTempl((const float*)pData, LERC_ARG_1);
55 case DT_Double: return ComputeCompressedSizeTempl((const double*)pData, LERC_ARG_1);
56
57 default:
58 return ErrCode::WrongParam;
59 }
60
61 #undef LERC_ARG_1
62 }
63
64 // -------------------------------------------------------------------------- ;
65
66 ErrCode Lerc::Encode(const void* pData, int version, DataType dt, int nDepth, int nCols, int nRows, int nBands,
67 int nMasks, const Byte* pValidBytes, double maxZErr, Byte* pBuffer, unsigned int numBytesBuffer,
68 unsigned int& numBytesWritten, const unsigned char* pUsesNoData, const double* noDataValues)
69 {
70 #define LERC_ARG_2 version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr, pBuffer, numBytesBuffer, numBytesWritten, pUsesNoData, noDataValues
71
72 switch (dt)
73 {
74 case DT_Char: return EncodeTempl((const signed char*)pData, LERC_ARG_2);
75 case DT_Byte: return EncodeTempl((const Byte*)pData, LERC_ARG_2);
76 case DT_Short: return EncodeTempl((const short*)pData, LERC_ARG_2);
77 case DT_UShort: return EncodeTempl((const unsigned short*)pData, LERC_ARG_2);
78 case DT_Int: return EncodeTempl((const int*)pData, LERC_ARG_2);
79 case DT_UInt: return EncodeTempl((const unsigned int*)pData, LERC_ARG_2);
80 case DT_Float: return EncodeTempl((const float*)pData, LERC_ARG_2);
81 case DT_Double: return EncodeTempl((const double*)pData, LERC_ARG_2);
82
83 default:
84 return ErrCode::WrongParam;
85 }
86
87 #undef LERC_ARG_2
88 }
89
90 // -------------------------------------------------------------------------- ;
91
92 ErrCode Lerc::GetLercInfo(const Byte* pLercBlob, unsigned int numBytesBlob, struct LercInfo& lercInfo, double* pMins, double* pMaxs, size_t nElem)
93 {
94 lercInfo.RawInit();
95
96 // first try Lerc2
97 struct Lerc2::HeaderInfo lerc2Info;
98 bool bHasMask = false;
99 int nMasks = 0;
100
101 if (Lerc2::GetHeaderInfo(pLercBlob, numBytesBlob, lerc2Info, bHasMask))
102 {
103 if (lerc2Info.blobSize < 0)
104 return ErrCode::Failed;
105
106 lercInfo.version = lerc2Info.version;
107 lercInfo.nDepth = lerc2Info.nDepth;
108 lercInfo.nCols = lerc2Info.nCols;
109 lercInfo.nRows = lerc2Info.nRows;
110 lercInfo.numValidPixel = lerc2Info.numValidPixel; // for 1st band
111 lercInfo.blobSize = (unsigned int)lerc2Info.blobSize; // blob size per band is in [0 .. 2 GB]
112 lercInfo.dt = (DataType)lerc2Info.dt;
113 lercInfo.zMin = lerc2Info.zMin;
114 lercInfo.zMax = lerc2Info.zMax;
115 lercInfo.maxZError = lerc2Info.maxZError;
116 lercInfo.nUsesNoDataValue = lerc2Info.bPassNoDataValues ? 1 : 0;
117
118 bool bTryNextBlob = (lerc2Info.version <= 5) || (lerc2Info.nBlobsMore > 0);
119
120 if (bHasMask || lercInfo.numValidPixel == 0)
121 nMasks = 1;
122
123 if (pMins && pMaxs)
124 {
125 ErrCode errCode = GetRanges(pLercBlob, numBytesBlob, 0, lerc2Info, pMins, pMaxs, nElem); // band 0
126 if (errCode != ErrCode::Ok)
127 return errCode;
128 }
129
130 lercInfo.nBands = 1;
131
132 if (lercInfo.blobSize > numBytesBlob) // truncated blob, we won't be able to read this band
133 return ErrCode::Failed;
134
135 struct Lerc2::HeaderInfo hdInfo;
136 while (bTryNextBlob && Lerc2::GetHeaderInfo(pLercBlob + lercInfo.blobSize, numBytesBlob - lercInfo.blobSize, hdInfo, bHasMask))
137 {
138 if (hdInfo.nDepth != lercInfo.nDepth
139 || hdInfo.nCols != lercInfo.nCols
140 || hdInfo.nRows != lercInfo.nRows
141 || (int)hdInfo.dt != (int)lercInfo.dt
142 || hdInfo.blobSize < 0)
143 {
144 return ErrCode::Failed;
145 }
146
147 bTryNextBlob = (hdInfo.version <= 5) || (hdInfo.nBlobsMore > 0);
148
149 if (hdInfo.bPassNoDataValues)
150 lercInfo.nUsesNoDataValue++;
151
152 if (bHasMask || hdInfo.numValidPixel != lercInfo.numValidPixel) // support mask per band
153 nMasks = 2;
154
155 if ((size_t)lercInfo.blobSize > (size_t)UINT_MAX - hdInfo.blobSize) // guard against overflow
156 return ErrCode::Failed;
157
158 if ((size_t)lercInfo.blobSize + hdInfo.blobSize > (size_t)numBytesBlob) // truncated blob, we won't be able to read this band
159 return ErrCode::Failed;
160
161 lercInfo.zMin = min(lercInfo.zMin, hdInfo.zMin);
162 lercInfo.zMax = max(lercInfo.zMax, hdInfo.zMax);
163 lercInfo.maxZError = max(lercInfo.maxZError, hdInfo.maxZError); // with the new bitplane compression, maxZError can vary between bands
164
165 if (pMins && pMaxs)
166 {
167 ErrCode errCode = GetRanges(pLercBlob + lercInfo.blobSize, numBytesBlob - lercInfo.blobSize, lercInfo.nBands, hdInfo, pMins, pMaxs, nElem);
168 if (errCode != ErrCode::Ok)
169 return errCode;
170 }
171
172 lercInfo.blobSize += hdInfo.blobSize;
173 lercInfo.nBands++;
174 }
175
176 lercInfo.nMasks = nMasks > 1 ? lercInfo.nBands : nMasks;
177
178 if (lercInfo.nUsesNoDataValue > 0)
179 lercInfo.nUsesNoDataValue = lercInfo.nBands; // if there is any noData used in any band, allow for different noData per band
180
181 return ErrCode::Ok;
182 }
183
184
185 #ifdef HAVE_LERC1_DECODE
186 // only if not Lerc2, try legacy Lerc1
187 unsigned int numBytesHeaderBand0 = CntZImage::computeNumBytesNeededToReadHeader(false);
188 unsigned int numBytesHeaderBand1 = CntZImage::computeNumBytesNeededToReadHeader(true);
189 const Byte* pByte = pLercBlob;
190
191 lercInfo.zMin = FLT_MAX;
192 lercInfo.zMax = -FLT_MAX;
193
194 CntZImage cntZImg;
195 if (numBytesHeaderBand0 <= numBytesBlob && cntZImg.read(&pByte, pLercBlob + numBytesBlob, 1e12, true)) // read just the header
196 {
197 size_t nBytesRead = pByte - pLercBlob;
198 size_t nBytesNeeded = 10 + 4 * sizeof(int) + 1 * sizeof(double);
199
200 if (nBytesRead < nBytesNeeded)
201 return ErrCode::Failed;
202
203 const Byte* ptr = pLercBlob;
204 ptr += 10 + 2 * sizeof(int);
205
206 int height(0), width(0);
207 memcpy(&height, ptr, sizeof(int)); ptr += sizeof(int);
208 memcpy(&width, ptr, sizeof(int)); ptr += sizeof(int);
209 double maxZErrorInFile(0);
210 memcpy(&maxZErrorInFile, ptr, sizeof(double));
211
212 if (height < 0 || width < 0 || height > 40000 || width > 40000) // guard against bogus numbers; size limitation for old Lerc1
213 return ErrCode::Failed;
214
215 if (sizeof(CntZ) * height * width > (size_t)INT_MAX)
216 return ErrCode::Failed;
217
218 lercInfo.nDepth = 1;
219 lercInfo.nCols = width;
220 lercInfo.nRows = height;
221 lercInfo.dt = Lerc::DT_Float;
222 lercInfo.maxZError = maxZErrorInFile;
223
224 pByte = pLercBlob;
225 bool onlyZPart = false;
226
227 while (lercInfo.blobSize + numBytesHeaderBand1 < numBytesBlob) // means there could be another band
228 {
229 if (!cntZImg.read(&pByte, pLercBlob + numBytesBlob, 1e12, false, onlyZPart))
230 return (lercInfo.nBands > 0) ? ErrCode::Ok : ErrCode::Failed; // no other band, we are done
231
232 onlyZPart = true;
233 lercInfo.blobSize = (int)(pByte - pLercBlob);
234
235 // now that we have decoded it, we can go the extra mile and collect some extra info
236 int numValidPixels = 0;
237 float zMin = FLT_MAX;
238 float zMax = -FLT_MAX;
239
240 for (int i = 0; i < height; i++)
241 {
242 for (int j = 0; j < width; j++)
243 if (cntZImg(i, j).cnt > 0)
244 {
245 numValidPixels++;
246 float z = cntZImg(i, j).z;
247 zMax = max(zMax, z);
248 zMin = min(zMin, z);
249 }
250 }
251
252 lercInfo.numValidPixel = numValidPixels;
253 lercInfo.zMin = std::min(lercInfo.zMin, (double)zMin);
254 lercInfo.zMax = std::max(lercInfo.zMax, (double)zMax);
255 lercInfo.nMasks = numValidPixels < width * height ? 1 : 0;
256
257 if (pMins && pMaxs)
258 {
259 pMins[lercInfo.nBands] = zMin;
260 pMaxs[lercInfo.nBands] = zMax;
261 }
262
263 lercInfo.nBands++;
264 }
265
266 return ErrCode::Ok;
267 }
268 #endif
269
270 return ErrCode::Failed;
271 }
272
273 // -------------------------------------------------------------------------- ;
274
275 ErrCode Lerc::Decode(const Byte* pLercBlob, unsigned int numBytesBlob, int nMasks, Byte* pValidBytes,
276 int nDepth, int nCols, int nRows, int nBands, DataType dt, void* pData, unsigned char* pUsesNoData, double* noDataValues)
277 {
278 #define LERC_ARG_3 pLercBlob, numBytesBlob, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, pUsesNoData, noDataValues
279
280 switch (dt)
281 {
282 case DT_Char: return DecodeTempl((signed char*)pData, LERC_ARG_3);
283 case DT_Byte: return DecodeTempl((Byte*)pData, LERC_ARG_3);
284 case DT_Short: return DecodeTempl((short*)pData, LERC_ARG_3);
285 case DT_UShort: return DecodeTempl((unsigned short*)pData, LERC_ARG_3);
286 case DT_Int: return DecodeTempl((int*)pData, LERC_ARG_3);
287 case DT_UInt: return DecodeTempl((unsigned int*)pData, LERC_ARG_3);
288 case DT_Float: return DecodeTempl((float*)pData, LERC_ARG_3);
289 case DT_Double: return DecodeTempl((double*)pData, LERC_ARG_3);
290
291 default:
292 return ErrCode::WrongParam;
293 }
294
295 #undef LERC_ARG_3
296 }
297
298 // -------------------------------------------------------------------------- ;
299
300 ErrCode Lerc::ConvertToDouble(const void* pDataIn, DataType dt, size_t nDataValues, double* pDataOut)
301 {
302 switch (dt)
303 {
304 case DT_Char: return ConvertToDoubleTempl((const signed char*)pDataIn, nDataValues, pDataOut);
305 case DT_Byte: return ConvertToDoubleTempl((const Byte*)pDataIn, nDataValues, pDataOut);
306 case DT_Short: return ConvertToDoubleTempl((const short*)pDataIn, nDataValues, pDataOut);
307 case DT_UShort: return ConvertToDoubleTempl((const unsigned short*)pDataIn, nDataValues, pDataOut);
308 case DT_Int: return ConvertToDoubleTempl((const int*)pDataIn, nDataValues, pDataOut);
309 case DT_UInt: return ConvertToDoubleTempl((const unsigned int*)pDataIn, nDataValues, pDataOut);
310 case DT_Float: return ConvertToDoubleTempl((const float*)pDataIn, nDataValues, pDataOut);
311 //case DT_Double: no convert double to double
312
313 default:
314 return ErrCode::WrongParam;
315 }
316 }
317
318 // -------------------------------------------------------------------------- ;
319 // -------------------------------------------------------------------------- ;
320
321 template<class T>
322 ErrCode Lerc::ComputeCompressedSizeTempl(const T* pData, int version, int nDepth, int nCols, int nRows,
323 int nBands, int nMasks, const Byte* pValidBytes, double maxZErr, unsigned int& numBytesNeeded,
324 const unsigned char* pUsesNoData, const double* noDataValues)
325 {
326 numBytesNeeded = 0;
327
328 if (!pData || nDepth <= 0 || nCols <= 0 || nRows <= 0 || nBands <= 0 || maxZErr < 0)
329 return ErrCode::WrongParam;
330
331 if (!(nMasks == 0 || nMasks == 1 || nMasks == nBands) || (nMasks > 0 && !pValidBytes))
332 return ErrCode::WrongParam;
333
334 if (!CheckDimensions(nDepth, nCols, nRows, sizeof(T)))
335 return ErrCode::DimensionsTooLarge;
336
337 unsigned int numBytesWritten = 0;
338
339 if (version >= 0 && version <= 5)
340 {
341 if (pUsesNoData)
342 for (int i = 0; i < nBands; i++)
343 if (pUsesNoData[i])
344 return ErrCode::WrongParam;
345
346 return EncodeInternal_v5(pData, version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr,
347 numBytesNeeded, nullptr, 0, numBytesWritten);
348 }
349 else
350 {
351 return EncodeInternal(pData, version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr,
352 numBytesNeeded, nullptr, 0, numBytesWritten, pUsesNoData, noDataValues);
353 }
354 }
355
356 // -------------------------------------------------------------------------- ;
357
358 template<class T>
359 ErrCode Lerc::EncodeTempl(const T* pData, int version, int nDepth, int nCols, int nRows, int nBands,
360 int nMasks, const Byte* pValidBytes, double maxZErr, Byte* pBuffer, unsigned int numBytesBuffer,
361 unsigned int& numBytesWritten, const unsigned char* pUsesNoData, const double* noDataValues)
362 {
363 numBytesWritten = 0;
364
365 if (!pData || nDepth <= 0 || nCols <= 0 || nRows <= 0 || nBands <= 0 || maxZErr < 0 || !pBuffer || !numBytesBuffer)
366 return ErrCode::WrongParam;
367
368 if (!(nMasks == 0 || nMasks == 1 || nMasks == nBands) || (nMasks > 0 && !pValidBytes))
369 return ErrCode::WrongParam;
370
371 if (!CheckDimensions(nDepth, nCols, nRows, sizeof(T)))
372 return ErrCode::DimensionsTooLarge;
373
374 memset(pBuffer, 0, (size_t)numBytesBuffer);
375
376 unsigned int numBytesNeeded = 0;
377
378 if (version >= 0 && version <= 5)
379 {
380 if (pUsesNoData)
381 for (int i = 0; i < nBands; i++)
382 if (pUsesNoData[i])
383 return ErrCode::WrongParam;
384
385 return EncodeInternal_v5(pData, version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr,
386 numBytesNeeded, pBuffer, numBytesBuffer, numBytesWritten);
387 }
388 else
389 {
390 return EncodeInternal(pData, version, nDepth, nCols, nRows, nBands, nMasks, pValidBytes, maxZErr,
391 numBytesNeeded, pBuffer, numBytesBuffer, numBytesWritten, pUsesNoData, noDataValues);
392 }
393 }
394
395 // -------------------------------------------------------------------------- ;
396
397 template<class T>
398 ErrCode Lerc::DecodeTempl(T* pData, const Byte* pLercBlob, unsigned int numBytesBlob,
399 int nDepth, int nCols, int nRows, int nBands, int nMasks, Byte* pValidBytes,
400 unsigned char* pUsesNoData, double* noDataValues)
401 {
402 if (!pData || nDepth <= 0 || nCols <= 0 || nRows <= 0 || nBands <= 0 || !pLercBlob || !numBytesBlob)
403 return ErrCode::WrongParam;
404
405 if (!(nMasks == 0 || nMasks == 1 || nMasks == nBands) || (nMasks > 0 && !pValidBytes))
406 return ErrCode::WrongParam;
407
408 if (!CheckDimensions(nDepth, nCols, nRows, sizeof(T)))
409 return ErrCode::DimensionsTooLarge;
410
411 const Byte* pByte = pLercBlob;
412 Lerc2::HeaderInfo hdInfo;
413 bool bHasMask = false;
414
415 if (Lerc2::GetHeaderInfo(pByte, numBytesBlob, hdInfo, bHasMask) && hdInfo.version >= 1) // if Lerc2
416 {
417 LercInfo lercInfo;
418 ErrCode errCode = GetLercInfo(pLercBlob, numBytesBlob, lercInfo); // fast for Lerc2, does most checks
419 if (errCode != ErrCode::Ok)
420 return errCode;
421
422 // caller must provide enough space for the masks that are there (e.g., if they differ between bands)
423 if (nMasks < lercInfo.nMasks) // 0, 1, or nBands
424 return ErrCode::WrongParam;
425
426 // caller cannot ask for more bands than are there
427 if (nBands > lercInfo.nBands)
428 return ErrCode::WrongParam;
429
430 // if Lerc blob has noData values not covered by the mask, caller must get it (make sure caller cannot miss it)
431 if (lercInfo.nUsesNoDataValue && nDepth > 1)
432 {
433 if (!pUsesNoData || !noDataValues)
434 return ErrCode::HasNoData;
435
436 try
437 {
438 memset(pUsesNoData, 0, nBands);
439 memset(noDataValues, 0, nBands * sizeof(double));
440 }
441 catch (...)
442 {
443 return ErrCode::HasNoData;
444 }
445 }
446
447 size_t nBytesRemaining = numBytesBlob;
448 Lerc2 lerc2;
449 BitMask bitMask;
450
451 for (int iBand = 0; iBand < nBands; iBand++)
452 {
453 if (((size_t)(pByte - pLercBlob) < numBytesBlob) && Lerc2::GetHeaderInfo(pByte, nBytesRemaining, hdInfo, bHasMask))
454 {
455 if (hdInfo.nDepth != nDepth || hdInfo.nCols != nCols || hdInfo.nRows != nRows || hdInfo.blobSize < 0)
456 return ErrCode::Failed;
457
458 if ((pByte - pLercBlob) + (size_t)hdInfo.blobSize > numBytesBlob) // corrupted blob
459 return ErrCode::Failed;
460
461 size_t nPix = (size_t)iBand * nRows * nCols;
462 T* arr = pData + nPix * nDepth;
463
464 bool bGetMask = iBand < nMasks;
465
466 if (bGetMask && !bitMask.SetSize(nCols, nRows))
467 return ErrCode::Failed;
468
469 if (!lerc2.Decode(&pByte, nBytesRemaining, arr, bGetMask ? bitMask.Bits() : nullptr))
470 return ErrCode::Failed;
471
472 if (lercInfo.nUsesNoDataValue && nDepth > 1)
473 {
474 pUsesNoData[iBand] = hdInfo.bPassNoDataValues ? 1 : 0;
475 noDataValues[iBand] = hdInfo.noDataValOrig;
476
477 if (hdInfo.bPassNoDataValues && !RemapNoData(arr, bitMask, hdInfo))
478 return ErrCode::Failed;
479 }
480
481 if (bGetMask && !Convert(bitMask, pValidBytes + nPix))
482 return ErrCode::Failed;
483 }
484 } // iBand
485 } // Lerc2
486
487 else // might be old Lerc1
488 {
489 #ifdef HAVE_LERC1_DECODE
490 unsigned int numBytesHeaderBand0 = CntZImage::computeNumBytesNeededToReadHeader(false);
491 unsigned int numBytesHeaderBand1 = CntZImage::computeNumBytesNeededToReadHeader(true);
492 const Byte* pByte1 = pLercBlob;
493 CntZImage zImg;
494
495 for (int iBand = 0; iBand < nBands; iBand++)
496 {
497 unsigned int numBytesHeader = iBand == 0 ? numBytesHeaderBand0 : numBytesHeaderBand1;
498 if ((size_t)(pByte1 - pLercBlob) + numBytesHeader > numBytesBlob) // corrupted blob or wrong nBands
499 return ErrCode::Failed;
500
501 bool onlyZPart = iBand > 0;
502 if (!zImg.read(&pByte1, pLercBlob + numBytesBlob, 1e12, false, onlyZPart))
503 return ErrCode::Failed;
504
505 if (zImg.getWidth() != nCols || zImg.getHeight() != nRows)
506 return ErrCode::Failed;
507
508 size_t nPix = (size_t)iBand * nRows * nCols;
509 T* arr = pData + nPix;
510 Byte* pDst = iBand < nMasks ? pValidBytes + nPix : nullptr;
511
512 if (!Convert(zImg, arr, pDst, iBand == 0))
513 return ErrCode::Failed;
514 }
515 #else
516 return ErrCode::Failed;
517 #endif
518 }
519
520 return ErrCode::Ok;
521 }
522
523 // -------------------------------------------------------------------------- ;
524 // -------------------------------------------------------------------------- ;
525
526 template<class T>
527 ErrCode Lerc::EncodeInternal_v5(const T* pData, int version, int nDepth, int nCols, int nRows, int nBands,
528 int nMasks, const Byte* pValidBytes, double maxZErr, unsigned int& numBytesNeeded,
529 Byte* pBuffer, unsigned int numBytesBuffer, unsigned int& numBytesWritten)
530 {
531 numBytesNeeded = 0;
532 numBytesWritten = 0;
533
534 Lerc2 lerc2;
535 if (version >= 0 && !lerc2.SetEncoderToOldVersion(version))
536 return ErrCode::WrongParam;
537
538 Byte* pDst = pBuffer;
539
540 const size_t nPix = (size_t)nCols * nRows;
541 const size_t nElem = nPix * nDepth;
542
543 const Byte* pPrevByteMask = nullptr;
544 vector<T> dataBuffer;
545 vector<Byte> maskBuffer, prevMaskBuffer;
546 BitMask bitMask;
547
548 // loop over the bands
549 for (int iBand = 0; iBand < nBands; iBand++)
550 {
551 bool bEncMsk = (iBand == 0);
552
553 // using the proper section of valid bytes, check this band for NaN
554 const T* arr = pData + nElem * iBand;
555 const Byte* pByteMask = (nMasks > 0) ? (pValidBytes + ((nMasks > 1) ? nPix * iBand : 0)) : nullptr;
556
557 ErrCode errCode = CheckForNaN(arr, nDepth, nCols, nRows, pByteMask);
558 if (errCode != ErrCode::Ok && errCode != ErrCode::NaN)
559 return errCode;
560
561 if (errCode == ErrCode::NaN) // found NaN values
562 {
563 if (!Resize(dataBuffer, nElem) || !Resize(maskBuffer, nPix))
564 return ErrCode::Failed;
565
566 memcpy(&dataBuffer[0], arr, nElem * sizeof(T));
567 pByteMask ? memcpy(&maskBuffer[0], pByteMask, nPix) : memset(&maskBuffer[0], 1, nPix);
568
569 if (!ReplaceNaNValues(dataBuffer, maskBuffer, nDepth, nCols, nRows))
570 return ErrCode::Failed;
571
572 if (iBand > 0 && MasksDiffer(&maskBuffer[0], pPrevByteMask, nPix))
573 bEncMsk = true;
574
575 if (iBand < nBands - 1)
576 {
577 // keep current mask as new previous band mask
578 prevMaskBuffer = maskBuffer;
579 pPrevByteMask = &prevMaskBuffer[0];
580 }
581
582 arr = &dataBuffer[0];
583 pByteMask = &maskBuffer[0];
584 }
585
586 else // no NaN in this band, the common case
587 {
588 if (iBand > 0 && MasksDiffer(pByteMask, pPrevByteMask, nPix))
589 bEncMsk = true;
590
591 pPrevByteMask = pByteMask;
592 }
593
594 if (bEncMsk)
595 {
596 if (pByteMask && !Convert(pByteMask, nCols, nRows, bitMask))
597 return ErrCode::Failed;
598
599 if (!lerc2.Set(nDepth, nCols, nRows, pByteMask ? bitMask.Bits() : nullptr))
600 return ErrCode::Failed;
601 }
602
603 unsigned int nBytes = lerc2.ComputeNumBytesNeededToWrite(arr, maxZErr, bEncMsk);
604 if (nBytes <= 0)
605 return ErrCode::Failed;
606
607 if ((size_t)numBytesNeeded + nBytes > (size_t)UINT_MAX) // keep total blob size (over all bands) <= 4 GB
608 return ErrCode::DimensionsTooLarge;
609
610 numBytesNeeded += nBytes;
611
612 if (pBuffer)
613 {
614 if ((size_t)(pDst - pBuffer) + nBytes > numBytesBuffer) // check we have enough space left
615 return ErrCode::BufferTooSmall;
616
617 if (!lerc2.Encode(arr, &pDst))
618 return ErrCode::Failed;
619 }
620 } // iBand
621
622 numBytesWritten = (unsigned int)(pDst - pBuffer);
623 return ErrCode::Ok;
624 }
625
626 // -------------------------------------------------------------------------- ;
627
628 template<class T>
629 ErrCode Lerc::EncodeInternal(const T* pData, int version, int nDepth, int nCols, int nRows, int nBands,
630 int nMasks, const Byte* pValidBytes, double maxZErr, unsigned int& numBytesNeeded,
631 Byte* pBuffer, unsigned int numBytesBuffer, unsigned int& numBytesWritten,
632 const unsigned char* pUsesNoData, const double* noDataValues)
633 {
634 numBytesNeeded = 0;
635 numBytesWritten = 0;
636
637 if (version >= 0 && version <= 5)
638 return ErrCode::WrongParam;
639
640 Lerc2 lerc2;
641
642 #ifdef ENCODE_VERIFY
643 Lerc2 lerc2Verify;
644 #endif
645
646 if (version >= 0 && !lerc2.SetEncoderToOldVersion(version))
647 return ErrCode::WrongParam;
648
649 if (pUsesNoData && !noDataValues)
650 for (int i = 0; i < nBands; i++)
651 if (pUsesNoData[i])
652 return ErrCode::WrongParam;
653
654 Byte* pDst = pBuffer;
655
656 const size_t nPix = (size_t)nCols * nRows;
657 const size_t nElem = nPix * nDepth;
658
659 const Byte* pPrevByteMask = nullptr;
660 vector<T> dataBuffer;
661 vector<Byte> maskBuffer, prevMaskBuffer;
662 BitMask bitMask;
663
664 // allocate buffer for 1 band
665 if (!Resize(dataBuffer, nElem) || !Resize(maskBuffer, nPix))
666 return ErrCode::Failed;
667
668 bool bIsFltOrDbl = (typeid(T) == typeid(float) || typeid(T) == typeid(double));
669 bool bAnyMaskModified = false;
670 ErrCode errCode = ErrCode::Ok;
671
672 // loop over the bands
673 for (int iBand = 0; iBand < nBands; iBand++)
674 {
675 bool bEncMsk = (iBand == 0);
676
677 // get the data and mask for this band
678 const T* arrOrig = pData + nElem * iBand;
679 const Byte* pByteMaskOrig = (nMasks > 0) ? (pValidBytes + ((nMasks > 1) ? nPix * iBand : 0)) : nullptr;
680
681 // copy to buffer so we can modify it
682 memcpy(&dataBuffer[0], arrOrig, nElem * sizeof(T));
683 pByteMaskOrig ? memcpy(&maskBuffer[0], pByteMaskOrig, nPix) : memset(&maskBuffer[0], 1, nPix);
684
685 double maxZErrL = maxZErr; // maxZErrL can get modified in the filter functions below
686
687 bool bPassNoDataValue = (pUsesNoData && (pUsesNoData[iBand] > 0));
688 const double noDataOrig = bPassNoDataValue ? noDataValues[iBand] : 0;
689
690 double noDataL = noDataOrig; // noDataL can get modified in the filter functions below
691
692 bool bIsFltDblAllInt = false; // are the flt numbers all integer really? Double can be used for int numbers beyond 32 bit range
693 bool bModifiedMask = false; // can turn true if NaN or noData found at valid pixels
694 bool bNeedNoData = false; // can only turn true for nDepth > 1, and mix of valid and invalid values at the same pixel (special case)
695 errCode = ErrCode::Ok;
696
697 double minVal(+1), maxVal(-1);
698 lerc2.ClearMinMax();
699
700 if (bIsFltOrDbl) // if flt type, filter out NaN and / or noData values and update the mask if possible
701 {
702 errCode = FilterNoDataAndNaN(dataBuffer, maskBuffer, nDepth, nCols, nRows, maxZErrL, bPassNoDataValue, noDataL,
703 bModifiedMask, bNeedNoData, bIsFltDblAllInt, minVal, maxVal);
704 }
705 else if (bPassNoDataValue) // if int type (no NaN), and no noData value specified, nothing to do
706 {
707 errCode = FilterNoData(dataBuffer, maskBuffer, nDepth, nCols, nRows, maxZErrL, bPassNoDataValue, noDataL,
708 bModifiedMask, bNeedNoData, minVal, maxVal);
709 }
710
711 if (errCode != ErrCode::Ok)
712 return errCode;
713
714 if (bModifiedMask)
715 bAnyMaskModified = true;
716
717 bool bCompareMasks = (nMasks > 1) || bAnyMaskModified;
718
719 if (bCompareMasks && (iBand > 0) && MasksDiffer(&maskBuffer[0], pPrevByteMask, nPix))
720 bEncMsk = true;
721
722 if (nBands > 1 && iBand < nBands - 1)
723 {
724 // keep current mask as new previous band mask
725 prevMaskBuffer = maskBuffer;
726 pPrevByteMask = &prevMaskBuffer[0];
727 }
728
729 const T* arrL = &dataBuffer[0];
730 const Byte* pByteMaskL = &maskBuffer[0];
731
732 if (bEncMsk)
733 {
734 bool bAllValid = !memchr(pByteMaskL, 0, nPix);
735
736 if (!bAllValid && !Convert(pByteMaskL, nCols, nRows, bitMask))
737 return ErrCode::Failed;
738
739 if (!lerc2.Set(nDepth, nCols, nRows, !bAllValid ? bitMask.Bits() : nullptr))
740 return ErrCode::Failed;
741 }
742
743 // set other flags
744 if ( !lerc2.SetNoDataValues(bNeedNoData, noDataL, noDataOrig)
745 || !lerc2.SetNumBlobsMoreToCome(nBands - 1 - iBand)
746 || !lerc2.SetIsAllInt(bIsFltDblAllInt))
747 return ErrCode::Failed;
748
749 if (nDepth == 1 && (maxVal >= minVal)
750 && !lerc2.SetMinMax(nDepth, minVal, maxVal))
751 return ErrCode::Failed;
752
753 unsigned int nBytes = lerc2.ComputeNumBytesNeededToWrite(arrL, maxZErrL, bEncMsk);
754 if (nBytes <= 0)
755 return ErrCode::Failed;
756
757 if ((size_t)numBytesNeeded + nBytes > (size_t)UINT_MAX) // keep total blob size (over all bands) <= 4 GB
758 return ErrCode::DimensionsTooLarge;
759
760 numBytesNeeded += nBytes;
761
762 if (pBuffer)
763 {
764 if ((size_t)(pDst - pBuffer) + nBytes > numBytesBuffer) // check we have enough space left
765 return ErrCode::BufferTooSmall;
766
767 #ifdef ENCODE_VERIFY
768 const Byte* pDst0 = pDst;
769 #endif
770
771 if (!lerc2.Encode(arrL, &pDst))
772 return ErrCode::Failed;
773
774 #ifdef ENCODE_VERIFY
775 size_t blobSize = pDst - pDst0;
776
777 if (!DecodeAndCompareToInput(pDst0, blobSize, maxZErrL, lerc2Verify, arrL, pByteMaskL,
778 arrOrig, pByteMaskOrig, bPassNoDataValue, noDataOrig, bModifiedMask))
779 {
780 return ErrCode::Failed;
781 }
782 #endif
783
784 }
785 } // iBand
786
787 numBytesWritten = (unsigned int)(pDst - pBuffer);
788 return ErrCode::Ok;
789 }
790
791 // -------------------------------------------------------------------------- ;
792
793 #ifdef HAVE_LERC1_DECODE
794 template<class T>
795 bool Lerc::Convert(const CntZImage& zImg, T* arr, Byte* pByteMask, bool bMustFillMask)
796 {
797 if (!arr || !zImg.getSize())
798 return false;
799
800 const bool fltPnt = (typeid(*arr) == typeid(double)) || (typeid(*arr) == typeid(float));
801
802 int h = zImg.getHeight();
803 int w = zImg.getWidth();
804
805 const CntZ* srcPtr = zImg.getData();
806 T* dstPtr = arr;
807 int num = w * h;
808
809 if (pByteMask)
810 {
811 memset(pByteMask, 0, num);
812
813 for (int k = 0; k < num; k++)
814 {
815 if (srcPtr->cnt > 0)
816 {
817 *dstPtr = fltPnt ? (T)srcPtr->z : (T)floor(srcPtr->z + 0.5);
818 pByteMask[k] = 1;
819 }
820
821 srcPtr++;
822 dstPtr++;
823 }
824 }
825 else
826 {
827 for (int k = 0; k < num; k++)
828 {
829 if (srcPtr->cnt > 0)
830 {
831 *dstPtr = fltPnt ? (T)srcPtr->z : (T)floor(srcPtr->z + 0.5);
832 }
833 else if (bMustFillMask)
834 return false;
835
836 srcPtr++;
837 dstPtr++;
838 }
839 }
840
841 return true;
842 }
843 #endif
844
845 // -------------------------------------------------------------------------- ;
846
847 template<class T>
848 ErrCode Lerc::ConvertToDoubleTempl(const T* pDataIn, size_t nDataValues, double* pDataOut)
849 {
850 if (!pDataIn || !nDataValues || !pDataOut)
851 return ErrCode::WrongParam;
852
853 for (size_t k = 0; k < nDataValues; k++)
854 pDataOut[k] = pDataIn[k];
855
856 return ErrCode::Ok;
857 }
858
859 // -------------------------------------------------------------------------- ;
860
861 template<class T> ErrCode Lerc::CheckForNaN(const T* arr, int nDepth, int nCols, int nRows, const Byte* pByteMask)
862 {
863 if (!arr || nDepth <= 0 || nCols <= 0 || nRows <= 0)
864 return ErrCode::WrongParam;
865
866 if (typeid(T) != typeid(double) && typeid(T) != typeid(float))
867 return ErrCode::Ok;
868
869 for (size_t k = 0, i = 0; i < (size_t)nRows; i++)
870 {
871 bool bFoundNaN = false;
872 const T* rowArr = &(arr[i * nCols * nDepth]);
873
874 if (!pByteMask) // all valid
875 {
876 size_t num = (size_t)nCols * nDepth;
877 for (size_t m = 0; m < num; m++)
878 if (std::isnan((double)rowArr[m]))
879 bFoundNaN = true;
880 }
881 else // not all valid
882 {
883 for (size_t n = 0, j = 0; j < (size_t)nCols; j++, k++, n += nDepth)
884 if (pByteMask[k])
885 {
886 for (int m = 0; m < nDepth; m++)
887 if (std::isnan((double)rowArr[n + m]))
888 bFoundNaN = true;
889 }
890 }
891
892 if (bFoundNaN)
893 return ErrCode::NaN;
894 }
895
896 return ErrCode::Ok;
897 }
898
899 // -------------------------------------------------------------------------- ;
900
901 template<class T> bool Lerc::ReplaceNaNValues(std::vector<T>& dataBuffer, std::vector<Byte>& maskBuffer, int nDepth, int nCols, int nRows)
902 {
903 if (nDepth <= 0 || nCols <= 0 || nRows <= 0 || dataBuffer.size() != (size_t)nDepth * nCols * nRows || maskBuffer.size() != (size_t)nCols * nRows)
904 return false;
905
906 T noDataValue = 0;
907 {
908 #if defined _WIN32
909 #pragma warning(disable: 4756) // would trigger build warning in linux
910 #endif
911
912 noDataValue = (T)((typeid(T) == typeid(float)) ? -FLT_MAX : -DBL_MAX);
913 }
914
915 for (size_t k = 0, i = 0; i < (size_t)nRows; i++)
916 {
917 T* rowArr = &(dataBuffer[i * nCols * nDepth]);
918
919 for (size_t n = 0, j = 0; j < (size_t)nCols; j++, k++, n += nDepth)
920 {
921 if (maskBuffer[k])
922 {
923 int cntNaN = 0;
924
925 for (int m = 0; m < nDepth; m++)
926 if (std::isnan((double)rowArr[n + m]))
927 {
928 cntNaN++;
929 rowArr[n + m] = noDataValue;
930 }
931
932 if (cntNaN == nDepth)
933 maskBuffer[k] = 0;
934 }
935 }
936 }
937
938 return true;
939 }
940
941 // -------------------------------------------------------------------------- ;
942
943 template<class T> bool Lerc::Resize(std::vector<T>& buffer, size_t nElem)
944 {
945 try
946 {
947 buffer.resize(nElem);
948 }
949 catch (...)
950 {
951 return false;
952 }
953
954 return (buffer.size() == nElem);
955 }
956
957 // -------------------------------------------------------------------------- ;
958
959 bool Lerc::Convert(const Byte* pByteMask, int nCols, int nRows, BitMask& bitMask)
960 {
961 if (!pByteMask || nCols <= 0 || nRows <= 0)
962 return false;
963
964 if (!bitMask.SetSize(nCols, nRows))
965 return false;
966
967 bitMask.SetAllValid();
968
969 for (int k = 0, i = 0; i < nRows; i++)
970 for (int j = 0; j < nCols; j++, k++)
971 if (!pByteMask[k])
972 bitMask.SetInvalid(k);
973
974 return true;
975 }
976
977 // -------------------------------------------------------------------------- ;
978
979 bool Lerc::Convert(const BitMask& bitMask, Byte* pByteMask)
980 {
981 int nCols = bitMask.GetWidth();
982 int nRows = bitMask.GetHeight();
983
984 if (nCols <= 0 || nRows <= 0 || !pByteMask)
985 return false;
986
987 memset(pByteMask, 0, (size_t)nCols * nRows);
988
989 for (int k = 0, i = 0; i < nRows; i++)
990 for (int j = 0; j < nCols; j++, k++)
991 if (bitMask.IsValid(k))
992 pByteMask[k] = 1;
993
994 return true;
995 }
996
997 // -------------------------------------------------------------------------- ;
998
999 bool Lerc::MasksDiffer(const Byte* p0, const Byte* p1, size_t n)
1000 {
1001 if (p0 == p1)
1002 return false;
1003
1004 if (!p0) // means all valid
1005 return memchr(p1, 0, n); // any invalid?
1006 else if (!p1)
1007 return memchr(p0, 0, n);
1008 else
1009 return memcmp(p0, p1, n);
1010 }
1011
1012 // -------------------------------------------------------------------------- ;
1013
1014 ErrCode Lerc::GetRanges(const Byte* pLercBlob, unsigned int numBytesBlob, int iBand,
1015 const struct Lerc2::HeaderInfo& lerc2Info, double* pMins, double* pMaxs, size_t nElem)
1016 {
1017 const int nDepth = lerc2Info.nDepth;
1018
1019 if (nDepth <= 0 || iBand < 0 || !pMins || !pMaxs)
1020 return ErrCode::WrongParam;
1021
1022 if (nElem < ((size_t)iBand + 1) * (size_t)nDepth)
1023 return ErrCode::BufferTooSmall;
1024
1025 if (nDepth == 1)
1026 {
1027 pMins[iBand] = lerc2Info.zMin;
1028 pMaxs[iBand] = lerc2Info.zMax;
1029 }
1030 else
1031 {
1032 if (lerc2Info.bPassNoDataValues) // for nDepth > 1, and mix of valid and invalid values at same pixel, better fail
1033 return ErrCode::HasNoData; // than return min or max values that contain noData (to be fixed in next codec version)
1034
1035 // read header, mask, ranges, and copy them out
1036 Lerc2 lerc2;
1037 if (!lerc2.GetRanges(pLercBlob, numBytesBlob, &pMins[iBand * nDepth], &pMaxs[iBand * nDepth]))
1038 return ErrCode::Failed;
1039 }
1040
1041 return ErrCode::Ok;
1042 }
1043
1044 // -------------------------------------------------------------------------- ;
1045
1046 template<class T>
1047 bool Lerc::RemapNoData(T* data, const BitMask& bitMask, const struct Lerc2::HeaderInfo& lerc2Info)
1048 {
1049 int nCols = lerc2Info.nCols;
1050 int nRows = lerc2Info.nRows;
1051 int nDepth = lerc2Info.nDepth;
1052
1053 if (!data || nCols <= 0 || nRows <= 0 || nDepth <= 0)
1054 return false;
1055
1056 const T noDataOld = (T)lerc2Info.noDataVal;
1057 const T noDataNew = (T)lerc2Info.noDataValOrig;
1058
1059 if (noDataNew != noDataOld)
1060 {
1061 bool bUseMask = (bitMask.GetWidth() == nCols) && (bitMask.GetHeight() == nRows);
1062
1063 for (long k = 0, i = 0; i < nRows; i++)
1064 {
1065 T* rowArr = &(data[i * nCols * nDepth]);
1066
1067 for (long n = 0, j = 0; j < nCols; j++, k++, n += nDepth)
1068 if (!bUseMask || bitMask.IsValid(k))
1069 for (long m = 0; m < nDepth; m++)
1070 if (rowArr[n + m] == noDataOld)
1071 rowArr[n + m] = noDataNew;
1072 }
1073 }
1074
1075 return true;
1076 }
1077
1078 // -------------------------------------------------------------------------- ;
1079
1080 template<class T>
1081 bool Lerc::DecodeAndCompareToInput(const Byte* pLercBlob, size_t blobSize, double maxZErr, Lerc2& lerc2Verify,
1082 const T* pData, const Byte* pByteMask, const T* pDataOrig, const Byte* pByteMaskOrig,
1083 bool bInputHasNoData, double origNoDataA, bool bModifiedMask)
1084 {
1085 if (!pLercBlob || !pData || !pDataOrig)
1086 return false;
1087
1088 const Byte* bytePtr = pLercBlob;
1089 size_t nBytesRemaining = blobSize;
1090
1091 bool bHasMask(false);
1092 Lerc2::HeaderInfo hd;
1093 if (!Lerc2::GetHeaderInfo(bytePtr, nBytesRemaining, hd, bHasMask))
1094 return false;
1095
1096 std::vector<T> arrDec;
1097 try
1098 {
1099 arrDec.assign(hd.nRows * hd.nCols * hd.nDepth, 0);
1100 }
1101 catch (...)
1102 {
1103 return false;
1104 }
1105
1106 BitMask bitMaskDec;
1107 if (!bitMaskDec.SetSize(hd.nCols, hd.nRows))
1108 return false;
1109
1110 bitMaskDec.SetAllInvalid();
1111
1112 if (!lerc2Verify.Decode(&bytePtr, nBytesRemaining, &arrDec[0], bitMaskDec.Bits()))
1113 return false;
1114
1115 // compare decoded bit mask and data array against the input to lerc encode (as after that orig input had the noData value remapped, NaN removed, bit mask altered)
1116 {
1117 bool bHasMaskBug(false);
1118 double maxDelta = 0;
1119
1120 for (int k = 0, i = 0; i < hd.nRows; i++)
1121 for (int j = 0; j < hd.nCols; j++, k++)
1122 if (bitMaskDec.IsValid(k))
1123 {
1124 if (pByteMask && !pByteMask[k])
1125 bHasMaskBug = true;
1126
1127 for (int n = k * hd.nDepth, m = 0; m < hd.nDepth; m++, n++)
1128 {
1129 double d = fabs((double)arrDec[n] - (double)pData[n]);
1130 if (d > maxDelta)
1131 maxDelta = d;
1132 }
1133 }
1134 else if (!pByteMask || pByteMask[k])
1135 bHasMaskBug = true;
1136
1137 if (bHasMaskBug || maxDelta > maxZErr * 1.1) // consider float rounding errors
1138 return false;
1139 }
1140
1141 if (!bInputHasNoData && !bModifiedMask) // any NaN in the input means either modify the mask or replace it by noData value
1142 return true;
1143
1144 const bool bIsFltOrDbl = (typeid(T) == typeid(double) || typeid(T) == typeid(float));
1145 const bool bHaveNoDataVal = (hd.version >= 6 && hd.bPassNoDataValues && hd.nDepth > 1);
1146
1147 if (bHaveNoDataVal && hd.noDataValOrig != origNoDataA)
1148 return false;
1149
1150 if (bHaveNoDataVal && hd.noDataVal != hd.noDataValOrig)
1151 {
1152 // remap the noData value from internal to orig
1153 if (!RemapNoData(&arrDec[0], bitMaskDec, hd))
1154 return false;
1155 }
1156
1157 // compare the final result to orig bit mask and data array as it was handed to the Compress() function
1158 {
1159 T noDataOrig = (T)origNoDataA;
1160 double maxDelta = 0;
1161 bool bHasBug(false);
1162
1163 for (int k = 0, i = 0; i < hd.nRows; i++)
1164 for (int j = 0; j < hd.nCols; j++, k++)
1165 if (!pByteMaskOrig || pByteMaskOrig[k])
1166 {
1167 if (!bitMaskDec.IsValid(k)) // then the orig data values must be noData or NaN
1168 {
1169 for (int n = k * hd.nDepth, m = 0; m < hd.nDepth; m++, n++)
1170 {
1171 T zOrig = pDataOrig[n];
1172 bool bIsNoData = (bInputHasNoData && zOrig == noDataOrig) || (bIsFltOrDbl && std::isnan((double)zOrig));
1173
1174 if (!bIsNoData)
1175 bHasBug = true;
1176 }
1177 }
1178 else // valid pixel
1179 {
1180 for (int n = k * hd.nDepth, m = 0; m < hd.nDepth; m++, n++)
1181 {
1182 T zOrig = pDataOrig[n];
1183 T z = arrDec[n];
1184
1185 if (z == zOrig) // valid value or noData
1186 continue;
1187
1188 if (bIsFltOrDbl && std::isnan((double)zOrig))
1189 zOrig = noDataOrig;
1190
1191 if (bInputHasNoData && (z == noDataOrig || zOrig == noDataOrig) && (z != zOrig))
1192 bHasBug = true;
1193
1194 if (!bHaveNoDataVal || z != noDataOrig) // is valid
1195 {
1196 double d = fabs((double)z - (double)zOrig);
1197 if (d > maxDelta)
1198 maxDelta = d;
1199 }
1200 }
1201 }
1202 }
1203 else if (bitMaskDec.IsValid(k))
1204 bHasBug = true;
1205
1206 if (bHasBug || maxDelta > maxZErr * 1.1) // consider float rounding errors
1207 return false;
1208 }
1209
1210 return true;
1211 }
1212
1213 // -------------------------------------------------------------------------- ;
1214
1215 template<class T>
1216 bool Lerc::GetTypeRange(const T, std::pair<double, double>& range)
1217 {
1218 range.first = 0;
1219
1220 if (typeid(T) == typeid(Byte))
1221 range.second = UCHAR_MAX;
1222 else if (typeid(T) == typeid(unsigned short))
1223 range.second = USHRT_MAX;
1224 else if (typeid(T) == typeid(unsigned int) || typeid(T) == typeid(unsigned long))
1225 range.second = UINT_MAX;
1226
1227 else if (typeid(T) == typeid(signed char))
1228 range = std::pair<double, double>(CHAR_MIN, CHAR_MAX);
1229 else if (typeid(T) == typeid(short))
1230 range = std::pair<double, double>(SHRT_MIN, SHRT_MAX);
1231 else if (typeid(T) == typeid(int) || typeid(T) == typeid(long))
1232 range = std::pair<double, double>(INT_MIN, INT_MAX);
1233 else
1234 return false;
1235
1236 return true;
1237 }
1238
1239 // -------------------------------------------------------------------------- ;
1240
1241 template<class T>
1242 ErrCode Lerc::FilterNoData(std::vector<T>& dataBuffer, std::vector<Byte>& maskBuffer, int nDepth, int nCols, int nRows,
1243 double& maxZError, bool bPassNoDataValue, double& noDataValue, bool& bModifiedMask, bool& bNeedNoData,
1244 double& minValA, double& maxValA)
1245 {
1246 if (nDepth <= 0 || nCols <= 0 || nRows <= 0 || maxZError < 0)
1247 return ErrCode::WrongParam;
1248
1249 if ((dataBuffer.size() != (size_t)nDepth * nCols * nRows) || (maskBuffer.size() != (size_t)nCols * nRows))
1250 return ErrCode::Failed;
1251
1252 bModifiedMask = false;
1253 bNeedNoData = false;
1254
1255 if (!bPassNoDataValue) // nothing to do
1256 return ErrCode::Ok;
1257
1258 std::pair<double, double> typeRange;
1259 if (!GetTypeRange(dataBuffer[0], typeRange))
1260 return ErrCode::Failed;
1261
1262 if (noDataValue < typeRange.first || noDataValue > typeRange.second)
1263 return ErrCode::WrongParam;
1264
1265 T origNoData = (T)noDataValue;
1266
1267 double minVal = DBL_MAX;
1268 double maxVal = -DBL_MAX;
1269
1270 // check for noData in valid pixels
1271 for (int k = 0, i = 0; i < nRows; i++)
1272 {
1273 T* rowArr = &(dataBuffer[(size_t)i * nCols * nDepth]);
1274
1275 for (int n = 0, j = 0; j < nCols; j++, k++, n += nDepth)
1276 if (maskBuffer[k])
1277 {
1278 int cntInvalid = 0;
1279
1280 for (int m = 0; m < nDepth; m++)
1281 {
1282 T z = rowArr[n + m];
1283
1284 if (z == origNoData)
1285 cntInvalid++;
1286 else
1287 {
1288 if (z < minVal)
1289 minVal = z;
1290 if (z > maxVal)
1291 maxVal = z;
1292 }
1293 }
1294
1295 if (cntInvalid == nDepth)
1296 {
1297 maskBuffer[k] = 0;
1298 bModifiedMask = true;
1299 }
1300 else if (cntInvalid > 0) // found mix of valid and invalid values at the same pixel
1301 bNeedNoData = true;
1302 }
1303 }
1304
1305 double maxZErrL = (std::max)(0.5, floor(maxZError)); // same mapping for int types as in Lerc2.cpp
1306 double dist = floor(maxZErrL);
1307
1308 if (minVal == DBL_MAX && maxVal == -DBL_MAX) // if the tile has no valid data
1309 {
1310 minValA = maxValA = 0;
1311 maxZError = 0.5;
1312 return ErrCode::Ok;
1313 }
1314
1315 minValA = minVal;
1316 maxValA = maxVal;
1317
1318 // check the orig noData value is far enough away from the valid range
1319 if ((origNoData >= minVal - dist) && (origNoData <= maxVal + dist))
1320 {
1321 maxZError = 0.5; // fall back to int lossless
1322 return ErrCode::Ok;
1323 }
1324
1325 if (bNeedNoData)
1326 {
1327 double minDist = floor(maxZErrL) + 1;
1328 double remapVal = minVal - minDist;
1329 T newNoData = origNoData;
1330
1331 if (remapVal >= typeRange.first)
1332 {
1333 newNoData = (T)remapVal;
1334 }
1335 else
1336 {
1337 maxZErrL = 0.5; // repeat with int lossless
1338 remapVal = minVal - 1;
1339
1340 if (remapVal >= typeRange.first)
1341 {
1342 newNoData = (T)remapVal;
1343 }
1344 else
1345 {
1346 remapVal = maxVal + 1; // try to map closer to valid range from top
1347
1348 if ((remapVal <= typeRange.second) && (remapVal < origNoData))
1349 newNoData = (T)remapVal;
1350 }
1351 }
1352
1353 if (newNoData != origNoData)
1354 {
1355 for (int k = 0, i = 0; i < nRows; i++)
1356 {
1357 T* rowArr = &(dataBuffer[(size_t)i * nCols * nDepth]);
1358
1359 for (int n = 0, j = 0; j < nCols; j++, k++, n += nDepth)
1360 if (maskBuffer[k])
1361 for (int m = 0; m < nDepth; m++)
1362 if (rowArr[n + m] == origNoData)
1363 rowArr[n + m] = newNoData;
1364 }
1365
1366 noDataValue = newNoData;
1367 }
1368 }
1369
1370 if (maxZError != maxZErrL)
1371 maxZError = maxZErrL;
1372
1373 return ErrCode::Ok;
1374 }
1375
1376 // -------------------------------------------------------------------------- ;
1377
1378 template<class T>
1379 ErrCode Lerc::FilterNoDataAndNaN(std::vector<T>& dataBuffer, std::vector<Byte>& maskBuffer, int nDepth, int nCols, int nRows,
1380 double& maxZError, bool bPassNoDataValue, double& noDataValue, bool& bModifiedMask, bool& bNeedNoData, bool& bIsFltDblAllInt,
1381 double& minValA, double& maxValA)
1382 {
1383 if (nDepth <= 0 || nCols <= 0 || nRows <= 0 || maxZError < 0)
1384 return ErrCode::WrongParam;
1385
1386 if ((dataBuffer.size() != (size_t)nDepth * nCols * nRows) || (maskBuffer.size() != (size_t)nCols * nRows))
1387 return ErrCode::Failed;
1388
1389 if (typeid(T) != typeid(double) && typeid(T) != typeid(float)) // only for float or double
1390 return ErrCode::Failed;
1391
1392 bModifiedMask = false;
1393 bNeedNoData = false;
1394 bIsFltDblAllInt = false;
1395
1396 bool bHasNoDataValuesLeft = false;
1397 bool bIsFloat4 = (typeid(T) == typeid(float));
1398 bool bAllInt = true;
1399 bool bHasNaN = false;
1400
1401 T origNoData(0);
1402
1403 if (bPassNoDataValue)
1404 {
1405 if (bIsFloat4 && (noDataValue < -FLT_MAX || noDataValue > FLT_MAX))
1406 return ErrCode::WrongParam;
1407
1408 origNoData = (T)noDataValue;
1409 }
1410 else
1411 origNoData = (T)(bIsFloat4 ? -FLT_MAX : -DBL_MAX);
1412
1413 // only treat int values as int's if within this range, incl orig noData
1414 const double lowIntLimit = (double)(bIsFloat4 ? -((long)1 << 23) : -((int64_t)1 << 53));
1415 const double highIntLimit = (double)(bIsFloat4 ? ((long)1 << 23) : ((int64_t)1 << 53));
1416
1417 double minVal = DBL_MAX;
1418 double maxVal = -DBL_MAX;
1419
1420 // check for NaN or noData in valid pixels
1421 for (int k = 0, i = 0; i < nRows; i++)
1422 {
1423 T* rowArr = &(dataBuffer[(size_t)i * nCols * nDepth]);
1424
1425 for (int n = 0, j = 0; j < nCols; j++, k++, n += nDepth)
1426 if (maskBuffer[k])
1427 {
1428 int cntInvalidValues = 0;
1429
1430 for (int m = 0; m < nDepth; m++)
1431 {
1432 T& zVal = rowArr[n + m];
1433
1434 if (std::isnan((double)zVal))
1435 {
1436 bHasNaN = true;
1437 cntInvalidValues++;
1438
1439 if (bPassNoDataValue && nDepth > 1)
1440 zVal = origNoData; // replace NaN
1441 else if (nDepth == 1)
1442 zVal = 0;
1443 }
1444 else if (bPassNoDataValue && zVal == origNoData)
1445 {
1446 cntInvalidValues++;
1447 }
1448 else
1449 {
1450 if (zVal < minVal)
1451 minVal = zVal;
1452 if (zVal > maxVal)
1453 maxVal = zVal;
1454
1455 if (bAllInt && !IsInt(zVal))
1456 bAllInt = false;
1457 }
1458 }
1459
1460 if (cntInvalidValues == nDepth)
1461 {
1462 maskBuffer[k] = 0;
1463 bModifiedMask = true;
1464 }
1465 else if (cntInvalidValues > 0) // found mix of valid and invalid values at the same pixel
1466 bHasNoDataValuesLeft = true;
1467 }
1468 }
1469
1470 if (minVal == DBL_MAX && maxVal == -DBL_MAX) // if the tile has no valid data
1471 {
1472 minValA = maxValA = 0;
1473 maxZError = 0;
1474 return ErrCode::Ok;
1475 }
1476
1477 minValA = minVal;
1478 maxValA = maxVal;
1479 bNeedNoData = bHasNoDataValuesLeft;
1480
1481 if (bHasNaN && nDepth > 1 && bHasNoDataValuesLeft && !bPassNoDataValue)
1482 {
1483 return ErrCode::NaN; // Lerc cannot handle this case, cannot pick a noData value on the tile level
1484 }
1485
1486 // now NaN's are gone, either moved to the mask or replaced by noData value
1487
1488 double maxZErrL = maxZError;
1489
1490 if (bAllInt)
1491 {
1492 bAllInt &= (minVal >= lowIntLimit) && (minVal <= highIntLimit)
1493 && (maxVal >= lowIntLimit) && (maxVal <= highIntLimit);
1494
1495 if (bHasNoDataValuesLeft)
1496 bAllInt &= IsInt(origNoData) && (origNoData >= lowIntLimit) && (origNoData <= highIntLimit);
1497
1498 if (bAllInt)
1499 maxZErrL = (std::max)(0.5, floor(maxZError)); // same mapping for int types as in Lerc2.cpp
1500 }
1501
1502 bIsFltDblAllInt = bAllInt;
1503
1504 if (maxZErrL == 0) // if flt lossless, we are done
1505 return ErrCode::Ok;
1506
1507 if (bPassNoDataValue)
1508 {
1509 // check the orig noData value is far enough away from the valid range
1510 double dist = bAllInt ? floor(maxZErrL) : 2 * maxZErrL;
1511
1512 if ((origNoData >= minVal - dist) && (origNoData <= maxVal + dist))
1513 {
1514 maxZError = bAllInt ? 0.5 : 0; // fall back to lossless
1515 return ErrCode::Ok;
1516 }
1517 }
1518
1519 if (bHasNoDataValuesLeft) // try to remap noData to new noData just below the global minimum
1520 {
1521 T remapVal = origNoData;
1522 bool bRemapNoData = FindNewNoDataBelowValidMin(minVal, maxZErrL, bAllInt, lowIntLimit, remapVal);
1523
1524 if (bRemapNoData)
1525 {
1526 if (remapVal != origNoData)
1527 {
1528 for (int k = 0, i = 0; i < nRows; i++)
1529 {
1530 T* rowArr = &(dataBuffer[(size_t)i * nCols * nDepth]);
1531
1532 for (int n = 0, j = 0; j < nCols; j++, k++, n += nDepth)
1533 if (maskBuffer[k])
1534 for (int m = 0; m < nDepth; m++)
1535 if (rowArr[n + m] == origNoData)
1536 rowArr[n + m] = remapVal;
1537 }
1538
1539 noDataValue = remapVal;
1540 }
1541 }
1542 else if ((double)origNoData >= minVal) // sufficient distance of origNoData to valid range has been checked above
1543 {
1544 maxZErrL = bAllInt ? 0.5 : 0; // need lossless if noData cannot be mapped below valid range
1545 }
1546 }
1547
1548 if (maxZError != maxZErrL)
1549 maxZError = maxZErrL;
1550
1551 return ErrCode::Ok;
1552 }
1553
1554 // -------------------------------------------------------------------------- ;
1555
1556 template<class T>
1557 bool Lerc::FindNewNoDataBelowValidMin(double minVal, double maxZErr, bool bAllInt, double lowIntLimit, T& newNoDataVal)
1558 {
1559 if (bAllInt)
1560 {
1561 std::vector<T> noDataCandVec;
1562
1563 { // collect dist candidates
1564 std::vector<double> distCandVec = { 4 * maxZErr, 1, 10, 100, 1000, 10000 }; // only int candidates
1565
1566 for (double dist : distCandVec)
1567 noDataCandVec.push_back((T)(minVal - dist));
1568
1569 double candForLargeMinVal = (minVal > 0 ? floor(minVal / 2) : minVal * 2); // also int
1570 noDataCandVec.push_back((T)candForLargeMinVal);
1571 }
1572
1573 // sort them in descending order
1574 std::sort(noDataCandVec.begin(), noDataCandVec.end(), std::greater<double>());
1575
1576 // take the first one that satisfies the condition
1577 for (T noDataVal : noDataCandVec)
1578 {
1579 if ((noDataVal > (T)lowIntLimit) && (noDataVal < (T)(minVal - 2 * maxZErr)) && IsInt(noDataVal))
1580 {
1581 newNoDataVal = noDataVal;
1582 return true;
1583 }
1584 }
1585 }
1586 else
1587 {
1588 std::vector<T> noDataCandVec;
1589
1590 { // dist candidates
1591 std::vector<double> distCandVec = { 4 * maxZErr, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000 };
1592
1593 for (double dist : distCandVec)
1594 noDataCandVec.push_back((T)(minVal - dist));
1595
1596 double candForLargeMinVal = (minVal > 0 ? minVal / 2 : minVal * 2);
1597 noDataCandVec.push_back((T)candForLargeMinVal);
1598 }
1599
1600 // sort them in descending order
1601 std::sort(noDataCandVec.begin(), noDataCandVec.end(), std::greater<double>());
1602
1603 bool bIsFloat4 = (typeid(T) == typeid(float));
1604 T lowestVal = (T)(bIsFloat4 ? -FLT_MAX : -DBL_MAX);
1605
1606 // take the first one that satisfies the condition
1607 for (T noDataVal : noDataCandVec)
1608 {
1609 if ((noDataVal > lowestVal) && (noDataVal < (T)(minVal - 2 * maxZErr)))
1610 {
1611 newNoDataVal = noDataVal;
1612 return true;
1613 }
1614 }
1615 }
1616
1617 return false;
1618 }
1619
1620 // -------------------------------------------------------------------------- ;
1621
1622 bool Lerc::CheckDimensions(int nDepth, int nCols, int nRows, size_t sizeOfDataElement)
1623 {
1624 // here we guard against too large input dimensions that might cause a possible int32 overflow later;
1625 // we limit the size of input data per band to 2 GB, so any product [height * width * depth * sizeof(data element)] <= INT_MAX;
1626 // (see the corresponding size and dimension checks in Lerc2::ReadHeader(...));
1627
1628 if (nDepth <= 0 || nCols <= 0 || nRows <= 0)
1629 return false;
1630
1631 const uint64_t numPixel = (uint64_t)nRows * nCols;
1632 const uint64_t maxint32 = (uint64_t)INT_MAX;
1633 const uint64_t nbpp = sizeOfDataElement;
1634
1635 if (numPixel > maxint32 || nbpp > maxint32 || nbpp * nDepth > maxint32 || nbpp * nDepth * numPixel > maxint32)
1636 return false;
1637
1638 return true;
1639 }
1640
1641 // -------------------------------------------------------------------------- ;