Debian Codegraph @

src/LercLib/fpl_EsriHuffman.cpp

raw symbols SCIP
1 /*
2 Copyright 2021 - 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 Analytical Raster Compression.
22 Original coding 2021 Yuriy Yakimenko
23 */
24
25 #include "fpl_EsriHuffman.h"
26 #include "Huffman.h"
27 #include <assert.h>
28 #include <cstdlib>
29 #include <stdint.h>
30 #include <limits>
31 #include <algorithm>
32
33 USING_NAMESPACE_LERC
34
35 void lerc_assert(bool v);
36
37 bool decodePackBits (const unsigned char *ptr, const size_t size, size_t expected, unsigned char **output)
38 {
39 unsigned char *out = NULL;
40
41 if (*output == NULL)
42 {
43 out = (unsigned char *)malloc (expected); // max possible
44
45 *output = out;
46 }
47 else
48 {
49 out = *output;
50 }
51
52 size_t curr = 0;
53
54 for (size_t i = 0; i < size; )
55 {
56 int b = ptr[i++]; // read header byte
57
58 if (b <= 127)
59 {
60 if (curr + b >= expected)
61 return false;
62
63 int b1 = b + 1;
64 memcpy(&out[curr], &ptr[i], b1);
65 curr += b1;
66 i += b1;
67 }
68 else
69 {
70 if (curr + b - 127 >= expected)
71 return false;
72
73 int b1 = b - 127 + 1;
74 memset(&out[curr], ptr[i], b1);
75 curr += b1;
76 i++;
77 }
78 }
79
80 return (curr == expected);
81 }
82
83 long encodePackBits (const unsigned char *ptr, const size_t size, unsigned char **output)
84 {
85 unsigned char *out = NULL;
86
87 if (*output == NULL)
88 {
89 out = (unsigned char *)malloc (size * 2 + 1); // max possible
90
91 *output = out;
92 }
93 else
94 {
95 out = *output;
96 }
97
98 int repeat_count = 0;
99
100 int literal_count = 0;
101
102 int curr = 0;
103
104 int literal_len_pos = -1;
105
106 for (size_t i = 0; i <= size; )
107 {
108 int b = (i == size) ? -1 : ptr[i];
109
110 repeat_count = 0;
111
112 while (i < size - 1 && b == ptr[i + 1] && repeat_count < 128)
113 {
114 i++;
115 repeat_count++;
116 }
117
118 i++;
119
120 // two cases:
121 // repeat count = 0: increase literal_len, assign literal_pos if not set.
122 // repeat count > 0 :
123 // a) if literal_len > 0, flush literal_len, then write sequence
124 // b) if literal_len = 0 then just write sequence
125
126 if (repeat_count == 0 && b >= 0)
127 {
128 if (literal_len_pos < 0)
129 {
130 literal_len_pos = curr;
131 curr++;
132 }
133
134 out[curr++] = (unsigned char)b;
135
136 literal_count++;
137
138 if (literal_count == 128)
139 {
140 out[literal_len_pos] = (unsigned char)(literal_count - 1);
141 literal_count = 0;
142 literal_len_pos = -1;
143 }
144 }
145 else
146 {
147 if (literal_count > 0)
148 {
149 out[literal_len_pos] = (unsigned char)(literal_count - 1);
150 literal_len_pos = -1;
151 literal_count = 0;
152 }
153
154 if (repeat_count > 0)
155 {
156 out[curr++] = (unsigned char)(127 + repeat_count);
157 out[curr++] = (unsigned char)b;
158 }
159
160 }
161
162 }
163
164 return curr;
165 }
166
167
168 long getPackBitsSize (const unsigned char *ptr, const size_t size, long * limit)
169 {
170 int repeat_count = 0;
171
172 int literal_count = 0;
173
174 long curr = 0;
175
176 int literal_len_pos = -1;
177
178 long m_limit = *limit ? *limit : (std::numeric_limits<long>::max)();
179
180 for (size_t i = 0; i <= size; )
181 {
182 int b = (i == size) ? -1 : ptr[i];
183
184 if (curr > m_limit)
185 return -1;
186
187 repeat_count = 0;
188
189 while (i < size - 1 && b == ptr[i + 1] && repeat_count < 128)
190 {
191 i++;
192 repeat_count++;
193 }
194
195 i++;
196
197 // two cases:
198 // repeat count = 0: increase literal_len, assign literal_pos if not set.
199 // repeat count > 0 :
200 // a) if literal_len > 0, flush literal_len, then write sequence
201 // b) if literal_len = 0 then just write sequence
202
203 if (repeat_count == 0 && b >= 0)
204 {
205 if (literal_len_pos < 0)
206 {
207 literal_len_pos = curr;
208 curr++;
209 }
210
211 curr++;
212
213 literal_count++;
214
215 if (literal_count == 128)
216 {
217 literal_count = 0;
218 literal_len_pos = -1;
219 }
220 }
221 else
222 {
223 if (literal_count > 0)
224 {
225 literal_len_pos = -1;
226 literal_count = 0;
227 }
228
229 if (repeat_count > 0)
230 {
231 curr += 2;
232 }
233
234 }
235
236 }
237
238 return curr;
239 }
240
241 enum HuffmanErrorCodes { MEMORY_ALLOC_FAIL = -1, HUFF_UNEXPECTED = -2 };
242
243 enum HuffmanFirstByte { HUFFMAN_NORMAL = 0, HUFFMAN_RLE = 1, HUFFMAN_NO_ENCODING = 2, HUFFMAN_PACKBITS = 3 };
244
245 bool ComputeHistoForHuffman(const unsigned char* data, size_t len, std::vector<int>& histo)
246 {
247 histo.resize(256);
248
249 memset (&histo[0], 0, histo.size() * sizeof(int));
250
251 for (size_t i = 0; i < len; i++)
252 {
253 unsigned char val = data[i];
254
255 histo[val]++;
256 }
257
258 int cnt = 0;
259 for (size_t i = 0; i < 256; i++)
260 {
261 if (histo[i] > 0)
262 {
263 cnt++;
264 if (cnt == 2) break;
265 }
266 }
267
268 return (cnt > 1);
269 }
270
271 void ComputeHuffmanCodes(const unsigned char* data, size_t len, int& numBytes, std::vector<std::pair<unsigned short, unsigned int> >& codes)
272 {
273 std::vector<int> histo;
274
275 if (!ComputeHistoForHuffman(data, len, histo))
276 {
277 numBytes = -1;
278 return;
279 }
280
281 int nBytes = 0;
282 double avgBpp = 0;
283 Huffman huffman;
284
285 if (!huffman.ComputeCodes(histo) || !huffman.ComputeCompressedSize(histo, nBytes, avgBpp))
286 nBytes = 0;
287
288 if (nBytes > 0)
289 {
290 codes = huffman.GetCodes() ;
291 }
292
293 numBytes = nBytes;
294 }
295
296 int fpl_EsriHuffman::getCompressedSize (const char *input, size_t input_len)
297 {
298 int numBytes = 0;
299 std::vector<std::pair<unsigned short, unsigned int> > m_huffmanCodes;
300
301 ComputeHuffmanCodes ((const unsigned char *)input, input_len, numBytes, m_huffmanCodes);
302
303 if (numBytes < 0) return 6;
304
305 if (numBytes == 0) return 0;
306
307 if (numBytes > (int)input_len)
308 return (int)input_len + 1;
309
310 return numBytes + 1;
311 }
312
313 //////////////////////////////////////////////////////////////////////////////////
314 // outputs size of encoded buffer.
315 // input: byte array, its length;
316 // output buffer, its length. If output len isn't sufficient, returns 0.
317 //////////////////////////////////////////////////////////////////////////////////
318
319 int fpl_EsriHuffman::EncodeHuffman (const char *input, size_t input_len, unsigned char ** ppByte, bool use_rle)
320 {
321 int numBytes = 0;
322 std::vector<std::pair<unsigned short, unsigned int> > m_huffmanCodes;
323
324 ComputeHuffmanCodes ((const unsigned char *)input, input_len, numBytes, m_huffmanCodes);
325
326 if (numBytes == -1)
327 {
328 // there's only one value in entire block (probably zeroes)
329 // encode as 6 bytes:
330 // byte 1 RLE flag
331 // byte 2 repeating value
332 // bytes 3-6 repeat count (32-bit unsigned int).
333 *ppByte = (unsigned char *)calloc (6, 1);
334
335 unsigned char *ptr = *ppByte;
336
337 ptr[0] = HUFFMAN_RLE; // RLE flag
338 ptr[1] = input[0];
339
340 lerc_assert(input_len <= 0xffffffff);
341
342 uint32_t len = (uint32_t)input_len;
343
344 memcpy (ptr + 2, &len, 4);
345
346 return 6;
347 }
348
349 if (numBytes == 0)
350 {
351 return HUFF_UNEXPECTED;
352 }
353
354 if (use_rle)
355 {
356 long limit = (std::min) (numBytes, (int)input_len);
357
358 long rle_len = getPackBitsSize ((unsigned char *)input, input_len, &limit);
359 if (rle_len > 0 && (rle_len < numBytes) && (rle_len < (long)input_len))
360 {
361 if ((rle_len + 1) <= 0) // rle_len is maximum long value, so adding 1 results in overflow.
362 {
363 return HUFF_UNEXPECTED; // this should not normally happen.
364 }
365
366 *ppByte = (unsigned char *)malloc (rle_len + 1);
367
368 if (*ppByte == NULL)
369 return MEMORY_ALLOC_FAIL;
370
371 unsigned char * originalPtr = *ppByte ;
372 originalPtr[0] = HUFFMAN_PACKBITS;
373
374 unsigned char *packed = originalPtr + 1; //NULL;
375 encodePackBits ((unsigned char *)input, input_len, &packed);
376
377 return rle_len + 1;
378 }
379 }
380
381 if (numBytes >= (int)input_len) // huffman will take more space than uncompressed. Don't encode.
382 {
383 *ppByte = (unsigned char *)malloc (input_len + 1);
384
385 if (*ppByte == NULL)
386 return MEMORY_ALLOC_FAIL;
387
388 unsigned char * originalPtr = *ppByte ;
389 originalPtr[0] = HUFFMAN_NO_ENCODING; // as is flag
390 memcpy (originalPtr + 1, input, input_len);
391
392 return (int)input_len + 1;
393 }
394
395 *ppByte = (unsigned char *)malloc (numBytes + 1);
396
397 if (*ppByte == NULL)
398 return MEMORY_ALLOC_FAIL;
399
400 unsigned char * originalPtr = *ppByte ;
401
402 originalPtr[0] = HUFFMAN_NORMAL; // normal "huffman flag"
403
404 *ppByte = originalPtr + 1;
405
406 Huffman huffman;
407
408 if (!huffman.SetCodes(m_huffmanCodes) || !huffman.WriteCodeTable(ppByte, 5)) // header and code table
409 {
410 free (originalPtr);
411 *ppByte = NULL;
412 return HUFF_UNEXPECTED;
413 }
414
415 int bitPos = 0;
416 int offset = 0;
417 const unsigned char *data = (const unsigned char *)input;
418
419 for (size_t m = 0; m < input_len; m++)
420 {
421 unsigned char val = data[m];
422
423 // bit stuff the huffman code for this val
424 int kBin = offset + (int)val;
425 int len = m_huffmanCodes[kBin].first;
426 if (len <= 0)
427 {
428 free (originalPtr);
429 *ppByte = NULL;
430 return HUFF_UNEXPECTED;
431 }
432
433 unsigned int code = m_huffmanCodes[kBin].second;
434
435 if (!Huffman::PushValue(ppByte, bitPos, code, len))
436 {
437 free(originalPtr);
438 *ppByte = NULL;
439 return HUFF_UNEXPECTED;
440 }
441 }
442
443 size_t numUInts = (bitPos > 0 ? 1 : 0) + 1; // add one more as the decode LUT can read ahead
444 *ppByte += numUInts * sizeof(unsigned int);
445
446 int ret = (int)(*ppByte - originalPtr);
447
448 *ppByte = originalPtr;
449
450 return ret;
451 }
452
453 bool fpl_EsriHuffman::DecodeHuffman(const unsigned char* inBytes, const size_t inCount, size_t& nBytesRemainingInOut, unsigned char** output)
454 {
455 const unsigned char* ppByte = (const unsigned char *)inBytes;
456
457 if (!ppByte)
458 {
459 //fprintf (stderr, "bad input: null pointer\n");
460 return false;
461 }
462
463 // check for RLE flag
464
465 if (ppByte[0] == HUFFMAN_RLE)
466 {
467 unsigned char s = ppByte[1];
468 uint32_t rle_size = 0;
469
470 memcpy (&rle_size, ppByte + 2, 4);
471
472 if (rle_size != nBytesRemainingInOut)
473 {
474 assert (0);
475 }
476
477 unsigned char *data = (unsigned char *)malloc (nBytesRemainingInOut);
478 *output = data;
479
480 if (data == NULL)
481 {
482 //fprintf (stderr, "malloc() failed\n");
483 return false;
484 }
485
486 memset (data, s, nBytesRemainingInOut);
487
488 return true;
489 }
490
491 if (ppByte[0] == HUFFMAN_NO_ENCODING) // "as is flag"
492 {
493 unsigned char *data = (unsigned char *)malloc (nBytesRemainingInOut);
494 *output = data;
495
496 if (data == NULL)
497 {
498 //printf ("malloc 2 fail\n");
499 return false;
500 }
501
502 memcpy (data, ppByte + 1, nBytesRemainingInOut);
503
504 return true;
505 }
506
507 if (ppByte[0] == HUFFMAN_PACKBITS)
508 {
509 unsigned char *unpacked = NULL;
510
511 lerc_assert (true == decodePackBits (ppByte + 1, inCount - 1, nBytesRemainingInOut, &unpacked));
512
513 *output = unpacked;
514
515 return true;
516 }
517
518 assert (ppByte[0] == HUFFMAN_NORMAL); // "normal" huffman flag.
519
520 ppByte++;
521
522 size_t expected_output_len = nBytesRemainingInOut;
523
524 Huffman huffman;
525 if (!huffman.ReadCodeTable(&ppByte, nBytesRemainingInOut, 5)) // header and code table
526 {
527 return false;
528 }
529
530 int numBitsLUT = 0;
531 if (!huffman.BuildTreeFromCodes(numBitsLUT))
532 {
533 return false;
534 }
535
536 unsigned char *data = (unsigned char *)malloc (expected_output_len);
537 *output = data;
538
539 if (!data)
540 {
541 return false;
542 }
543
544 int offset = 0;
545 int bitPos = 0;
546 size_t nBytesRemaining = nBytesRemainingInOut;
547
548 for (size_t m = 0; m < expected_output_len; m++)
549 {
550 int val = 0;
551 if (!huffman.DecodeOneValue(&ppByte, nBytesRemaining, bitPos, numBitsLUT, val))
552 {
553 return false;
554 }
555
556 data[m] = (unsigned char)(val - offset);
557 }
558
559 return true;
560 }