Debian Codegraph @

thirdparty/thorvg/src/common/tvgCompressor.cpp

raw symbols SCIP
1 /*
2 * Copyright (c) 2020 - 2024 the ThorVG project. All rights reserved.
3
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
13
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 /*
24 * Lempel–Ziv–Welch (LZW) encoder/decoder by Guilherme R. Lampert([email protected])
25
26 * This is the compression scheme used by the GIF image format and the Unix 'compress' tool.
27 * Main differences from this implementation is that End Of Input (EOI) and Clear Codes (CC)
28 * are not stored in the output and the max code length in bits is 12, vs 16 in compress.
29 *
30 * EOI is simply detected by the end of the data stream, while CC happens if the
31 * dictionary gets filled. Data is written/read from bit streams, which handle
32 * byte-alignment for us in a transparent way.
33
34 * The decoder relies on the hardcoded data layout produced by the encoder, since
35 * no additional reconstruction data is added to the output, so they must match.
36 * The nice thing about LZW is that we can reconstruct the dictionary directly from
37 * the stream of codes generated by the encoder, so this avoids storing additional
38 * headers in the bit stream.
39
40 * The output code length is variable. It starts with the minimum number of bits
41 * required to store the base byte-sized dictionary and automatically increases
42 * as the dictionary gets larger (it starts at 9-bits and grows to 10-bits when
43 * code 512 is added, then 11-bits when 1024 is added, and so on). If the dictionary
44 * is filled (4096 items for a 12-bits dictionary), the whole thing is cleared and
45 * the process starts over. This is the main reason why the encoder and the decoder
46 * must match perfectly, since the lengths of the codes will not be specified with
47 * the data itself.
48
49 * USEFUL LINKS:
50 * https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch
51 * http://rosettacode.org/wiki/LZW_compression
52 * http://www.cs.duke.edu/csed/curious/compression/lzw.html
53 * http://www.cs.cf.ac.uk/Dave/Multimedia/node214.html
54 * http://marknelson.us/1989/10/01/lzw-data-compression/
55 */
56 #include "config.h"
57
58
59
60 #include <cstdlib>
61 #include <string>
62 #include <memory.h>
63 #include "tvgCompressor.h"
64
65 namespace tvg {
66
67
68 /************************************************************************/
69 /* LZW Implementation */
70 /************************************************************************/
71
72
73 //LZW Dictionary helper:
74 constexpr int Nil = -1;
75 constexpr int MaxDictBits = 12;
76 constexpr int StartBits = 9;
77 constexpr int FirstCode = (1 << (StartBits - 1)); // 256
78 constexpr int MaxDictEntries = (1 << MaxDictBits); // 4096
79
80
81 //Round up to the next power-of-two number, e.g. 37 => 64
82 static int nextPowerOfTwo(int num)
83 {
84 --num;
85 for (size_t i = 1; i < sizeof(num) * 8; i <<= 1) {
86 num = num | num >> i;
87 }
88 return ++num;
89 }
90
91
92 struct BitStreamWriter
93 {
94 uint8_t* stream; //Growable buffer to store our bits. Heap allocated & owned by the class instance.
95 int bytesAllocated; //Current size of heap-allocated stream buffer *in bytes*.
96 int granularity; //Amount bytesAllocated multiplies by when auto-resizing in appendBit().
97 int currBytePos; //Current byte being written to, from 0 to bytesAllocated-1.
98 int nextBitPos; //Bit position within the current byte to access next. 0 to 7.
99 int numBitsWritten; //Number of bits in use from the stream buffer, not including byte-rounding padding.
100
101 void internalInit()
102 {
103 stream = nullptr;
104 bytesAllocated = 0;
105 granularity = 2;
106 currBytePos = 0;
107 nextBitPos = 0;
108 numBitsWritten = 0;
109 }
110
111 uint8_t* allocBytes(const int bytesWanted, uint8_t * oldPtr, const int oldSize)
112 {
113 auto newMemory = static_cast<uint8_t *>(malloc(bytesWanted));
114 memset(newMemory, 0, bytesWanted);
115
116 if (oldPtr) {
117 memcpy(newMemory, oldPtr, oldSize);
118 free(oldPtr);
119 }
120 return newMemory;
121 }
122
123 BitStreamWriter()
124 {
125 /* 8192 bits for a start (1024 bytes). It will resize if needed.
126 Default granularity is 2. */
127 internalInit();
128 allocate(8192);
129 }
130
131 BitStreamWriter(const int initialSizeInBits, const int growthGranularity = 2)
132 {
133 internalInit();
134 setGranularity(growthGranularity);
135 allocate(initialSizeInBits);
136 }
137
138 ~BitStreamWriter()
139 {
140 free(stream);
141 }
142
143 void allocate(int bitsWanted)
144 {
145 //Require at least a byte.
146 if (bitsWanted <= 0) bitsWanted = 8;
147
148 //Round upwards if needed:
149 if ((bitsWanted % 8) != 0) bitsWanted = nextPowerOfTwo(bitsWanted);
150
151 //We might already have the required count.
152 const int sizeInBytes = bitsWanted / 8;
153 if (sizeInBytes <= bytesAllocated) return;
154
155 stream = allocBytes(sizeInBytes, stream, bytesAllocated);
156 bytesAllocated = sizeInBytes;
157 }
158
159 void appendBit(const int bit)
160 {
161 const uint32_t mask = uint32_t(1) << nextBitPos;
162 stream[currBytePos] = (stream[currBytePos] & ~mask) | (-bit & mask);
163 ++numBitsWritten;
164
165 if (++nextBitPos == 8) {
166 nextBitPos = 0;
167 if (++currBytePos == bytesAllocated) allocate(bytesAllocated * granularity * 8);
168 }
169 }
170
171 void appendBitsU64(const uint64_t num, const int bitCount)
172 {
173 for (int b = 0; b < bitCount; ++b) {
174 const uint64_t mask = uint64_t(1) << b;
175 const int bit = !!(num & mask);
176 appendBit(bit);
177 }
178 }
179
180 uint8_t* release()
181 {
182 auto oldPtr = stream;
183 internalInit();
184 return oldPtr;
185 }
186
187 void setGranularity(const int growthGranularity)
188 {
189 granularity = (growthGranularity >= 2) ? growthGranularity : 2;
190 }
191
192 int getByteCount() const
193 {
194 int usedBytes = numBitsWritten / 8;
195 int leftovers = numBitsWritten % 8;
196 if (leftovers != 0) ++usedBytes;
197 return usedBytes;
198 }
199 };
200
201
202 struct BitStreamReader
203 {
204 const uint8_t* stream; // Pointer to the external bit stream. Not owned by the reader.
205 const int sizeInBytes; // Size of the stream *in bytes*. Might include padding.
206 const int sizeInBits; // Size of the stream *in bits*, padding *not* include.
207 int currBytePos = 0; // Current byte being read in the stream.
208 int nextBitPos = 0; // Bit position within the current byte to access next. 0 to 7.
209 int numBitsRead = 0; // Total bits read from the stream so far. Never includes byte-rounding padding.
210
211 BitStreamReader(const uint8_t* bitStream, const int byteCount, const int bitCount) : stream(bitStream), sizeInBytes(byteCount), sizeInBits(bitCount)
212 {
213 }
214
215 bool readNextBit(int& bitOut)
216 {
217 if (numBitsRead >= sizeInBits) return false; //We are done.
218
219 const uint32_t mask = uint32_t(1) << nextBitPos;
220 bitOut = !!(stream[currBytePos] & mask);
221 ++numBitsRead;
222
223 if (++nextBitPos == 8) {
224 nextBitPos = 0;
225 ++currBytePos;
226 }
227 return true;
228 }
229
230 uint64_t readBitsU64(const int bitCount)
231 {
232 uint64_t num = 0;
233 for (int b = 0; b < bitCount; ++b) {
234 int bit;
235 if (!readNextBit(bit)) break;
236 /* Based on a "Stanford bit-hack":
237 http://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching */
238 const uint64_t mask = uint64_t(1) << b;
239 num = (num & ~mask) | (-bit & mask);
240 }
241 return num;
242 }
243
244 bool isEndOfStream() const
245 {
246 return numBitsRead >= sizeInBits;
247 }
248 };
249
250
251 struct Dictionary
252 {
253 struct Entry
254 {
255 int code;
256 int value;
257 };
258
259 //Dictionary entries 0-255 are always reserved to the byte/ASCII range.
260 int size;
261 Entry entries[MaxDictEntries];
262
263 Dictionary()
264 {
265 /* First 256 dictionary entries are reserved to the byte/ASCII range.
266 Additional entries follow for the character sequences found in the input.
267 Up to 4096 - 256 (MaxDictEntries - FirstCode). */
268 size = FirstCode;
269
270 for (int i = 0; i < size; ++i) {
271 entries[i].code = Nil;
272 entries[i].value = i;
273 }
274 }
275
276 int findIndex(const int code, const int value) const
277 {
278 if (code == Nil) return value;
279
280 //Linear search for now.
281 //TODO: Worth optimizing with a proper hash-table?
282 for (int i = 0; i < size; ++i) {
283 if (entries[i].code == code && entries[i].value == value) return i;
284 }
285 return Nil;
286 }
287
288 bool add(const int code, const int value)
289 {
290 if (size == MaxDictEntries) return false;
291 entries[size].code = code;
292 entries[size].value = value;
293 ++size;
294 return true;
295 }
296
297 bool flush(int & codeBitsWidth)
298 {
299 if (size == (1 << codeBitsWidth)) {
300 ++codeBitsWidth;
301 if (codeBitsWidth > MaxDictBits) {
302 //Clear the dictionary (except the first 256 byte entries).
303 codeBitsWidth = StartBits;
304 size = FirstCode;
305 return true;
306 }
307 }
308 return false;
309 }
310 };
311
312
313 static bool outputByte(int code, uint8_t*& output, int outputSizeBytes, int& bytesDecodedSoFar)
314 {
315 if (bytesDecodedSoFar >= outputSizeBytes) return false;
316 *output++ = static_cast<uint8_t>(code);
317 ++bytesDecodedSoFar;
318 return true;
319 }
320
321
322 static bool outputSequence(const Dictionary& dict, int code, uint8_t*& output, int outputSizeBytes, int& bytesDecodedSoFar, int& firstByte)
323 {
324 /* A sequence is stored backwards, so we have to write
325 it to a temp then output the buffer in reverse. */
326 int i = 0;
327 uint8_t sequence[MaxDictEntries];
328
329 do {
330 sequence[i++] = dict.entries[code].value;
331 code = dict.entries[code].code;
332 } while (code >= 0);
333
334 firstByte = sequence[--i];
335
336 for (; i >= 0; --i) {
337 if (!outputByte(sequence[i], output, outputSizeBytes, bytesDecodedSoFar)) return false;
338 }
339 return true;
340 }
341
342
343 uint8_t* lzwDecode(const uint8_t* compressed, uint32_t compressedSizeBytes, uint32_t compressedSizeBits, uint32_t uncompressedSizeBytes)
344 {
345 int code = Nil;
346 int prevCode = Nil;
347 int firstByte = 0;
348 int bytesDecoded = 0;
349 int codeBitsWidth = StartBits;
350 auto uncompressed = (uint8_t*) malloc(sizeof(uint8_t) * uncompressedSizeBytes);
351 auto ptr = uncompressed;
352
353 /* We'll reconstruct the dictionary based on the bit stream codes.
354 Unlike Huffman encoding, we don't store the dictionary as a prefix to the data. */
355 Dictionary dictionary;
356 BitStreamReader bitStream(compressed, compressedSizeBytes, compressedSizeBits);
357
358 /* We check to avoid an overflow of the user buffer.
359 If the buffer is smaller than the decompressed size, we break the loop and return the current decompression count. */
360 while (!bitStream.isEndOfStream()) {
361 code = static_cast<int>(bitStream.readBitsU64(codeBitsWidth));
362
363 if (prevCode == Nil) {
364 if (!outputByte(code, ptr, uncompressedSizeBytes, bytesDecoded)) break;
365 firstByte = code;
366 prevCode = code;
367 continue;
368 }
369 if (code >= dictionary.size) {
370 if (!outputSequence(dictionary, prevCode, ptr, uncompressedSizeBytes, bytesDecoded, firstByte)) break;
371 if (!outputByte(firstByte, ptr, uncompressedSizeBytes, bytesDecoded)) break;
372 } else if (!outputSequence(dictionary, code, ptr, uncompressedSizeBytes, bytesDecoded, firstByte)) break;
373
374 dictionary.add(prevCode, firstByte);
375 if (dictionary.flush(codeBitsWidth)) prevCode = Nil;
376 else prevCode = code;
377 }
378
379 return uncompressed;
380 }
381
382
383 uint8_t* lzwEncode(const uint8_t* uncompressed, uint32_t uncompressedSizeBytes, uint32_t* compressedSizeBytes, uint32_t* compressedSizeBits)
384 {
385 //LZW encoding context:
386 int code = Nil;
387 int codeBitsWidth = StartBits;
388 Dictionary dictionary;
389
390 //Output bit stream we write to. This will allocate memory as needed to accommodate the encoded data.
391 BitStreamWriter bitStream;
392
393 for (; uncompressedSizeBytes > 0; --uncompressedSizeBytes, ++uncompressed) {
394 const int value = *uncompressed;
395 const int index = dictionary.findIndex(code, value);
396
397 if (index != Nil) {
398 code = index;
399 continue;
400 }
401
402 //Write the dictionary code using the minimum bit-with:
403 bitStream.appendBitsU64(code, codeBitsWidth);
404
405 //Flush it when full so we can restart the sequences.
406 if (!dictionary.flush(codeBitsWidth)) {
407 //There's still space for this sequence.
408 dictionary.add(code, value);
409 }
410 code = value;
411 }
412
413 //Residual code at the end:
414 if (code != Nil) bitStream.appendBitsU64(code, codeBitsWidth);
415
416 //Pass ownership of the compressed data buffer to the user pointer:
417 *compressedSizeBytes = bitStream.getByteCount();
418 *compressedSizeBits = bitStream.numBitsWritten;
419
420 return bitStream.release();
421 }
422
423
424 /************************************************************************/
425 /* B64 Implementation */
426 /************************************************************************/
427
428
429 size_t b64Decode(const char* encoded, const size_t len, char** decoded)
430 {
431 static constexpr const char B64_INDEX[256] =
432 {
433 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
434 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
435 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55, 56, 57,
436 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6,
437 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
438 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
439 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
440 };
441
442
443 if (!decoded || !encoded || len == 0) return 0;
444
445 auto reserved = 3 * (1 + (len >> 2)) + 1;
446 auto output = static_cast<char*>(malloc(reserved * sizeof(char)));
447 if (!output) return 0;
448 output[reserved - 1] = '\0';
449
450 size_t idx = 0;
451
452 while (*encoded && *(encoded + 1)) {
453 if (*encoded <= 0x20) {
454 ++encoded;
455 continue;
456 }
457
458 auto value1 = B64_INDEX[(size_t)encoded[0]];
459 auto value2 = B64_INDEX[(size_t)encoded[1]];
460 output[idx++] = (value1 << 2) + ((value2 & 0x30) >> 4);
461
462 if (!encoded[2] || encoded[3] < 0 || encoded[2] == '=' || encoded[2] == '.') break;
463 auto value3 = B64_INDEX[(size_t)encoded[2]];
464 output[idx++] = ((value2 & 0x0f) << 4) + ((value3 & 0x3c) >> 2);
465
466 if (!encoded[3] || encoded[3] < 0 || encoded[3] == '=' || encoded[3] == '.') break;
467 auto value4 = B64_INDEX[(size_t)encoded[3]];
468 output[idx++] = ((value3 & 0x03) << 6) + value4;
469 encoded += 4;
470 }
471 *decoded = output;
472 return idx;
473 }
474
475
476 /************************************************************************/
477 /* DJB2 Implementation */
478 /************************************************************************/
479
480 unsigned long djb2Encode(const char* str)
481 {
482 if (!str) return 0;
483
484 unsigned long hash = 5381;
485 int c;
486
487 while ((c = *str++)) {
488 hash = ((hash << 5) + hash) + c; // hash * 33 + c
489 }
490 return hash;
491 }
492
493 }