Debian Codegraph @

src/LercLib/Huffman.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 <algorithm>
25 #include <queue>
26 #include "Defines.h"
27 #include "Huffman.h"
28 #include "BitStuffer2.h"
29
30 using namespace std;
31 USING_NAMESPACE_LERC
32
33 // -------------------------------------------------------------------------- ;
34
35 bool Huffman::ComputeCodes(const vector<int>& histo)
36 {
37 if (histo.empty() || histo.size() >= m_maxHistoSize)
38 return false;
39
40 priority_queue<Node, vector<Node>, less<Node> > pq;
41
42 int numNodes = 0;
43
44 int size = (int)histo.size();
45 for (int i = 0; i < size; i++) // add all leaf nodes
46 if (histo[i] > 0)
47 pq.push(Node((short)i, histo[i]));
48
49 if (pq.size() < 2) // histo has only 0 or 1 bin that is not empty; quit Huffman and give it to Lerc
50 return false;
51
52 while (pq.size() > 1) // build the Huffman tree
53 {
54 Node* child0 = new Node(pq.top());
55 numNodes++;
56 pq.pop();
57 Node* child1 = new Node(pq.top());
58 numNodes++;
59 pq.pop();
60 pq.push(Node(child0, child1));
61 }
62
63 m_codeTable.resize(size);
64 std::fill(m_codeTable.begin(), m_codeTable.end(),
65 std::pair<unsigned short, unsigned int>((short)0, 0));
66
67 if (!pq.top().TreeToLUT(0, 0, m_codeTable)) // fill the LUT
68 return false;
69
70 //pq.top().FreeTree(numNodes); // Linux compiler complains
71 Node nodeNonConst = pq.top();
72 nodeNonConst.FreeTree(numNodes); // free all the nodes
73
74 if (numNodes != 0) // check the ref count
75 return false;
76
77 if (!ConvertCodesToCanonical())
78 return false;
79
80 return true;
81 }
82
83 // -------------------------------------------------------------------------- ;
84
85 bool Huffman::ComputeCompressedSize(const std::vector<int>& histo, int& numBytes, double& avgBpp) const
86 {
87 if (histo.empty() || histo.size() >= m_maxHistoSize)
88 return false;
89
90 numBytes = 0;
91 if (!ComputeNumBytesCodeTable(numBytes)) // header and code table
92 return false;
93
94 int numBits = 0, numElem = 0;
95 int size = (int)histo.size();
96 for (int i = 0; i < size; i++)
97 if (histo[i] > 0)
98 {
99 numBits += histo[i] * m_codeTable[i].first;
100 numElem += histo[i];
101 }
102
103 if (numElem == 0)
104 return false;
105
106 int numUInts = ((((numBits + 7) >> 3) + 3) >> 2) + 1; // add one more as the decode LUT can read ahead
107 numBytes += 4 * numUInts; // data huffman coded
108 avgBpp = 8 * numBytes / (double)numElem;
109
110 return true;
111 }
112
113 // -------------------------------------------------------------------------- ;
114
115 bool Huffman::SetCodes(const vector<pair<unsigned short, unsigned int> >& codeTable)
116 {
117 if (codeTable.empty() || codeTable.size() >= m_maxHistoSize)
118 return false;
119
120 m_codeTable = codeTable;
121 return true;
122 }
123
124 // -------------------------------------------------------------------------- ;
125
126 bool Huffman::WriteCodeTable(Byte** ppByte, int lerc2Version) const
127 {
128 if (!ppByte)
129 return false;
130
131 int i0, i1, maxLen;
132 if (!GetRange(i0, i1, maxLen))
133 return false;
134
135 int size = (int)m_codeTable.size();
136 vector<unsigned int> dataVec(i1 - i0, 0);
137
138 for (int i = i0; i < i1; i++)
139 {
140 int k = GetIndexWrapAround(i, size);
141 dataVec[i - i0] = m_codeTable[k].first;
142 }
143
144 // header
145 vector<int> intVec;
146 intVec.push_back(4); // huffman version; 4 guarantees canonical codes
147 intVec.push_back(size);
148 intVec.push_back(i0); // code range
149 intVec.push_back(i1);
150
151 Byte* ptr = *ppByte;
152
153 size_t len = intVec.size() * sizeof(int);
154 memcpy(ptr, &intVec[0], len);
155 ptr += len;
156
157 BitStuffer2 bitStuffer2;
158 if (!bitStuffer2.EncodeSimple(&ptr, dataVec, lerc2Version)) // code lengths, bit stuffed
159 return false;
160
161 if (!BitStuffCodes(&ptr, i0, i1)) // variable length codes, bit stuffed
162 return false;
163
164 *ppByte = ptr;
165 return true;
166 }
167
168 // -------------------------------------------------------------------------- ;
169
170 bool Huffman::ReadCodeTable(const Byte** ppByte, size_t& nBytesRemainingInOut, int lerc2Version)
171 {
172 if (!ppByte || !(*ppByte))
173 return false;
174
175 const Byte* ptr = *ppByte;
176 size_t nBytesRemaining = nBytesRemainingInOut;
177
178 vector<int> intVec(4, 0);
179 size_t len = intVec.size() * sizeof(int);
180
181 if (nBytesRemaining < len)
182 return false;
183
184 memcpy(&intVec[0], ptr, len);
185 ptr += len;
186 nBytesRemaining -= len;
187
188 int version = intVec[0];
189
190 if (version < 2) // allow forward compatibility; for updates that break old decoders increase Lerc2 version number;
191 return false;
192
193 const int size = intVec[1];
194 const int i0 = intVec[2];
195 const int i1 = intVec[3];
196
197 if (i0 >= i1 || i0 < 0 || size < 0 || size > (int)m_maxHistoSize)
198 return false;
199
200 if (GetIndexWrapAround(i0, size) >= size || GetIndexWrapAround(i1 - 1, size) >= size)
201 return false;
202
203 try
204 {
205 vector<unsigned int> dataVec(i1 - i0, 0);
206 BitStuffer2 bitStuffer2;
207 if (!bitStuffer2.Decode(&ptr, nBytesRemaining, dataVec, dataVec.size(), lerc2Version)) // unstuff the code lengths
208 return false;
209
210 if (dataVec.size() != static_cast<size_t>(i1 - i0))
211 return false;
212
213 m_codeTable.resize(size);
214 std::fill(m_codeTable.begin(), m_codeTable.end(),
215 std::pair<unsigned short, unsigned int>((short)0, 0));
216
217 for (int i = i0; i < i1; i++)
218 {
219 int k = GetIndexWrapAround(i, size);
220 m_codeTable[k].first = (unsigned short)dataVec[i - i0];
221 }
222
223 if (!BitUnStuffCodes(&ptr, nBytesRemaining, i0, i1)) // unstuff the codes
224 return false;
225
226 *ppByte = ptr;
227 nBytesRemainingInOut = nBytesRemaining;
228 return true;
229 }
230 catch (std::exception&)
231 {
232 return false;
233 }
234 }
235
236 // -------------------------------------------------------------------------- ;
237
238 bool Huffman::BuildTreeFromCodes(int& numBitsLUT)
239 {
240 int i0 = 0, i1 = 0, maxLen = 0;
241 if (!GetRange(i0, i1, maxLen))
242 return false;
243
244 // build decode LUT using max of 12 bits
245 int size = (int)m_codeTable.size();
246 int minNumZeroBits = 32;
247
248 bool bNeedTree = maxLen > m_maxNumBitsLUT;
249 numBitsLUT = min(maxLen, m_maxNumBitsLUT);
250
251 int sizeLUT = 1 << numBitsLUT;
252
253 m_decodeLUT.clear();
254 m_decodeLUT.assign((size_t)sizeLUT, pair<short, short>((short)-1, (short)-1));
255
256 for (int i = i0; i < i1; i++)
257 {
258 int k = GetIndexWrapAround(i, size);
259 int len = m_codeTable[k].first;
260
261 if (len == 0)
262 continue;
263
264 unsigned int code = m_codeTable[k].second;
265
266 if (len <= numBitsLUT)
267 {
268 code <<= (numBitsLUT - len);
269 unsigned int numEntries = 1 << (numBitsLUT - len);
270 pair<short, short> entry((short)len, (short)k);
271
272 for (unsigned int j = 0; j < numEntries; j++)
273 m_decodeLUT[code | j] = entry; // add the duplicates
274 }
275 else // for the codes too long for the LUT, count how many leading bits are 0
276 {
277 int shift = 1;
278 while (code >>= 1) shift++; // large canonical codes start with zero's
279 minNumZeroBits = min(minNumZeroBits, len - shift);
280 }
281 }
282
283 m_numBitsToSkipInTree = bNeedTree? minNumZeroBits : 0;
284
285 if (!bNeedTree) // decode LUT covers it all, no tree needed
286 return true;
287
288 //m_numBitsToSkipInTree = 0; // to disable skipping the 0 bits
289
290 ClearTree(); // if there
291
292 Node emptyNode((short)-1, 0);
293 m_root = new Node(emptyNode);
294
295 for (int i = i0; i < i1; i++)
296 {
297 int k = GetIndexWrapAround(i, size);
298 int len = m_codeTable[k].first;
299
300 if (len > 0 && len > numBitsLUT) // add only codes not in the decode LUT
301 {
302 unsigned int code = m_codeTable[k].second;
303 Node* node = m_root;
304 int j = len - m_numBitsToSkipInTree; // reduce len by number of leading 0 bits from above
305
306 while (--j >= 0) // go over the bits
307 {
308 if (code & (1 << j))
309 {
310 if (!node->child1)
311 node->child1 = new Node(emptyNode);
312
313 node = node->child1;
314 }
315 else
316 {
317 if (!node->child0)
318 node->child0 = new Node(emptyNode);
319
320 node = node->child0;
321 }
322
323 if (j == 0) // last bit, leaf node
324 node->value = (short)k; // set the value
325 }
326 }
327 }
328
329 return true;
330 }
331
332 // -------------------------------------------------------------------------- ;
333
334 void Huffman::Clear()
335 {
336 m_codeTable.clear();
337 m_decodeLUT.clear();
338 ClearTree();
339 }
340
341 // -------------------------------------------------------------------------- ;
342
343 void Huffman::ClearTree()
344 {
345 if (m_root)
346 {
347 int n = 0;
348 m_root->FreeTree(n);
349 delete m_root;
350 m_root = nullptr;
351 }
352 }
353
354 // -------------------------------------------------------------------------- ;
355 // -------------------------------------------------------------------------- ;
356
357 bool Huffman::ComputeNumBytesCodeTable(int& numBytes) const
358 {
359 int i0, i1, maxLen;
360 if (!GetRange(i0, i1, maxLen))
361 return false;
362
363 int size = (int)m_codeTable.size();
364 int sum = 0;
365 for (int i = i0; i < i1; i++)
366 {
367 int k = GetIndexWrapAround(i, size);
368 sum += m_codeTable[k].first;
369 }
370
371 numBytes = 4 * sizeof(int); // version, size, first bin, (last + 1) bin
372
373 BitStuffer2 bitStuffer2;
374 numBytes += bitStuffer2.ComputeNumBytesNeededSimple((unsigned int)(i1 - i0), (unsigned int)maxLen); // code lengths
375 int numUInts = (((sum + 7) >> 3) + 3) >> 2;
376 numBytes += 4 * numUInts; // byte array with the codes bit stuffed
377
378 return true;
379 }
380
381 // -------------------------------------------------------------------------- ;
382
383 bool Huffman::GetRange(int& i0, int& i1, int& maxCodeLength) const
384 {
385 if (m_codeTable.empty() || m_codeTable.size() >= m_maxHistoSize)
386 return false;
387
388 // first, check for peak somewhere in the middle with 0 stretches left and right
389 int size = (int)m_codeTable.size();
390 {
391 int i = 0;
392 while (i < size && m_codeTable[i].first == 0) i++;
393 i0 = i;
394 i = size - 1;
395 while (i >= 0 && m_codeTable[i].first == 0) i--;
396 i1 = i + 1; // exclusive
397 }
398
399 if (i1 <= i0)
400 return false;
401
402 // second, cover the common case that the peak is close to 0
403 pair<int, int> segm(0, 0);
404 int j = 0;
405 while (j < size) // find the largest stretch of 0's, if any
406 {
407 while (j < size && m_codeTable[j].first > 0) j++;
408 int k0 = j;
409 while (j < size && m_codeTable[j].first == 0) j++;
410 int k1 = j;
411
412 if (k1 - k0 > segm.second)
413 segm = pair<int, int>(k0, k1 - k0);
414 }
415
416 if (size - segm.second < i1 - i0)
417 {
418 i0 = segm.first + segm.second;
419 i1 = segm.first + size; // do wrap around
420 }
421
422 if (i1 <= i0)
423 return false;
424
425 int maxLen = 0;
426 for (int i = i0; i < i1; i++)
427 {
428 int k = GetIndexWrapAround(i, size);
429 int len = m_codeTable[k].first;
430 maxLen = max(maxLen, len);
431 }
432
433 if (maxLen <= 0 || maxLen > 32)
434 return false;
435
436 maxCodeLength = maxLen;
437 return true;
438 }
439
440 // -------------------------------------------------------------------------- ;
441
442 bool Huffman::BitStuffCodes(Byte** ppByte, int i0, int i1) const
443 {
444 if (!ppByte)
445 return false;
446
447 int size = (int)m_codeTable.size();
448 int bitPos = 0;
449
450 for (int i = i0; i < i1; i++)
451 {
452 int k = GetIndexWrapAround(i, size);
453 int len = m_codeTable[k].first;
454 if (len > 0)
455 {
456 unsigned int val = m_codeTable[k].second;
457
458 if (!Huffman::PushValue(ppByte, bitPos, val, len))
459 return false;
460 }
461 }
462
463 size_t numUInts = (bitPos > 0 ? 1 : 0);
464 *ppByte += numUInts * sizeof(unsigned int);
465
466 return true;
467 }
468
469 // -------------------------------------------------------------------------- ;
470
471 bool Huffman::BitUnStuffCodes(const Byte** ppByte, size_t& nBytesRemainingInOut, int i0, int i1)
472 {
473 if (!ppByte || !(*ppByte))
474 return false;
475
476 size_t nBytesRemaining = nBytesRemainingInOut;
477
478 const Byte* ptr0 = *ppByte;
479 const Byte* ptr = ptr0;
480
481 const size_t s4 = sizeof(unsigned int);
482
483 int size = (int)m_codeTable.size();
484 int bitPos = 0;
485
486 for (int i = i0; i < i1; i++)
487 {
488 int k = GetIndexWrapAround(i, size);
489 int len = m_codeTable[k].first;
490 if (len > 0)
491 {
492 if (nBytesRemaining < s4 || len > 32)
493 return false;
494
495 unsigned int temp(0);
496 memcpy(&temp, ptr, s4);
497 m_codeTable[k].second = (temp << bitPos) >> (32 - len);
498
499 if (32 - bitPos >= len)
500 {
501 bitPos += len;
502 if (bitPos == 32)
503 {
504 bitPos = 0;
505 ptr += s4;
506 nBytesRemaining -= s4;
507 }
508 }
509 else
510 {
511 bitPos += len - 32;
512 ptr += s4;
513 nBytesRemaining -= s4;
514
515 if (nBytesRemaining < s4)
516 return false;
517
518 memcpy(&temp, ptr, s4);
519 m_codeTable[k].second |= temp >> (32 - bitPos); // bitPos > 0
520 }
521 }
522 }
523
524 size_t len = (ptr - ptr0) + (bitPos > 0 ? s4 : 0);
525
526 if (nBytesRemainingInOut < len)
527 return false;
528
529 *ppByte += len;
530 nBytesRemainingInOut -= len;
531
532 if (nBytesRemaining != nBytesRemainingInOut
533 && nBytesRemaining != nBytesRemainingInOut + s4) // the real check
534 return false;
535
536 return true;
537 }
538
539 // -------------------------------------------------------------------------- ;
540
541 bool Huffman::ConvertCodesToCanonical()
542 {
543 // from the non canonical code book, create an array to be sorted in descending order:
544 // codeLength * tableSize - index
545
546 unsigned int tableSize = (unsigned int)m_codeTable.size();
547 vector<pair<int, unsigned int>> sortVec(tableSize, pair<int, unsigned int>(0, 0));
548
549 for (unsigned int i = 0; i < tableSize; i++)
550 if (m_codeTable[i].first > 0)
551 sortVec[i] = pair<int, unsigned int>(m_codeTable[i].first * tableSize - i, i);
552
553 std::sort(sortVec.begin(), sortVec.end(),
554 [](const pair<int, unsigned int>& p0,
555 const pair<int, unsigned int>& p1) { return p0.first > p1.first; });
556
557 // create canonical codes and assign to orig code table
558 unsigned int index = sortVec[0].second;
559 unsigned short codeLen = m_codeTable[index].first; // max code length for this table
560 unsigned int i = 0, codeCanonical = 0;
561
562 while (i < tableSize && sortVec[i].first > 0)
563 {
564 index = sortVec[i++].second;
565 short delta = codeLen - m_codeTable[index].first; // difference of 2 consecutive code lengths, >= 0 as sorted
566 codeCanonical >>= delta;
567 codeLen -= delta;
568 m_codeTable[index].second = codeCanonical++;
569 }
570
571 return true;
572 }
573
574 // -------------------------------------------------------------------------- ;