lerc-sys 0.1.5

Low-level FFI bindings to Esri's LERC C API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/*
Copyright 2021 - 2022 Esri

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

A local copy of the license and additional notices are located with the
source distribution at:

http://github.com/Esri/lerc/

Analytical Raster Compression.
Original coding 2021 Yuriy Yakimenko
*/

#include "fpl_EsriHuffman.h"
#include "Huffman.h"
#include <assert.h>
#include <cstdlib>
#include <stdint.h>
#include <limits>
#include <algorithm>

USING_NAMESPACE_LERC

void lerc_assert(bool v);

bool decodePackBits (const unsigned char *ptr, const size_t size, size_t expected, unsigned char **output)
{
    unsigned char *out = NULL;

    if (*output == NULL)
    {
        out = (unsigned char *)malloc (expected); // max possible

        *output = out;
    }
    else
    {
        out = *output;
    }

    size_t curr = 0;

    for (size_t i = 0; i < size; )
    {
        // read header byte.

        int b = ptr[i];

        if (b <= 127)
        {
            while (b >= 0) { i++; out[curr++] = ptr[i]; b--; }
            i++;
            continue;
        }
        else
        {
            i++;
            while (b >= 127) { out[curr++] = ptr[i]; b--; }
            i++;
            continue;
        }
    }

    return (curr == expected);
}

long encodePackBits (const unsigned char *ptr, const size_t size, unsigned char **output)
{
    unsigned char *out = NULL;

    if (*output == NULL)
    {
        out = (unsigned char *)malloc (size * 2 + 1); // max possible

        *output = out;
    }
    else
    {
        out = *output;
    }

    int repeat_count = 0;

    int literal_count = 0;

    int curr = 0;

    int literal_len_pos = -1;

    for (size_t i = 0; i <= size; )
    {
        int b = (i == size) ? -1 : ptr[i];

        repeat_count = 0;

        while (i < size - 1 && b == ptr[i + 1] && repeat_count < 128)
        {
            i++;
            repeat_count++;
        }

        i++;

        // two cases:
        // repeat count = 0: increase literal_len, assign literal_pos if not set.
        // repeat count > 0 :
        //    a) if literal_len > 0, flush literal_len, then write sequence
        //    b) if literal_len = 0 then just write sequence

        if (repeat_count == 0 && b >= 0)
        {
            if (literal_len_pos < 0)
            {
                literal_len_pos = curr;
                curr++;
            }

            out[curr++] = (unsigned char)b;

            literal_count++;

            if (literal_count == 128)
            {
                out[literal_len_pos] = (unsigned char)(literal_count - 1);
                literal_count = 0;
                literal_len_pos = -1;
            }
        }
        else
        {
            if (literal_count > 0)
            {
                out[literal_len_pos] = (unsigned char)(literal_count - 1);
                literal_len_pos = -1;
                literal_count = 0;
            }

            if (repeat_count > 0)
            {
                out[curr++] = (unsigned char)(127 + repeat_count);
                out[curr++] = (unsigned char)b;
            }

        }

    }

    return curr;
}


long getPackBitsSize (const unsigned char *ptr, const size_t size, long * limit)
{
    int repeat_count = 0;

    int literal_count = 0;

    long curr = 0;

    int literal_len_pos = -1;

    long m_limit = *limit ? *limit : (std::numeric_limits<long>::max)();

    for (size_t i = 0; i <= size; )
    {
        int b = (i == size) ? -1 : ptr[i];

        if (curr > m_limit)
            return -1;

        repeat_count = 0;

        while (i < size - 1 && b == ptr[i + 1] && repeat_count < 128)
        {
            i++;
            repeat_count++;
        }

        i++;

        // two cases:
        // repeat count = 0: increase literal_len, assign literal_pos if not set.
        // repeat count > 0 :
        //    a) if literal_len > 0, flush literal_len, then write sequence
        //    b) if literal_len = 0 then just write sequence

        if (repeat_count == 0 && b >= 0)
        {
            if (literal_len_pos < 0)
            {
                literal_len_pos = curr;
                curr++;
            }

            curr++;

            literal_count++;

            if (literal_count == 128)
            {
                literal_count = 0;
                literal_len_pos = -1;
            }
        }
        else
        {
            if (literal_count > 0)
            {
                literal_len_pos = -1;
                literal_count = 0;
            }

            if (repeat_count > 0)
            {
                curr += 2;
            }

        }

    }

    return curr;
}

enum HuffmanErrorCodes { MEMORY_ALLOC_FAIL = -1, HUFF_UNEXPECTED = -2 };

enum HuffmanFirstByte { HUFFMAN_NORMAL = 0, HUFFMAN_RLE = 1, HUFFMAN_NO_ENCODING = 2, HUFFMAN_PACKBITS = 3 };

bool ComputeHistoForHuffman(const unsigned char* data, size_t len, std::vector<int>& histo)
{
    histo.resize(256);

    memset (&histo[0], 0, histo.size() * sizeof(int));

    for (size_t i = 0; i < len; i++)
    {
        unsigned char val = data[i];

        histo[val]++;
    }

    int cnt = 0;
    for (size_t i = 0; i < 256; i++)
    {
        if (histo[i] > 0)
        {
            cnt++;
            if (cnt == 2) break;
        }
    }

    return (cnt > 1);
}

void ComputeHuffmanCodes(const unsigned char* data, size_t len, int& numBytes, std::vector<std::pair<unsigned short, unsigned int> >& codes)
{
    std::vector<int> histo;

    if (!ComputeHistoForHuffman(data, len, histo))
    {
        numBytes = -1;
        return;
    }

    int nBytes = 0;
    double avgBpp = 0;
    Huffman huffman;

    if (!huffman.ComputeCodes(histo) || !huffman.ComputeCompressedSize(histo, nBytes, avgBpp))
      nBytes = 0;

    if (nBytes > 0)
    {
        codes = huffman.GetCodes() ;
    }

    numBytes = nBytes;
}

int fpl_EsriHuffman::getCompressedSize (const char *input, size_t input_len)
{
    int numBytes = 0;
    std::vector<std::pair<unsigned short, unsigned int> > m_huffmanCodes;

    ComputeHuffmanCodes ((const unsigned char *)input, input_len, numBytes, m_huffmanCodes);

    if (numBytes < 0) return 6;

    if (numBytes == 0) return 0;

    if (numBytes > (int)input_len)
        return (int)input_len + 1;

    return numBytes + 1;
}

//////////////////////////////////////////////////////////////////////////////////
//  outputs size of encoded buffer.
//  input: byte array, its length;
//  output buffer, its length. If output len isn't sufficient, returns 0.
//////////////////////////////////////////////////////////////////////////////////

int fpl_EsriHuffman::EncodeHuffman (const char *input, size_t input_len, unsigned char ** ppByte, bool use_rle)
{
    int numBytes = 0;
    std::vector<std::pair<unsigned short, unsigned int> > m_huffmanCodes;

    ComputeHuffmanCodes ((const unsigned char *)input, input_len, numBytes, m_huffmanCodes);

    if (numBytes == -1)
    {
        // there's only one value in entire block (probably zeroes)
        // encode as 6 bytes:
        // byte 1 RLE flag
        // byte 2 repeating value
        // bytes 3-6 repeat count (32-bit unsigned int).
        *ppByte = (unsigned char *)calloc (6, 1);

        unsigned char *ptr = *ppByte;

        ptr[0] = HUFFMAN_RLE; // RLE flag
        ptr[1] = input[0];

        lerc_assert(input_len <= 0xffffffff);

        uint32_t len = (uint32_t)input_len;

        memcpy (ptr + 2, &len, 4);

        return 6;
    }

    if (numBytes == 0)
    {
        return HUFF_UNEXPECTED;
    }

    if (use_rle)
    {
        long limit = (std::min) (numBytes, (int)input_len);

        long rle_len = getPackBitsSize ((unsigned char *)input, input_len, &limit);
        if (rle_len > 0 && (rle_len < numBytes) && (rle_len < (long)input_len))
        {
            *ppByte = (unsigned char *)malloc (rle_len + 1);

            if (*ppByte == NULL)
              return MEMORY_ALLOC_FAIL;

            unsigned char * originalPtr = *ppByte ;
            originalPtr[0] = HUFFMAN_PACKBITS;

            unsigned char *packed = originalPtr + 1; //NULL;
            encodePackBits ((unsigned char *)input, input_len, &packed);

            return rle_len + 1;
        }
    }

    if (numBytes >= (int)input_len) // huffman will take more space than uncompressed. Don't encode.
    {
        *ppByte = (unsigned char *)malloc (input_len + 1);

        if (*ppByte == NULL)
          return MEMORY_ALLOC_FAIL;

        unsigned char * originalPtr = *ppByte ;
        originalPtr[0] = HUFFMAN_NO_ENCODING; // as is flag
        memcpy (originalPtr + 1, input, input_len);

        return (int)input_len + 1;
    }

    *ppByte = (unsigned char *)malloc (numBytes + 1);

    if (*ppByte == NULL)
      return MEMORY_ALLOC_FAIL;

    unsigned char * originalPtr = *ppByte ;

    originalPtr[0] = HUFFMAN_NORMAL; // normal "huffman flag"

    *ppByte = originalPtr + 1;

    Huffman huffman;

    if (!huffman.SetCodes(m_huffmanCodes) || !huffman.WriteCodeTable(ppByte, 5))    // header and code table
    {
        free (originalPtr);
        *ppByte = NULL;
        return HUFF_UNEXPECTED;
    }

    int bitPos = 0;
    int offset = 0;
    const unsigned char *data = (const unsigned char *)input;

    for (size_t m = 0; m < input_len; m++)
    {
        unsigned char val = data[m];

        // bit stuff the huffman code for this val
        int kBin = offset + (int)val;
        int len = m_huffmanCodes[kBin].first;
        if (len <= 0)
        {
            free (originalPtr);
            *ppByte = NULL;
            return HUFF_UNEXPECTED;
        }

        unsigned int code = m_huffmanCodes[kBin].second;

        if (!Huffman::PushValue(ppByte, bitPos, code, len))
        {
          free(originalPtr);
          *ppByte = NULL;
          return HUFF_UNEXPECTED;
        }
    }

    size_t numUInts = (bitPos > 0 ? 1 : 0) + 1;    // add one more as the decode LUT can read ahead
    *ppByte += numUInts * sizeof(unsigned int);

    int ret = (int)(*ppByte - originalPtr);

    *ppByte = originalPtr;

    return ret;
}

bool fpl_EsriHuffman::DecodeHuffman(const unsigned char* inBytes, const size_t inCount, size_t& nBytesRemainingInOut, unsigned char** output)
{
    const unsigned char* ppByte = (const unsigned char *)inBytes;

    if (!ppByte)
    {
        //fprintf (stderr, "bad input: null pointer\n");
        return false;
    }

    // check for RLE flag

    if (ppByte[0] == HUFFMAN_RLE)
    {
        unsigned char s = ppByte[1];
        uint32_t rle_size = 0;

        memcpy (&rle_size, ppByte + 2, 4);

        if (rle_size != nBytesRemainingInOut)
        {
            assert (0);
        }

        unsigned char *data = (unsigned char *)malloc (nBytesRemainingInOut);
        *output = data;

        if (data == NULL)
        {
            //fprintf (stderr, "malloc() failed\n");
            return false;
        }

        memset (data, s, nBytesRemainingInOut);

        return true;
    }

    if (ppByte[0] == HUFFMAN_NO_ENCODING) // "as is flag"
    {
        unsigned char *data = (unsigned char *)malloc (nBytesRemainingInOut);
        *output = data;

        if (data == NULL)
        {
            //printf ("malloc 2 fail\n");
            return false;
        }

        memcpy (data, ppByte + 1, nBytesRemainingInOut);

        return true;
    }

    if (ppByte[0] == HUFFMAN_PACKBITS)
    {
        unsigned char *unpacked = NULL;

        lerc_assert (true == decodePackBits (ppByte + 1, inCount - 1, nBytesRemainingInOut, &unpacked));

        *output = unpacked;

        return true;
    }

    assert (ppByte[0] == HUFFMAN_NORMAL); // "normal" huffman flag.

    ppByte++;

    size_t expected_output_len = nBytesRemainingInOut;

    Huffman huffman;
    if (!huffman.ReadCodeTable(&ppByte, nBytesRemainingInOut, 5))    // header and code table
    {
        return false;
    }

    int numBitsLUT = 0;
    if (!huffman.BuildTreeFromCodes(numBitsLUT))
    {
        return false;
    }

    unsigned char *data = (unsigned char *)malloc (expected_output_len);
    *output = data;

    if (!data)
    {
        return false;
    }

    int offset = 0;
    int bitPos = 0;
    size_t nBytesRemaining = nBytesRemainingInOut;

    for (size_t m = 0; m < expected_output_len; m++)
    {
        int val = 0;
        if (!huffman.DecodeOneValue(&ppByte, nBytesRemaining, bitPos, numBitsLUT, val))
        {
            return false;
        }

        data[m] = (unsigned char)(val - offset);
    }

    return true;
}