1 /*
2 LodePNG version 20160124
3
4 Copyright (c) 2005-2016 Lode Vandevenne
5
6 This software is provided 'as-is', without any express or implied
7 warranty. In no event will the authors be held liable for any damages
8 arising from the use of this software.
9
10 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications, and to alter it and redistribute it
12 freely, subject to the following restrictions:
13
14 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required.
18
19 2. Altered source versions must be plainly marked as such, and must not be
20 misrepresented as being the original software.
21
22 3. This notice may not be removed or altered from any source
23 distribution.
24 */
25
26 /*
27 The manual and changelog are in the header file "lodepng.h"
28 Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
29 */
30
31 #include "lodepng.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35
36 #ifdef LODEPNG_COMPILE_CPP
37 #include <fstream>
38 #endif /*LODEPNG_COMPILE_CPP*/
39
40 #if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
41 #pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
42 #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
43 #endif /*_MSC_VER */
44 namespace lpng {
45 const char* LODEPNG_VERSION_STRING = "20160124";
46
47 /*
48 This source file is built up in the following large parts. The code sections
49 with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
50 -Tools for C and common code for PNG and Zlib
51 -C Code for Zlib (huffman, deflate, ...)
52 -C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
53 -The C++ wrapper around all of the above
54 */
55
56 /*The malloc, realloc and free functions defined here with "lodepng_" in front
57 of the name, so that you can easily change them to others related to your
58 platform if needed. Everything else in the code calls these. Pass
59 -DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
60 #define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
61 define them in your own project's source files without needing to change
62 lodepng source code. Don't forget to remove "static" if you copypaste them
63 from here.*/
64
65 #ifdef LODEPNG_COMPILE_ALLOCATORS
lodepng_malloc(size_t size)66 static void* lodepng_malloc(size_t size)
67 {
68 return malloc(size);
69 }
70
lodepng_realloc(void * ptr,size_t new_size)71 static void* lodepng_realloc(void* ptr, size_t new_size)
72 {
73 return realloc(ptr, new_size);
74 }
75
lodepng_free(void * ptr)76 static void lodepng_free(void* ptr)
77 {
78 free(ptr);
79 }
80 #else /*LODEPNG_COMPILE_ALLOCATORS*/
81 void* lodepng_malloc(size_t size);
82 void* lodepng_realloc(void* ptr, size_t new_size);
83 void lodepng_free(void* ptr);
84 #endif /*LODEPNG_COMPILE_ALLOCATORS*/
85
86 /* ////////////////////////////////////////////////////////////////////////// */
87 /* ////////////////////////////////////////////////////////////////////////// */
88 /* // Tools for C, and common code for PNG and Zlib. // */
89 /* ////////////////////////////////////////////////////////////////////////// */
90 /* ////////////////////////////////////////////////////////////////////////// */
91
92 /*
93 Often in case of an error a value is assigned to a variable and then it breaks
94 out of a loop (to go to the cleanup phase of a function). This macro does that.
95 It makes the error handling code shorter and more readable.
96
97 Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
98 */
99 #define CERROR_BREAK(errorvar, code)\
100 {\
101 errorvar = code;\
102 break;\
103 }
104
105 /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
106 #define ERROR_BREAK(code) CERROR_BREAK(error, code)
107
108 /*Set error var to the error code, and return it.*/
109 #define CERROR_RETURN_ERROR(errorvar, code)\
110 {\
111 errorvar = code;\
112 return code;\
113 }
114
115 /*Try the code, if it returns error, also return the error.*/
116 #define CERROR_TRY_RETURN(call)\
117 {\
118 unsigned error = call;\
119 if(error) return error;\
120 }
121
122 /*Set error var to the error code, and return from the void function.*/
123 #define CERROR_RETURN(errorvar, code)\
124 {\
125 errorvar = code;\
126 return;\
127 }
128
129 /*
130 About uivector, ucvector and string:
131 -All of them wrap dynamic arrays or text strings in a similar way.
132 -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
133 -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
134 -They're not used in the interface, only internally in this file as static functions.
135 -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
136 */
137
138 #ifdef LODEPNG_COMPILE_ZLIB
139 /*dynamic vector of unsigned ints*/
140 typedef struct uivector
141 {
142 unsigned* data;
143 size_t size; /*size in number of unsigned longs*/
144 size_t allocsize; /*allocated size in bytes*/
145 } uivector;
146
uivector_cleanup(void * p)147 static void uivector_cleanup(void* p)
148 {
149 ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
150 lodepng_free(((uivector*)p)->data);
151 ((uivector*)p)->data = NULL;
152 }
153
154 /*returns 1 if success, 0 if failure ==> nothing done*/
uivector_reserve(uivector * p,size_t allocsize)155 static unsigned uivector_reserve(uivector* p, size_t allocsize)
156 {
157 if(allocsize > p->allocsize)
158 {
159 size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
160 void* data = lodepng_realloc(p->data, newsize);
161 if(data)
162 {
163 p->allocsize = newsize;
164 p->data = (unsigned*)data;
165 }
166 else return 0; /*error: not enough memory*/
167 }
168 return 1;
169 }
170
171 /*returns 1 if success, 0 if failure ==> nothing done*/
uivector_resize(uivector * p,size_t size)172 static unsigned uivector_resize(uivector* p, size_t size)
173 {
174 if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
175 p->size = size;
176 return 1; /*success*/
177 }
178
179 /*resize and give all new elements the value*/
uivector_resizev(uivector * p,size_t size,unsigned value)180 static unsigned uivector_resizev(uivector* p, size_t size, unsigned value)
181 {
182 size_t oldsize = p->size, i;
183 if(!uivector_resize(p, size)) return 0;
184 for(i = oldsize; i < size; ++i) p->data[i] = value;
185 return 1;
186 }
187
uivector_init(uivector * p)188 static void uivector_init(uivector* p)
189 {
190 p->data = NULL;
191 p->size = p->allocsize = 0;
192 }
193
194 #ifdef LODEPNG_COMPILE_ENCODER
195 /*returns 1 if success, 0 if failure ==> nothing done*/
uivector_push_back(uivector * p,unsigned c)196 static unsigned uivector_push_back(uivector* p, unsigned c)
197 {
198 if(!uivector_resize(p, p->size + 1)) return 0;
199 p->data[p->size - 1] = c;
200 return 1;
201 }
202 #endif /*LODEPNG_COMPILE_ENCODER*/
203 #endif /*LODEPNG_COMPILE_ZLIB*/
204
205 /* /////////////////////////////////////////////////////////////////////////// */
206
207 /*dynamic vector of unsigned chars*/
208 typedef struct ucvector
209 {
210 unsigned char* data;
211 size_t size; /*used size*/
212 size_t allocsize; /*allocated size*/
213 } ucvector;
214
215 /*returns 1 if success, 0 if failure ==> nothing done*/
ucvector_reserve(ucvector * p,size_t allocsize)216 static unsigned ucvector_reserve(ucvector* p, size_t allocsize)
217 {
218 if(allocsize > p->allocsize)
219 {
220 size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
221 void* data = lodepng_realloc(p->data, newsize);
222 if(data)
223 {
224 p->allocsize = newsize;
225 p->data = (unsigned char*)data;
226 }
227 else return 0; /*error: not enough memory*/
228 }
229 return 1;
230 }
231
232 /*returns 1 if success, 0 if failure ==> nothing done*/
ucvector_resize(ucvector * p,size_t size)233 static unsigned ucvector_resize(ucvector* p, size_t size)
234 {
235 if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
236 p->size = size;
237 return 1; /*success*/
238 }
239
240 #ifdef LODEPNG_COMPILE_PNG
241
ucvector_cleanup(void * p)242 static void ucvector_cleanup(void* p)
243 {
244 ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
245 lodepng_free(((ucvector*)p)->data);
246 ((ucvector*)p)->data = NULL;
247 }
248
ucvector_init(ucvector * p)249 static void ucvector_init(ucvector* p)
250 {
251 p->data = NULL;
252 p->size = p->allocsize = 0;
253 }
254 #endif /*LODEPNG_COMPILE_PNG*/
255
256 #ifdef LODEPNG_COMPILE_ZLIB
257 /*you can both convert from vector to buffer&size and vica versa. If you use
258 init_buffer to take over a buffer and size, it is not needed to use cleanup*/
ucvector_init_buffer(ucvector * p,unsigned char * buffer,size_t size)259 static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size)
260 {
261 p->data = buffer;
262 p->allocsize = p->size = size;
263 }
264 #endif /*LODEPNG_COMPILE_ZLIB*/
265
266 #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
267 /*returns 1 if success, 0 if failure ==> nothing done*/
ucvector_push_back(ucvector * p,unsigned char c)268 static unsigned ucvector_push_back(ucvector* p, unsigned char c)
269 {
270 if(!ucvector_resize(p, p->size + 1)) return 0;
271 p->data[p->size - 1] = c;
272 return 1;
273 }
274 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
275
276
277 /* ////////////////////////////////////////////////////////////////////////// */
278
279 #ifdef LODEPNG_COMPILE_PNG
280 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
281 /*returns 1 if success, 0 if failure ==> nothing done*/
string_resize(char ** out,size_t size)282 static unsigned string_resize(char** out, size_t size)
283 {
284 char* data = (char*)lodepng_realloc(*out, size + 1);
285 if(data)
286 {
287 data[size] = 0; /*null termination char*/
288 *out = data;
289 }
290 return data != 0;
291 }
292
293 /*init a {char*, size_t} pair for use as string*/
string_init(char ** out)294 static void string_init(char** out)
295 {
296 *out = NULL;
297 string_resize(out, 0);
298 }
299
300 /*free the above pair again*/
string_cleanup(char ** out)301 static void string_cleanup(char** out)
302 {
303 lodepng_free(*out);
304 *out = NULL;
305 }
306
string_set(char ** out,const char * in)307 static void string_set(char** out, const char* in)
308 {
309 size_t insize = strlen(in), i;
310 if(string_resize(out, insize))
311 {
312 for(i = 0; i != insize; ++i)
313 {
314 (*out)[i] = in[i];
315 }
316 }
317 }
318 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
319 #endif /*LODEPNG_COMPILE_PNG*/
320
321 /* ////////////////////////////////////////////////////////////////////////// */
322
lodepng_read32bitInt(const unsigned char * buffer)323 unsigned lodepng_read32bitInt(const unsigned char* buffer)
324 {
325 return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
326 }
327
328 #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
329 /*buffer must have at least 4 allocated bytes available*/
lodepng_set32bitInt(unsigned char * buffer,unsigned value)330 static void lodepng_set32bitInt(unsigned char* buffer, unsigned value)
331 {
332 buffer[0] = (unsigned char)((value >> 24) & 0xff);
333 buffer[1] = (unsigned char)((value >> 16) & 0xff);
334 buffer[2] = (unsigned char)((value >> 8) & 0xff);
335 buffer[3] = (unsigned char)((value ) & 0xff);
336 }
337 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
338
339 #ifdef LODEPNG_COMPILE_ENCODER
lodepng_add32bitInt(ucvector * buffer,unsigned value)340 static void lodepng_add32bitInt(ucvector* buffer, unsigned value)
341 {
342 ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
343 lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
344 }
345 #endif /*LODEPNG_COMPILE_ENCODER*/
346
347 /* ////////////////////////////////////////////////////////////////////////// */
348 /* / File IO / */
349 /* ////////////////////////////////////////////////////////////////////////// */
350
351 #ifdef LODEPNG_COMPILE_DISK
352
lodepng_load_file(unsigned char ** out,size_t * outsize,const char * filename)353 unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename)
354 {
355 FILE* file;
356 long size;
357
358 /*provide some proper output values if error will happen*/
359 *out = 0;
360 *outsize = 0;
361
362 file = fopen(filename, "rb");
363 if(!file) return 78;
364
365 /*get filesize:*/
366 fseek(file , 0 , SEEK_END);
367 size = ftell(file);
368 rewind(file);
369
370 /*read contents of the file into the vector*/
371 *outsize = 0;
372 *out = (unsigned char*)lodepng_malloc((size_t)size);
373 if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file);
374
375 fclose(file);
376 if(!(*out) && size) return 83; /*the above malloc failed*/
377 return 0;
378 }
379
380 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
lodepng_save_file(const unsigned char * buffer,size_t buffersize,const char * filename)381 unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename)
382 {
383 FILE* file;
384 file = fopen(filename, "wb" );
385 if(!file) return 79;
386 fwrite((char*)buffer , 1 , buffersize, file);
387 fclose(file);
388 return 0;
389 }
390
391 #endif /*LODEPNG_COMPILE_DISK*/
392
393 /* ////////////////////////////////////////////////////////////////////////// */
394 /* ////////////////////////////////////////////////////////////////////////// */
395 /* // End of common code and tools. Begin of Zlib related code. // */
396 /* ////////////////////////////////////////////////////////////////////////// */
397 /* ////////////////////////////////////////////////////////////////////////// */
398
399 #ifdef LODEPNG_COMPILE_ZLIB
400 #ifdef LODEPNG_COMPILE_ENCODER
401 /*TODO: this ignores potential out of memory errors*/
402 #define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\
403 {\
404 /*add a new byte at the end*/\
405 if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\
406 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\
407 (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
408 ++(*bitpointer);\
409 }
410
addBitsToStream(size_t * bitpointer,ucvector * bitstream,unsigned value,size_t nbits)411 static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
412 {
413 size_t i;
414 for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
415 }
416
addBitsToStreamReversed(size_t * bitpointer,ucvector * bitstream,unsigned value,size_t nbits)417 static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
418 {
419 size_t i;
420 for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
421 }
422 #endif /*LODEPNG_COMPILE_ENCODER*/
423
424 #ifdef LODEPNG_COMPILE_DECODER
425
426 #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
427
readBitFromStream(size_t * bitpointer,const unsigned char * bitstream)428 static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream)
429 {
430 unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
431 ++(*bitpointer);
432 return result;
433 }
434
readBitsFromStream(size_t * bitpointer,const unsigned char * bitstream,size_t nbits)435 static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
436 {
437 unsigned result = 0, i;
438 for(i = 0; i != nbits; ++i)
439 {
440 result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
441 ++(*bitpointer);
442 }
443 return result;
444 }
445 #endif /*LODEPNG_COMPILE_DECODER*/
446
447 /* ////////////////////////////////////////////////////////////////////////// */
448 /* / Deflate - Huffman / */
449 /* ////////////////////////////////////////////////////////////////////////// */
450
451 #define FIRST_LENGTH_CODE_INDEX 257
452 #define LAST_LENGTH_CODE_INDEX 285
453 /*256 literals, the end code, some length codes, and 2 unused codes*/
454 #define NUM_DEFLATE_CODE_SYMBOLS 288
455 /*the distance codes have their own symbols, 30 used, 2 unused*/
456 #define NUM_DISTANCE_SYMBOLS 32
457 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
458 #define NUM_CODE_LENGTH_CODES 19
459
460 /*the base lengths represented by codes 257-285*/
461 static const unsigned LENGTHBASE[29]
462 = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
463 67, 83, 99, 115, 131, 163, 195, 227, 258};
464
465 /*the extra bits used by codes 257-285 (added to base length)*/
466 static const unsigned LENGTHEXTRA[29]
467 = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
468 4, 4, 4, 4, 5, 5, 5, 5, 0};
469
470 /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
471 static const unsigned DISTANCEBASE[30]
472 = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
473 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
474
475 /*the extra bits of backwards distances (added to base)*/
476 static const unsigned DISTANCEEXTRA[30]
477 = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
478 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
479
480 /*the order in which "code length alphabet code lengths" are stored, out of this
481 the huffman tree of the dynamic huffman tree lengths is generated*/
482 static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
483 = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
484
485 /* ////////////////////////////////////////////////////////////////////////// */
486
487 /*
488 Huffman tree struct, containing multiple representations of the tree
489 */
490 typedef struct HuffmanTree
491 {
492 unsigned* tree2d;
493 unsigned* tree1d;
494 unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
495 unsigned maxbitlen; /*maximum number of bits a single code can get*/
496 unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
497 } HuffmanTree;
498
499 /*function used for debug purposes to draw the tree in ascii art with C++*/
500 /*
501 static void HuffmanTree_draw(HuffmanTree* tree)
502 {
503 std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
504 for(size_t i = 0; i != tree->tree1d.size; ++i)
505 {
506 if(tree->lengths.data[i])
507 std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
508 }
509 std::cout << std::endl;
510 }*/
511
HuffmanTree_init(HuffmanTree * tree)512 static void HuffmanTree_init(HuffmanTree* tree)
513 {
514 tree->tree2d = 0;
515 tree->tree1d = 0;
516 tree->lengths = 0;
517 }
518
HuffmanTree_cleanup(HuffmanTree * tree)519 static void HuffmanTree_cleanup(HuffmanTree* tree)
520 {
521 lodepng_free(tree->tree2d);
522 lodepng_free(tree->tree1d);
523 lodepng_free(tree->lengths);
524 }
525
526 /*the tree representation used by the decoder. return value is error*/
HuffmanTree_make2DTree(HuffmanTree * tree)527 static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
528 {
529 unsigned nodefilled = 0; /*up to which node it is filled*/
530 unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
531 unsigned n, i;
532
533 tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
534 if(!tree->tree2d) return 83; /*alloc fail*/
535
536 /*
537 convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
538 uninited, a value >= numcodes is an address to another bit, a value < numcodes
539 is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
540 many columns as codes - 1.
541 A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
542 Here, the internal nodes are stored (what their 0 and 1 option point to).
543 There is only memory for such good tree currently, if there are more nodes
544 (due to too long length codes), error 55 will happen
545 */
546 for(n = 0; n < tree->numcodes * 2; ++n)
547 {
548 tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
549 }
550
551 for(n = 0; n < tree->numcodes; ++n) /*the codes*/
552 {
553 for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/
554 {
555 unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
556 /*oversubscribed, see comment in lodepng_error_text*/
557 if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55;
558 if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
559 {
560 if(i + 1 == tree->lengths[n]) /*last bit*/
561 {
562 tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
563 treepos = 0;
564 }
565 else
566 {
567 /*put address of the next step in here, first that address has to be found of course
568 (it's just nodefilled + 1)...*/
569 ++nodefilled;
570 /*addresses encoded with numcodes added to it*/
571 tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
572 treepos = nodefilled;
573 }
574 }
575 else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
576 }
577 }
578
579 for(n = 0; n < tree->numcodes * 2; ++n)
580 {
581 if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
582 }
583
584 return 0;
585 }
586
587 /*
588 Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
589 numcodes, lengths and maxbitlen must already be filled in correctly. return
590 value is error.
591 */
HuffmanTree_makeFromLengths2(HuffmanTree * tree)592 static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
593 {
594 uivector blcount;
595 uivector nextcode;
596 unsigned error = 0;
597 unsigned bits, n;
598
599 uivector_init(&blcount);
600 uivector_init(&nextcode);
601
602 tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
603 if(!tree->tree1d) error = 83; /*alloc fail*/
604
605 if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
606 || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
607 error = 83; /*alloc fail*/
608
609 if(!error)
610 {
611 /*step 1: count number of instances of each code length*/
612 for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]];
613 /*step 2: generate the nextcode values*/
614 for(bits = 1; bits <= tree->maxbitlen; ++bits)
615 {
616 nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
617 }
618 /*step 3: generate all the codes*/
619 for(n = 0; n != tree->numcodes; ++n)
620 {
621 if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
622 }
623 }
624
625 uivector_cleanup(&blcount);
626 uivector_cleanup(&nextcode);
627
628 if(!error) return HuffmanTree_make2DTree(tree);
629 else return error;
630 }
631
632 /*
633 given the code lengths (as stored in the PNG file), generate the tree as defined
634 by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
635 return value is error.
636 */
HuffmanTree_makeFromLengths(HuffmanTree * tree,const unsigned * bitlen,size_t numcodes,unsigned maxbitlen)637 static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
638 size_t numcodes, unsigned maxbitlen)
639 {
640 unsigned i;
641 tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
642 if(!tree->lengths) return 83; /*alloc fail*/
643 for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
644 tree->numcodes = (unsigned)numcodes; /*number of symbols*/
645 tree->maxbitlen = maxbitlen;
646 return HuffmanTree_makeFromLengths2(tree);
647 }
648
649 #ifdef LODEPNG_COMPILE_ENCODER
650
651 /*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
652 Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
653
654 /*chain node for boundary package merge*/
655 typedef struct BPMNode
656 {
657 int weight; /*the sum of all weights in this chain*/
658 unsigned index; /*index of this leaf node (called "count" in the paper)*/
659 struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
660 int in_use;
661 } BPMNode;
662
663 /*lists of chains*/
664 typedef struct BPMLists
665 {
666 /*memory pool*/
667 unsigned memsize;
668 BPMNode* memory;
669 unsigned numfree;
670 unsigned nextfree;
671 BPMNode** freelist;
672 /*two heads of lookahead chains per list*/
673 unsigned listsize;
674 BPMNode** chains0;
675 BPMNode** chains1;
676 } BPMLists;
677
678 /*creates a new chain node with the given parameters, from the memory in the lists */
bpmnode_create(BPMLists * lists,int weight,unsigned index,BPMNode * tail)679 static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail)
680 {
681 unsigned i;
682 BPMNode* result;
683
684 /*memory full, so garbage collect*/
685 if(lists->nextfree >= lists->numfree)
686 {
687 /*mark only those that are in use*/
688 for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
689 for(i = 0; i != lists->listsize; ++i)
690 {
691 BPMNode* node;
692 for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
693 for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
694 }
695 /*collect those that are free*/
696 lists->numfree = 0;
697 for(i = 0; i != lists->memsize; ++i)
698 {
699 if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
700 }
701 lists->nextfree = 0;
702 }
703
704 result = lists->freelist[lists->nextfree++];
705 result->weight = weight;
706 result->index = index;
707 result->tail = tail;
708 return result;
709 }
710
bpmnode_compare(const void * a,const void * b)711 static int bpmnode_compare(const void* a, const void* b)
712 {
713 int wa = ((const BPMNode*)a)->weight;
714 int wb = ((const BPMNode*)b)->weight;
715 if(wa < wb) return -1;
716 if(wa > wb) return 1;
717 /*make the qsort a stable sort*/
718 return ((const BPMNode*)a)->index < ((const BPMNode*)b)->index ? 1 : -1;
719 }
720
721 /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
boundaryPM(BPMLists * lists,BPMNode * leaves,size_t numpresent,int c,int num)722 static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num)
723 {
724 unsigned lastindex = lists->chains1[c]->index;
725
726 if(c == 0)
727 {
728 if(lastindex >= numpresent) return;
729 lists->chains0[c] = lists->chains1[c];
730 lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
731 }
732 else
733 {
734 /*sum of the weights of the head nodes of the previous lookahead chains.*/
735 int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
736 lists->chains0[c] = lists->chains1[c];
737 if(lastindex < numpresent && sum > leaves[lastindex].weight)
738 {
739 lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
740 return;
741 }
742 lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
743 /*in the end we are only interested in the chain of the last list, so no
744 need to recurse if we're at the last one (this gives measurable speedup)*/
745 if(num + 1 < (int)(2 * numpresent - 2))
746 {
747 boundaryPM(lists, leaves, numpresent, c - 1, num);
748 boundaryPM(lists, leaves, numpresent, c - 1, num);
749 }
750 }
751 }
752
lodepng_huffman_code_lengths(unsigned * lengths,const unsigned * frequencies,size_t numcodes,unsigned maxbitlen)753 unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
754 size_t numcodes, unsigned maxbitlen)
755 {
756 unsigned error = 0;
757 unsigned i;
758 size_t numpresent = 0; /*number of symbols with non-zero frequency*/
759 BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
760
761 if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
762 if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/
763
764 leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
765 if(!leaves) return 83; /*alloc fail*/
766
767 for(i = 0; i != numcodes; ++i)
768 {
769 if(frequencies[i] > 0)
770 {
771 leaves[numpresent].weight = (int)frequencies[i];
772 leaves[numpresent].index = i;
773 ++numpresent;
774 }
775 }
776
777 for(i = 0; i != numcodes; ++i) lengths[i] = 0;
778
779 /*ensure at least two present symbols. There should be at least one symbol
780 according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
781 make these work as well ensure there are at least two symbols. The
782 Package-Merge code below also doesn't work correctly if there's only one
783 symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
784 if(numpresent == 0)
785 {
786 lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
787 }
788 else if(numpresent == 1)
789 {
790 lengths[leaves[0].index] = 1;
791 lengths[leaves[0].index == 0 ? 1 : 0] = 1;
792 }
793 else
794 {
795 BPMLists lists;
796 BPMNode* node;
797
798 qsort(leaves, numpresent, sizeof(BPMNode), bpmnode_compare);
799
800 lists.listsize = maxbitlen;
801 lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
802 lists.nextfree = 0;
803 lists.numfree = lists.memsize;
804 lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
805 lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
806 lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
807 lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
808 if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
809
810 if(!error)
811 {
812 for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
813
814 bpmnode_create(&lists, leaves[0].weight, 1, 0);
815 bpmnode_create(&lists, leaves[1].weight, 2, 0);
816
817 for(i = 0; i != lists.listsize; ++i)
818 {
819 lists.chains0[i] = &lists.memory[0];
820 lists.chains1[i] = &lists.memory[1];
821 }
822
823 /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
824 for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
825
826 for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail)
827 {
828 for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
829 }
830 }
831
832 lodepng_free(lists.memory);
833 lodepng_free(lists.freelist);
834 lodepng_free(lists.chains0);
835 lodepng_free(lists.chains1);
836 }
837
838 lodepng_free(leaves);
839 return error;
840 }
841
842 /*Create the Huffman tree given the symbol frequencies*/
HuffmanTree_makeFromFrequencies(HuffmanTree * tree,const unsigned * frequencies,size_t mincodes,size_t numcodes,unsigned maxbitlen)843 static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
844 size_t mincodes, size_t numcodes, unsigned maxbitlen)
845 {
846 unsigned error = 0;
847 while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
848 tree->maxbitlen = maxbitlen;
849 tree->numcodes = (unsigned)numcodes; /*number of symbols*/
850 tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
851 if(!tree->lengths) return 83; /*alloc fail*/
852 /*initialize all lengths to 0*/
853 memset(tree->lengths, 0, numcodes * sizeof(unsigned));
854
855 error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
856 if(!error) error = HuffmanTree_makeFromLengths2(tree);
857 return error;
858 }
859
HuffmanTree_getCode(const HuffmanTree * tree,unsigned index)860 static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
861 {
862 return tree->tree1d[index];
863 }
864
HuffmanTree_getLength(const HuffmanTree * tree,unsigned index)865 static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index)
866 {
867 return tree->lengths[index];
868 }
869 #endif /*LODEPNG_COMPILE_ENCODER*/
870
871 /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
generateFixedLitLenTree(HuffmanTree * tree)872 static unsigned generateFixedLitLenTree(HuffmanTree* tree)
873 {
874 unsigned i, error = 0;
875 unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
876 if(!bitlen) return 83; /*alloc fail*/
877
878 /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
879 for(i = 0; i <= 143; ++i) bitlen[i] = 8;
880 for(i = 144; i <= 255; ++i) bitlen[i] = 9;
881 for(i = 256; i <= 279; ++i) bitlen[i] = 7;
882 for(i = 280; i <= 287; ++i) bitlen[i] = 8;
883
884 error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
885
886 lodepng_free(bitlen);
887 return error;
888 }
889
890 /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
generateFixedDistanceTree(HuffmanTree * tree)891 static unsigned generateFixedDistanceTree(HuffmanTree* tree)
892 {
893 unsigned i, error = 0;
894 unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
895 if(!bitlen) return 83; /*alloc fail*/
896
897 /*there are 32 distance codes, but 30-31 are unused*/
898 for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
899 error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
900
901 lodepng_free(bitlen);
902 return error;
903 }
904
905 #ifdef LODEPNG_COMPILE_DECODER
906
907 /*
908 returns the code, or (unsigned)(-1) if error happened
909 inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
910 */
huffmanDecodeSymbol(const unsigned char * in,size_t * bp,const HuffmanTree * codetree,size_t inbitlength)911 static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
912 const HuffmanTree* codetree, size_t inbitlength)
913 {
914 unsigned treepos = 0, ct;
915 for(;;)
916 {
917 if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
918 /*
919 decode the symbol from the tree. The "readBitFromStream" code is inlined in
920 the expression below because this is the biggest bottleneck while decoding
921 */
922 ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
923 ++(*bp);
924 if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
925 else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
926
927 if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
928 }
929 }
930 #endif /*LODEPNG_COMPILE_DECODER*/
931
932 #ifdef LODEPNG_COMPILE_DECODER
933
934 /* ////////////////////////////////////////////////////////////////////////// */
935 /* / Inflator (Decompressor) / */
936 /* ////////////////////////////////////////////////////////////////////////// */
937
938 /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
getTreeInflateFixed(HuffmanTree * tree_ll,HuffmanTree * tree_d)939 static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
940 {
941 /*TODO: check for out of memory errors*/
942 generateFixedLitLenTree(tree_ll);
943 generateFixedDistanceTree(tree_d);
944 }
945
946 /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
getTreeInflateDynamic(HuffmanTree * tree_ll,HuffmanTree * tree_d,const unsigned char * in,size_t * bp,size_t inlength)947 static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
948 const unsigned char* in, size_t* bp, size_t inlength)
949 {
950 /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
951 unsigned error = 0;
952 unsigned n, HLIT, HDIST, HCLEN, i;
953 size_t inbitlength = inlength * 8;
954
955 /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
956 unsigned* bitlen_ll = 0; /*lit,len code lengths*/
957 unsigned* bitlen_d = 0; /*dist code lengths*/
958 /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
959 unsigned* bitlen_cl = 0;
960 HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
961
962 if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
963
964 /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
965 HLIT = readBitsFromStream(bp, in, 5) + 257;
966 /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
967 HDIST = readBitsFromStream(bp, in, 5) + 1;
968 /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
969 HCLEN = readBitsFromStream(bp, in, 4) + 4;
970
971 if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
972
973 HuffmanTree_init(&tree_cl);
974
975 while(!error)
976 {
977 /*read the code length codes out of 3 * (amount of code length codes) bits*/
978
979 bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
980 if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
981
982 for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i)
983 {
984 if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
985 else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
986 }
987
988 error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
989 if(error) break;
990
991 /*now we can use this tree to read the lengths for the tree that this function will return*/
992 bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
993 bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
994 if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
995 for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
996 for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
997
998 /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
999 i = 0;
1000 while(i < HLIT + HDIST)
1001 {
1002 unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
1003 if(code <= 15) /*a length code*/
1004 {
1005 if(i < HLIT) bitlen_ll[i] = code;
1006 else bitlen_d[i - HLIT] = code;
1007 ++i;
1008 }
1009 else if(code == 16) /*repeat previous*/
1010 {
1011 unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1012 unsigned value; /*set value to the previous code*/
1013
1014 if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1015
1016 if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1017 replength += readBitsFromStream(bp, in, 2);
1018
1019 if(i < HLIT + 1) value = bitlen_ll[i - 1];
1020 else value = bitlen_d[i - HLIT - 1];
1021 /*repeat this value in the next lengths*/
1022 for(n = 0; n < replength; ++n)
1023 {
1024 if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1025 if(i < HLIT) bitlen_ll[i] = value;
1026 else bitlen_d[i - HLIT] = value;
1027 ++i;
1028 }
1029 }
1030 else if(code == 17) /*repeat "0" 3-10 times*/
1031 {
1032 unsigned replength = 3; /*read in the bits that indicate repeat length*/
1033 if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1034 replength += readBitsFromStream(bp, in, 3);
1035
1036 /*repeat this value in the next lengths*/
1037 for(n = 0; n < replength; ++n)
1038 {
1039 if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1040
1041 if(i < HLIT) bitlen_ll[i] = 0;
1042 else bitlen_d[i - HLIT] = 0;
1043 ++i;
1044 }
1045 }
1046 else if(code == 18) /*repeat "0" 11-138 times*/
1047 {
1048 unsigned replength = 11; /*read in the bits that indicate repeat length*/
1049 if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1050 replength += readBitsFromStream(bp, in, 7);
1051
1052 /*repeat this value in the next lengths*/
1053 for(n = 0; n < replength; ++n)
1054 {
1055 if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1056
1057 if(i < HLIT) bitlen_ll[i] = 0;
1058 else bitlen_d[i - HLIT] = 0;
1059 ++i;
1060 }
1061 }
1062 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1063 {
1064 if(code == (unsigned)(-1))
1065 {
1066 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1067 (10=no endcode, 11=wrong jump outside of tree)*/
1068 error = (*bp) > inbitlength ? 10 : 11;
1069 }
1070 else error = 16; /*unexisting code, this can never happen*/
1071 break;
1072 }
1073 }
1074 if(error) break;
1075
1076 if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1077
1078 /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1079 error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
1080 if(error) break;
1081 error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
1082
1083 break; /*end of error-while*/
1084 }
1085
1086 lodepng_free(bitlen_cl);
1087 lodepng_free(bitlen_ll);
1088 lodepng_free(bitlen_d);
1089 HuffmanTree_cleanup(&tree_cl);
1090
1091 return error;
1092 }
1093
1094 /*inflate a block with dynamic of fixed Huffman tree*/
inflateHuffmanBlock(ucvector * out,const unsigned char * in,size_t * bp,size_t * pos,size_t inlength,unsigned btype)1095 static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
1096 size_t* pos, size_t inlength, unsigned btype)
1097 {
1098 unsigned error = 0;
1099 HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
1100 HuffmanTree tree_d; /*the huffman tree for distance codes*/
1101 size_t inbitlength = inlength * 8;
1102
1103 HuffmanTree_init(&tree_ll);
1104 HuffmanTree_init(&tree_d);
1105
1106 if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
1107 else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
1108
1109 while(!error) /*decode all symbols until end reached, breaks at end code*/
1110 {
1111 /*code_ll is literal, length or end code*/
1112 unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
1113 if(code_ll <= 255) /*literal symbol*/
1114 {
1115 /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
1116 if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
1117 out->data[*pos] = (unsigned char)code_ll;
1118 ++(*pos);
1119 }
1120 else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
1121 {
1122 unsigned code_d, distance;
1123 unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
1124 size_t start, forward, backward, length;
1125
1126 /*part 1: get length base*/
1127 length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
1128
1129 /*part 2: get extra bits and add the value of that to length*/
1130 numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
1131 if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1132 length += readBitsFromStream(bp, in, numextrabits_l);
1133
1134 /*part 3: get distance code*/
1135 code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
1136 if(code_d > 29)
1137 {
1138 if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1139 {
1140 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1141 (10=no endcode, 11=wrong jump outside of tree)*/
1142 error = (*bp) > inlength * 8 ? 10 : 11;
1143 }
1144 else error = 18; /*error: invalid distance code (30-31 are never used)*/
1145 break;
1146 }
1147 distance = DISTANCEBASE[code_d];
1148
1149 /*part 4: get extra bits from distance*/
1150 numextrabits_d = DISTANCEEXTRA[code_d];
1151 if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1152 distance += readBitsFromStream(bp, in, numextrabits_d);
1153
1154 /*part 5: fill in all the out[n] values based on the length and dist*/
1155 start = (*pos);
1156 if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
1157 backward = start - distance;
1158
1159 if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
1160 if (distance < length) {
1161 for(forward = 0; forward < length; ++forward)
1162 {
1163 out->data[(*pos)++] = out->data[backward++];
1164 }
1165 } else {
1166 memcpy(out->data + *pos, out->data + backward, length);
1167 *pos += length;
1168 }
1169 }
1170 else if(code_ll == 256)
1171 {
1172 break; /*end code, break the loop*/
1173 }
1174 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1175 {
1176 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1177 (10=no endcode, 11=wrong jump outside of tree)*/
1178 error = ((*bp) > inlength * 8) ? 10 : 11;
1179 break;
1180 }
1181 }
1182
1183 HuffmanTree_cleanup(&tree_ll);
1184 HuffmanTree_cleanup(&tree_d);
1185
1186 return error;
1187 }
1188
inflateNoCompression(ucvector * out,const unsigned char * in,size_t * bp,size_t * pos,size_t inlength)1189 static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength)
1190 {
1191 size_t p;
1192 unsigned LEN, NLEN, n, error = 0;
1193
1194 /*go to first boundary of byte*/
1195 while(((*bp) & 0x7) != 0) ++(*bp);
1196 p = (*bp) / 8; /*byte position*/
1197
1198 /*read LEN (2 bytes) and NLEN (2 bytes)*/
1199 if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/
1200 LEN = in[p] + 256u * in[p + 1]; p += 2;
1201 NLEN = in[p] + 256u * in[p + 1]; p += 2;
1202
1203 /*check if 16-bit NLEN is really the one's complement of LEN*/
1204 if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
1205
1206 if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
1207
1208 /*read the literal data: LEN bytes are now stored in the out buffer*/
1209 if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
1210 for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++];
1211
1212 (*bp) = p * 8;
1213
1214 return error;
1215 }
1216
lodepng_inflatev(ucvector * out,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)1217 static unsigned lodepng_inflatev(ucvector* out,
1218 const unsigned char* in, size_t insize,
1219 const LodePNGDecompressSettings* settings)
1220 {
1221 /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1222 size_t bp = 0;
1223 unsigned BFINAL = 0;
1224 size_t pos = 0; /*byte position in the out buffer*/
1225 unsigned error = 0;
1226
1227 (void)settings;
1228
1229 while(!BFINAL)
1230 {
1231 unsigned BTYPE;
1232 if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
1233 BFINAL = readBitFromStream(&bp, in);
1234 BTYPE = 1u * readBitFromStream(&bp, in);
1235 BTYPE += 2u * readBitFromStream(&bp, in);
1236
1237 if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
1238 else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
1239 else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
1240
1241 if(error) return error;
1242 }
1243
1244 return error;
1245 }
1246
lodepng_inflate(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)1247 unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
1248 const unsigned char* in, size_t insize,
1249 const LodePNGDecompressSettings* settings)
1250 {
1251 unsigned error;
1252 ucvector v;
1253 ucvector_init_buffer(&v, *out, *outsize);
1254 error = lodepng_inflatev(&v, in, insize, settings);
1255 *out = v.data;
1256 *outsize = v.size;
1257 return error;
1258 }
1259
inflate(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)1260 static unsigned inflate(unsigned char** out, size_t* outsize,
1261 const unsigned char* in, size_t insize,
1262 const LodePNGDecompressSettings* settings)
1263 {
1264 if(settings->custom_inflate)
1265 {
1266 return settings->custom_inflate(out, outsize, in, insize, settings);
1267 }
1268 else
1269 {
1270 return lodepng_inflate(out, outsize, in, insize, settings);
1271 }
1272 }
1273
1274 #endif /*LODEPNG_COMPILE_DECODER*/
1275
1276 #ifdef LODEPNG_COMPILE_ENCODER
1277
1278 /* ////////////////////////////////////////////////////////////////////////// */
1279 /* / Deflator (Compressor) / */
1280 /* ////////////////////////////////////////////////////////////////////////// */
1281
1282 static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
1283
1284 /*bitlen is the size in bits of the code*/
addHuffmanSymbol(size_t * bp,ucvector * compressed,unsigned code,unsigned bitlen)1285 static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen)
1286 {
1287 addBitsToStreamReversed(bp, compressed, code, bitlen);
1288 }
1289
1290 /*search the index in the array, that has the largest value smaller than or equal to the given value,
1291 given array must be sorted (if no value is smaller, it returns the size of the given array)*/
searchCodeIndex(const unsigned * array,size_t array_size,size_t value)1292 static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value)
1293 {
1294 /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
1295 size_t left = 1;
1296 size_t right = array_size - 1;
1297
1298 while(left <= right) {
1299 size_t mid = (left + right) >> 1;
1300 if (array[mid] >= value) right = mid - 1;
1301 else left = mid + 1;
1302 }
1303 if(left >= array_size || array[left] > value) left--;
1304 return left;
1305 }
1306
addLengthDistance(uivector * values,size_t length,size_t distance)1307 static void addLengthDistance(uivector* values, size_t length, size_t distance)
1308 {
1309 /*values in encoded vector are those used by deflate:
1310 0-255: literal bytes
1311 256: end
1312 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1313 286-287: invalid*/
1314
1315 unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
1316 unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
1317 unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
1318 unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
1319
1320 uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
1321 uivector_push_back(values, extra_length);
1322 uivector_push_back(values, dist_code);
1323 uivector_push_back(values, extra_distance);
1324 }
1325
1326 /*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
1327 bytes as input because 3 is the minimum match length for deflate*/
1328 static const unsigned HASH_NUM_VALUES = 65536;
1329 static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
1330
1331 typedef struct Hash
1332 {
1333 int* head; /*hash value to head circular pos - can be outdated if went around window*/
1334 /*circular pos to prev circular pos*/
1335 unsigned short* chain;
1336 int* val; /*circular pos to hash value*/
1337
1338 /*TODO: do this not only for zeros but for any repeated byte. However for PNG
1339 it's always going to be the zeros that dominate, so not important for PNG*/
1340 int* headz; /*similar to head, but for chainz*/
1341 unsigned short* chainz; /*those with same amount of zeros*/
1342 unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
1343 } Hash;
1344
hash_init(Hash * hash,unsigned windowsize)1345 static unsigned hash_init(Hash* hash, unsigned windowsize)
1346 {
1347 unsigned i;
1348 hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
1349 hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
1350 hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1351
1352 hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1353 hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
1354 hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1355
1356 if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros)
1357 {
1358 return 83; /*alloc fail*/
1359 }
1360
1361 /*initialize hash table*/
1362 for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
1363 for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
1364 for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
1365
1366 for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
1367 for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
1368
1369 return 0;
1370 }
1371
hash_cleanup(Hash * hash)1372 static void hash_cleanup(Hash* hash)
1373 {
1374 lodepng_free(hash->head);
1375 lodepng_free(hash->val);
1376 lodepng_free(hash->chain);
1377
1378 lodepng_free(hash->zeros);
1379 lodepng_free(hash->headz);
1380 lodepng_free(hash->chainz);
1381 }
1382
1383
1384
getHash(const unsigned char * data,size_t size,size_t pos)1385 static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
1386 {
1387 unsigned result = 0;
1388 if(pos + 2 < size)
1389 {
1390 /*A simple shift and xor hash is used. Since the data of PNGs is dominated
1391 by zeroes due to the filters, a better hash does not have a significant
1392 effect on speed in traversing the chain, and causes more time spend on
1393 calculating the hash.*/
1394 result ^= (unsigned)(data[pos + 0] << 0u);
1395 result ^= (unsigned)(data[pos + 1] << 4u);
1396 result ^= (unsigned)(data[pos + 2] << 8u);
1397 } else {
1398 size_t amount, i;
1399 if(pos >= size) return 0;
1400 amount = size - pos;
1401 for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
1402 }
1403 return result & HASH_BIT_MASK;
1404 }
1405
countZeros(const unsigned char * data,size_t size,size_t pos)1406 static unsigned countZeros(const unsigned char* data, size_t size, size_t pos)
1407 {
1408 const unsigned char* start = data + pos;
1409 const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
1410 if(end > data + size) end = data + size;
1411 data = start;
1412 while(data != end && *data == 0) ++data;
1413 /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1414 return (unsigned)(data - start);
1415 }
1416
1417 /*wpos = pos & (windowsize - 1)*/
updateHashChain(Hash * hash,size_t wpos,unsigned hashval,unsigned short numzeros)1418 static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros)
1419 {
1420 hash->val[wpos] = (int)hashval;
1421 if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
1422 hash->head[hashval] = wpos;
1423
1424 hash->zeros[wpos] = numzeros;
1425 if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
1426 hash->headz[numzeros] = wpos;
1427 }
1428
1429 /*
1430 LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1431 is in the form of unsigned integers with codes representing for example literal bytes, or
1432 length/distance pairs.
1433 It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1434 sliding window (of windowsize) is used, and all past bytes in that window can be used as
1435 the "dictionary". A brute force search through all possible distances would be slow, and
1436 this hash technique is one out of several ways to speed this up.
1437 */
encodeLZ77(uivector * out,Hash * hash,const unsigned char * in,size_t inpos,size_t insize,unsigned windowsize,unsigned minmatch,unsigned nicematch,unsigned lazymatching)1438 static unsigned encodeLZ77(uivector* out, Hash* hash,
1439 const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
1440 unsigned minmatch, unsigned nicematch, unsigned lazymatching)
1441 {
1442 size_t pos;
1443 unsigned i, error = 0;
1444 /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1445 unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
1446 unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
1447
1448 unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
1449 unsigned numzeros = 0;
1450
1451 unsigned offset; /*the offset represents the distance in LZ77 terminology*/
1452 unsigned length;
1453 unsigned lazy = 0;
1454 unsigned lazylength = 0, lazyoffset = 0;
1455 unsigned hashval;
1456 unsigned current_offset, current_length;
1457 unsigned prev_offset;
1458 const unsigned char *lastptr, *foreptr, *backptr;
1459 unsigned hashpos;
1460
1461 if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
1462 if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
1463
1464 if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
1465
1466 for(pos = inpos; pos < insize; ++pos)
1467 {
1468 size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
1469 unsigned chainlength = 0;
1470
1471 hashval = getHash(in, insize, pos);
1472
1473 if(usezeros && hashval == 0)
1474 {
1475 if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1476 else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1477 }
1478 else
1479 {
1480 numzeros = 0;
1481 }
1482
1483 updateHashChain(hash, wpos, hashval, numzeros);
1484
1485 /*the length and offset found for the current position*/
1486 length = 0;
1487 offset = 0;
1488
1489 hashpos = hash->chain[wpos];
1490
1491 lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
1492
1493 /*search for the longest string*/
1494 prev_offset = 0;
1495 for(;;)
1496 {
1497 if(chainlength++ >= maxchainlength) break;
1498 current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize;
1499
1500 if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
1501 prev_offset = current_offset;
1502 if(current_offset > 0)
1503 {
1504 /*test the next characters*/
1505 foreptr = &in[pos];
1506 backptr = &in[pos - current_offset];
1507
1508 /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1509 if(numzeros >= 3)
1510 {
1511 unsigned skip = hash->zeros[hashpos];
1512 if(skip > numzeros) skip = numzeros;
1513 backptr += skip;
1514 foreptr += skip;
1515 }
1516
1517 while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/
1518 {
1519 ++backptr;
1520 ++foreptr;
1521 }
1522 current_length = (unsigned)(foreptr - &in[pos]);
1523
1524 if(current_length > length)
1525 {
1526 length = current_length; /*the longest length*/
1527 offset = current_offset; /*the offset that is related to this longest length*/
1528 /*jump out once a length of max length is found (speed gain). This also jumps
1529 out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
1530 if(current_length >= nicematch) break;
1531 }
1532 }
1533
1534 if(hashpos == hash->chain[hashpos]) break;
1535
1536 if(numzeros >= 3 && length > numzeros)
1537 {
1538 hashpos = hash->chainz[hashpos];
1539 if(hash->zeros[hashpos] != numzeros) break;
1540 }
1541 else
1542 {
1543 hashpos = hash->chain[hashpos];
1544 /*outdated hash value, happens if particular value was not encountered in whole last window*/
1545 if(hash->val[hashpos] != (int)hashval) break;
1546 }
1547 }
1548
1549 if(lazymatching)
1550 {
1551 if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH)
1552 {
1553 lazy = 1;
1554 lazylength = length;
1555 lazyoffset = offset;
1556 continue; /*try the next byte*/
1557 }
1558 if(lazy)
1559 {
1560 lazy = 0;
1561 if(pos == 0) ERROR_BREAK(81);
1562 if(length > lazylength + 1)
1563 {
1564 /*push the previous character as literal*/
1565 if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
1566 }
1567 else
1568 {
1569 length = lazylength;
1570 offset = lazyoffset;
1571 hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1572 hash->headz[numzeros] = -1; /*idem*/
1573 --pos;
1574 }
1575 }
1576 }
1577 if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1578
1579 /*encode it as length/distance pair or literal value*/
1580 if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1581 {
1582 if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1583 }
1584 else if(length < minmatch || (length == 3 && offset > 4096))
1585 {
1586 /*compensate for the fact that longer offsets have more extra bits, a
1587 length of only 3 may be not worth it then*/
1588 if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1589 }
1590 else
1591 {
1592 addLengthDistance(out, length, offset);
1593 for(i = 1; i < length; ++i)
1594 {
1595 ++pos;
1596 wpos = pos & (windowsize - 1);
1597 hashval = getHash(in, insize, pos);
1598 if(usezeros && hashval == 0)
1599 {
1600 if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1601 else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1602 }
1603 else
1604 {
1605 numzeros = 0;
1606 }
1607 updateHashChain(hash, wpos, hashval, numzeros);
1608 }
1609 }
1610 } /*end of the loop through each character of input*/
1611
1612 return error;
1613 }
1614
1615 /* /////////////////////////////////////////////////////////////////////////// */
1616
deflateNoCompression(ucvector * out,const unsigned char * data,size_t datasize)1617 static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize)
1618 {
1619 /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1620 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1621
1622 size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
1623 unsigned datapos = 0;
1624 for(i = 0; i != numdeflateblocks; ++i)
1625 {
1626 unsigned BFINAL, BTYPE, LEN, NLEN;
1627 unsigned char firstbyte;
1628
1629 BFINAL = (i == numdeflateblocks - 1);
1630 BTYPE = 0;
1631
1632 firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
1633 ucvector_push_back(out, firstbyte);
1634
1635 LEN = 65535;
1636 if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
1637 NLEN = 65535 - LEN;
1638
1639 ucvector_push_back(out, (unsigned char)(LEN & 255));
1640 ucvector_push_back(out, (unsigned char)(LEN >> 8));
1641 ucvector_push_back(out, (unsigned char)(NLEN & 255));
1642 ucvector_push_back(out, (unsigned char)(NLEN >> 8));
1643
1644 /*Decompressed data*/
1645 for(j = 0; j < 65535 && datapos < datasize; ++j)
1646 {
1647 ucvector_push_back(out, data[datapos++]);
1648 }
1649 }
1650
1651 return 0;
1652 }
1653
1654 /*
1655 write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1656 tree_ll: the tree for lit and len codes.
1657 tree_d: the tree for distance codes.
1658 */
writeLZ77data(size_t * bp,ucvector * out,const uivector * lz77_encoded,const HuffmanTree * tree_ll,const HuffmanTree * tree_d)1659 static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
1660 const HuffmanTree* tree_ll, const HuffmanTree* tree_d)
1661 {
1662 size_t i = 0;
1663 for(i = 0; i != lz77_encoded->size; ++i)
1664 {
1665 unsigned val = lz77_encoded->data[i];
1666 addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
1667 if(val > 256) /*for a length code, 3 more things have to be added*/
1668 {
1669 unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
1670 unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
1671 unsigned length_extra_bits = lz77_encoded->data[++i];
1672
1673 unsigned distance_code = lz77_encoded->data[++i];
1674
1675 unsigned distance_index = distance_code;
1676 unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
1677 unsigned distance_extra_bits = lz77_encoded->data[++i];
1678
1679 addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
1680 addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
1681 HuffmanTree_getLength(tree_d, distance_code));
1682 addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
1683 }
1684 }
1685 }
1686
1687 /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
deflateDynamic(ucvector * out,size_t * bp,Hash * hash,const unsigned char * data,size_t datapos,size_t dataend,const LodePNGCompressSettings * settings,unsigned final)1688 static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
1689 const unsigned char* data, size_t datapos, size_t dataend,
1690 const LodePNGCompressSettings* settings, unsigned final)
1691 {
1692 unsigned error = 0;
1693
1694 /*
1695 A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1696 literal bytes and length/distance pairs. This is then huffman compressed with
1697 two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1698 another huffman tree is used for the dist values ("d"). These two trees are
1699 stored using their code lengths, and to compress even more these code lengths
1700 are also run-length encoded and huffman compressed. This gives a huffman tree
1701 of code lengths "cl". The code lenghts used to describe this third tree are
1702 the code length code lengths ("clcl").
1703 */
1704
1705 /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1706 uivector lz77_encoded;
1707 HuffmanTree tree_ll; /*tree for lit,len values*/
1708 HuffmanTree tree_d; /*tree for distance codes*/
1709 HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1710 uivector frequencies_ll; /*frequency of lit,len codes*/
1711 uivector frequencies_d; /*frequency of dist codes*/
1712 uivector frequencies_cl; /*frequency of code length codes*/
1713 uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1714 uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1715 /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1716 (these are written as is in the file, it would be crazy to compress these using yet another huffman
1717 tree that needs to be represented by yet another set of code lengths)*/
1718 uivector bitlen_cl;
1719 size_t datasize = dataend - datapos;
1720
1721 /*
1722 Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1723 bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1724 bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1725 bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1726 */
1727
1728 unsigned BFINAL = final;
1729 size_t numcodes_ll, numcodes_d, i;
1730 unsigned HLIT, HDIST, HCLEN;
1731
1732 uivector_init(&lz77_encoded);
1733 HuffmanTree_init(&tree_ll);
1734 HuffmanTree_init(&tree_d);
1735 HuffmanTree_init(&tree_cl);
1736 uivector_init(&frequencies_ll);
1737 uivector_init(&frequencies_d);
1738 uivector_init(&frequencies_cl);
1739 uivector_init(&bitlen_lld);
1740 uivector_init(&bitlen_lld_e);
1741 uivector_init(&bitlen_cl);
1742
1743 /*This while loop never loops due to a break at the end, it is here to
1744 allow breaking out of it to the cleanup phase on error conditions.*/
1745 while(!error)
1746 {
1747 if(settings->use_lz77)
1748 {
1749 error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1750 settings->minmatch, settings->nicematch, settings->lazymatching);
1751 if(error) break;
1752 }
1753 else
1754 {
1755 if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
1756 for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
1757 }
1758
1759 if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
1760 if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
1761
1762 /*Count the frequencies of lit, len and dist codes*/
1763 for(i = 0; i != lz77_encoded.size; ++i)
1764 {
1765 unsigned symbol = lz77_encoded.data[i];
1766 ++frequencies_ll.data[symbol];
1767 if(symbol > 256)
1768 {
1769 unsigned dist = lz77_encoded.data[i + 2];
1770 ++frequencies_d.data[dist];
1771 i += 3;
1772 }
1773 }
1774 frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1775
1776 /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1777 error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
1778 if(error) break;
1779 /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1780 error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
1781 if(error) break;
1782
1783 numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
1784 numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
1785 /*store the code lengths of both generated trees in bitlen_lld*/
1786 for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
1787 for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
1788
1789 /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1790 17 (3-10 zeroes), 18 (11-138 zeroes)*/
1791 for(i = 0; i != (unsigned)bitlen_lld.size; ++i)
1792 {
1793 unsigned j = 0; /*amount of repititions*/
1794 while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
1795
1796 if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/
1797 {
1798 ++j; /*include the first zero*/
1799 if(j <= 10) /*repeat code 17 supports max 10 zeroes*/
1800 {
1801 uivector_push_back(&bitlen_lld_e, 17);
1802 uivector_push_back(&bitlen_lld_e, j - 3);
1803 }
1804 else /*repeat code 18 supports max 138 zeroes*/
1805 {
1806 if(j > 138) j = 138;
1807 uivector_push_back(&bitlen_lld_e, 18);
1808 uivector_push_back(&bitlen_lld_e, j - 11);
1809 }
1810 i += (j - 1);
1811 }
1812 else if(j >= 3) /*repeat code for value other than zero*/
1813 {
1814 size_t k;
1815 unsigned num = j / 6, rest = j % 6;
1816 uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1817 for(k = 0; k < num; ++k)
1818 {
1819 uivector_push_back(&bitlen_lld_e, 16);
1820 uivector_push_back(&bitlen_lld_e, 6 - 3);
1821 }
1822 if(rest >= 3)
1823 {
1824 uivector_push_back(&bitlen_lld_e, 16);
1825 uivector_push_back(&bitlen_lld_e, rest - 3);
1826 }
1827 else j -= rest;
1828 i += j;
1829 }
1830 else /*too short to benefit from repeat code*/
1831 {
1832 uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1833 }
1834 }
1835
1836 /*generate tree_cl, the huffmantree of huffmantrees*/
1837
1838 if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
1839 for(i = 0; i != bitlen_lld_e.size; ++i)
1840 {
1841 ++frequencies_cl.data[bitlen_lld_e.data[i]];
1842 /*after a repeat code come the bits that specify the number of repetitions,
1843 those don't need to be in the frequencies_cl calculation*/
1844 if(bitlen_lld_e.data[i] >= 16) ++i;
1845 }
1846
1847 error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
1848 frequencies_cl.size, frequencies_cl.size, 7);
1849 if(error) break;
1850
1851 if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
1852 for(i = 0; i != tree_cl.numcodes; ++i)
1853 {
1854 /*lenghts of code length tree is in the order as specified by deflate*/
1855 bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
1856 }
1857 while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4)
1858 {
1859 /*remove zeros at the end, but minimum size must be 4*/
1860 if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
1861 }
1862 if(error) break;
1863
1864 /*
1865 Write everything into the output
1866
1867 After the BFINAL and BTYPE, the dynamic block consists out of the following:
1868 - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1869 - (HCLEN+4)*3 bits code lengths of code length alphabet
1870 - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
1871 alphabet, + possible repetition codes 16, 17, 18)
1872 - HDIST + 1 code lengths of distance alphabet (encoded using the code length
1873 alphabet, + possible repetition codes 16, 17, 18)
1874 - compressed data
1875 - 256 (end code)
1876 */
1877
1878 /*Write block type*/
1879 addBitToStream(bp, out, BFINAL);
1880 addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
1881 addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
1882
1883 /*write the HLIT, HDIST and HCLEN values*/
1884 HLIT = (unsigned)(numcodes_ll - 257);
1885 HDIST = (unsigned)(numcodes_d - 1);
1886 HCLEN = (unsigned)bitlen_cl.size - 4;
1887 /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
1888 while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
1889 addBitsToStream(bp, out, HLIT, 5);
1890 addBitsToStream(bp, out, HDIST, 5);
1891 addBitsToStream(bp, out, HCLEN, 4);
1892
1893 /*write the code lenghts of the code length alphabet*/
1894 for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
1895
1896 /*write the lenghts of the lit/len AND the dist alphabet*/
1897 for(i = 0; i != bitlen_lld_e.size; ++i)
1898 {
1899 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
1900 HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
1901 /*extra bits of repeat codes*/
1902 if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
1903 else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
1904 else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
1905 }
1906
1907 /*write the compressed data symbols*/
1908 writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1909 /*error: the length of the end code 256 must be larger than 0*/
1910 if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
1911
1912 /*write the end code*/
1913 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1914
1915 break; /*end of error-while*/
1916 }
1917
1918 /*cleanup*/
1919 uivector_cleanup(&lz77_encoded);
1920 HuffmanTree_cleanup(&tree_ll);
1921 HuffmanTree_cleanup(&tree_d);
1922 HuffmanTree_cleanup(&tree_cl);
1923 uivector_cleanup(&frequencies_ll);
1924 uivector_cleanup(&frequencies_d);
1925 uivector_cleanup(&frequencies_cl);
1926 uivector_cleanup(&bitlen_lld_e);
1927 uivector_cleanup(&bitlen_lld);
1928 uivector_cleanup(&bitlen_cl);
1929
1930 return error;
1931 }
1932
deflateFixed(ucvector * out,size_t * bp,Hash * hash,const unsigned char * data,size_t datapos,size_t dataend,const LodePNGCompressSettings * settings,unsigned final)1933 static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
1934 const unsigned char* data,
1935 size_t datapos, size_t dataend,
1936 const LodePNGCompressSettings* settings, unsigned final)
1937 {
1938 HuffmanTree tree_ll; /*tree for literal values and length codes*/
1939 HuffmanTree tree_d; /*tree for distance codes*/
1940
1941 unsigned BFINAL = final;
1942 unsigned error = 0;
1943 size_t i;
1944
1945 HuffmanTree_init(&tree_ll);
1946 HuffmanTree_init(&tree_d);
1947
1948 generateFixedLitLenTree(&tree_ll);
1949 generateFixedDistanceTree(&tree_d);
1950
1951 addBitToStream(bp, out, BFINAL);
1952 addBitToStream(bp, out, 1); /*first bit of BTYPE*/
1953 addBitToStream(bp, out, 0); /*second bit of BTYPE*/
1954
1955 if(settings->use_lz77) /*LZ77 encoded*/
1956 {
1957 uivector lz77_encoded;
1958 uivector_init(&lz77_encoded);
1959 error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1960 settings->minmatch, settings->nicematch, settings->lazymatching);
1961 if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1962 uivector_cleanup(&lz77_encoded);
1963 }
1964 else /*no LZ77, but still will be Huffman compressed*/
1965 {
1966 for(i = datapos; i < dataend; ++i)
1967 {
1968 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
1969 }
1970 }
1971 /*add END code*/
1972 if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1973
1974 /*cleanup*/
1975 HuffmanTree_cleanup(&tree_ll);
1976 HuffmanTree_cleanup(&tree_d);
1977
1978 return error;
1979 }
1980
lodepng_deflatev(ucvector * out,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)1981 static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
1982 const LodePNGCompressSettings* settings)
1983 {
1984 unsigned error = 0;
1985 size_t i, blocksize, numdeflateblocks;
1986 size_t bp = 0; /*the bit pointer*/
1987 Hash hash;
1988
1989 if(settings->btype > 2) return 61;
1990 else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
1991 else if(settings->btype == 1) blocksize = insize;
1992 else /*if(settings->btype == 2)*/
1993 {
1994 /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
1995 blocksize = insize / 8 + 8;
1996 if(blocksize < 65536) blocksize = 65536;
1997 if(blocksize > 262144) blocksize = 262144;
1998 }
1999
2000 numdeflateblocks = (insize + blocksize - 1) / blocksize;
2001 if(numdeflateblocks == 0) numdeflateblocks = 1;
2002
2003 error = hash_init(&hash, settings->windowsize);
2004 if(error) return error;
2005
2006 for(i = 0; i != numdeflateblocks && !error; ++i)
2007 {
2008 unsigned final = (i == numdeflateblocks - 1);
2009 size_t start = i * blocksize;
2010 size_t end = start + blocksize;
2011 if(end > insize) end = insize;
2012
2013 if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
2014 else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
2015 }
2016
2017 hash_cleanup(&hash);
2018
2019 return error;
2020 }
2021
lodepng_deflate(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)2022 unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
2023 const unsigned char* in, size_t insize,
2024 const LodePNGCompressSettings* settings)
2025 {
2026 unsigned error;
2027 ucvector v;
2028 ucvector_init_buffer(&v, *out, *outsize);
2029 error = lodepng_deflatev(&v, in, insize, settings);
2030 *out = v.data;
2031 *outsize = v.size;
2032 return error;
2033 }
2034
deflate(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)2035 static unsigned deflate(unsigned char** out, size_t* outsize,
2036 const unsigned char* in, size_t insize,
2037 const LodePNGCompressSettings* settings)
2038 {
2039 if(settings->custom_deflate)
2040 {
2041 return settings->custom_deflate(out, outsize, in, insize, settings);
2042 }
2043 else
2044 {
2045 return lodepng_deflate(out, outsize, in, insize, settings);
2046 }
2047 }
2048
2049 #endif /*LODEPNG_COMPILE_DECODER*/
2050
2051 /* ////////////////////////////////////////////////////////////////////////// */
2052 /* / Adler32 */
2053 /* ////////////////////////////////////////////////////////////////////////// */
2054
update_adler32(unsigned adler,const unsigned char * data,unsigned len)2055 static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
2056 {
2057 unsigned s1 = adler & 0xffff;
2058 unsigned s2 = (adler >> 16) & 0xffff;
2059
2060 while(len > 0)
2061 {
2062 /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2063 unsigned amount = len > 5550 ? 5550 : len;
2064 len -= amount;
2065 while(amount > 0)
2066 {
2067 s1 += (*data++);
2068 s2 += s1;
2069 --amount;
2070 }
2071 s1 %= 65521;
2072 s2 %= 65521;
2073 }
2074
2075 return (s2 << 16) | s1;
2076 }
2077
2078 /*Return the adler32 of the bytes data[0..len-1]*/
adler32(const unsigned char * data,unsigned len)2079 static unsigned adler32(const unsigned char* data, unsigned len)
2080 {
2081 return update_adler32(1L, data, len);
2082 }
2083
2084 /* ////////////////////////////////////////////////////////////////////////// */
2085 /* / Zlib / */
2086 /* ////////////////////////////////////////////////////////////////////////// */
2087
2088 #ifdef LODEPNG_COMPILE_DECODER
2089
lodepng_zlib_decompress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)2090 unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2091 size_t insize, const LodePNGDecompressSettings* settings)
2092 {
2093 unsigned error = 0;
2094 unsigned CM, CINFO, FDICT;
2095
2096 if(insize < 2) return 53; /*error, size of zlib data too small*/
2097 /*read information from zlib header*/
2098 if((in[0] * 256 + in[1]) % 31 != 0)
2099 {
2100 /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2101 return 24;
2102 }
2103
2104 CM = in[0] & 15;
2105 CINFO = (in[0] >> 4) & 15;
2106 /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2107 FDICT = (in[1] >> 5) & 1;
2108 /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2109
2110 if(CM != 8 || CINFO > 7)
2111 {
2112 /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2113 return 25;
2114 }
2115 if(FDICT != 0)
2116 {
2117 /*error: the specification of PNG says about the zlib stream:
2118 "The additional flags shall not specify a preset dictionary."*/
2119 return 26;
2120 }
2121
2122 error = inflate(out, outsize, in + 2, insize - 2, settings);
2123 if(error) return error;
2124
2125 if(!settings->ignore_adler32)
2126 {
2127 unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
2128 unsigned checksum = adler32(*out, (unsigned)(*outsize));
2129 if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
2130 }
2131
2132 return 0; /*no error*/
2133 }
2134
zlib_decompress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)2135 static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2136 size_t insize, const LodePNGDecompressSettings* settings)
2137 {
2138 if(settings->custom_zlib)
2139 {
2140 return settings->custom_zlib(out, outsize, in, insize, settings);
2141 }
2142 else
2143 {
2144 return lodepng_zlib_decompress(out, outsize, in, insize, settings);
2145 }
2146 }
2147
2148 #endif /*LODEPNG_COMPILE_DECODER*/
2149
2150 #ifdef LODEPNG_COMPILE_ENCODER
2151
lodepng_zlib_compress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)2152 unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2153 size_t insize, const LodePNGCompressSettings* settings)
2154 {
2155 /*initially, *out must be NULL and outsize 0, if you just give some random *out
2156 that's pointing to a non allocated buffer, this'll crash*/
2157 ucvector outv;
2158 size_t i;
2159 unsigned error;
2160 unsigned char* deflatedata = 0;
2161 size_t deflatesize = 0;
2162
2163 /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2164 unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2165 unsigned FLEVEL = 0;
2166 unsigned FDICT = 0;
2167 unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
2168 unsigned FCHECK = 31 - CMFFLG % 31;
2169 CMFFLG += FCHECK;
2170
2171 /*ucvector-controlled version of the output buffer, for dynamic array*/
2172 ucvector_init_buffer(&outv, *out, *outsize);
2173
2174 ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8));
2175 ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255));
2176
2177 error = deflate(&deflatedata, &deflatesize, in, insize, settings);
2178
2179 if(!error)
2180 {
2181 unsigned ADLER32 = adler32(in, (unsigned)insize);
2182 for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]);
2183 lodepng_free(deflatedata);
2184 lodepng_add32bitInt(&outv, ADLER32);
2185 }
2186
2187 *out = outv.data;
2188 *outsize = outv.size;
2189
2190 return error;
2191 }
2192
2193 /* compress using the default or custom zlib function */
zlib_compress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)2194 static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2195 size_t insize, const LodePNGCompressSettings* settings)
2196 {
2197 if(settings->custom_zlib)
2198 {
2199 return settings->custom_zlib(out, outsize, in, insize, settings);
2200 }
2201 else
2202 {
2203 return lodepng_zlib_compress(out, outsize, in, insize, settings);
2204 }
2205 }
2206
2207 #endif /*LODEPNG_COMPILE_ENCODER*/
2208
2209 #else /*no LODEPNG_COMPILE_ZLIB*/
2210
2211 #ifdef LODEPNG_COMPILE_DECODER
zlib_decompress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGDecompressSettings * settings)2212 static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2213 size_t insize, const LodePNGDecompressSettings* settings)
2214 {
2215 if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2216 return settings->custom_zlib(out, outsize, in, insize, settings);
2217 }
2218 #endif /*LODEPNG_COMPILE_DECODER*/
2219 #ifdef LODEPNG_COMPILE_ENCODER
zlib_compress(unsigned char ** out,size_t * outsize,const unsigned char * in,size_t insize,const LodePNGCompressSettings * settings)2220 static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2221 size_t insize, const LodePNGCompressSettings* settings)
2222 {
2223 if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2224 return settings->custom_zlib(out, outsize, in, insize, settings);
2225 }
2226 #endif /*LODEPNG_COMPILE_ENCODER*/
2227
2228 #endif /*LODEPNG_COMPILE_ZLIB*/
2229
2230 /* ////////////////////////////////////////////////////////////////////////// */
2231
2232 #ifdef LODEPNG_COMPILE_ENCODER
2233
2234 /*this is a good tradeoff between speed and compression ratio*/
2235 #define DEFAULT_WINDOWSIZE 2048
2236
lodepng_compress_settings_init(LodePNGCompressSettings * settings)2237 void lodepng_compress_settings_init(LodePNGCompressSettings* settings)
2238 {
2239 /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2240 settings->btype = 2;
2241 settings->use_lz77 = 1;
2242 settings->windowsize = DEFAULT_WINDOWSIZE;
2243 settings->minmatch = 3;
2244 settings->nicematch = 128;
2245 settings->lazymatching = 1;
2246
2247 settings->custom_zlib = 0;
2248 settings->custom_deflate = 0;
2249 settings->custom_context = 0;
2250 }
2251
2252 const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
2253
2254
2255 #endif /*LODEPNG_COMPILE_ENCODER*/
2256
2257 #ifdef LODEPNG_COMPILE_DECODER
2258
lodepng_decompress_settings_init(LodePNGDecompressSettings * settings)2259 void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
2260 {
2261 settings->ignore_adler32 = 0;
2262
2263 settings->custom_zlib = 0;
2264 settings->custom_inflate = 0;
2265 settings->custom_context = 0;
2266 }
2267
2268 const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
2269
2270 #endif /*LODEPNG_COMPILE_DECODER*/
2271
2272 /* ////////////////////////////////////////////////////////////////////////// */
2273 /* ////////////////////////////////////////////////////////////////////////// */
2274 /* // End of Zlib related code. Begin of PNG related code. // */
2275 /* ////////////////////////////////////////////////////////////////////////// */
2276 /* ////////////////////////////////////////////////////////////////////////// */
2277
2278 #ifdef LODEPNG_COMPILE_PNG
2279
2280 /* ////////////////////////////////////////////////////////////////////////// */
2281 /* / CRC32 / */
2282 /* ////////////////////////////////////////////////////////////////////////// */
2283
2284
2285 #ifndef LODEPNG_NO_COMPILE_CRC
2286 /* CRC polynomial: 0xedb88320 */
2287 static unsigned lodepng_crc32_table[256] = {
2288 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
2289 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
2290 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
2291 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
2292 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
2293 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
2294 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
2295 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
2296 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2297 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
2298 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
2299 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
2300 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
2301 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
2302 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
2303 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
2304 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
2305 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
2306 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
2307 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
2308 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
2309 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
2310 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
2311 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2312 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2313 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2314 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2315 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2316 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2317 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
2318 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
2319 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
2320 };
2321
2322 /*Return the CRC of the bytes buf[0..len-1].*/
lodepng_crc32(const unsigned char * data,size_t length)2323 unsigned lodepng_crc32(const unsigned char* data, size_t length)
2324 {
2325 unsigned r = 0xffffffffu;
2326 size_t i;
2327 for(i = 0; i < length; ++i)
2328 {
2329 r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8);
2330 }
2331 return r ^ 0xffffffffu;
2332 }
2333 #else /* !LODEPNG_NO_COMPILE_CRC */
2334 unsigned lodepng_crc32(const unsigned char* data, size_t length);
2335 #endif /* !LODEPNG_NO_COMPILE_CRC */
2336
2337 /* ////////////////////////////////////////////////////////////////////////// */
2338 /* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2339 /* ////////////////////////////////////////////////////////////////////////// */
2340
readBitFromReversedStream(size_t * bitpointer,const unsigned char * bitstream)2341 static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
2342 {
2343 unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2344 ++(*bitpointer);
2345 return result;
2346 }
2347
readBitsFromReversedStream(size_t * bitpointer,const unsigned char * bitstream,size_t nbits)2348 static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
2349 {
2350 unsigned result = 0;
2351 size_t i;
2352 for(i = nbits - 1; i < nbits; --i)
2353 {
2354 result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
2355 }
2356 return result;
2357 }
2358
2359 #ifdef LODEPNG_COMPILE_DECODER
setBitOfReversedStream0(size_t * bitpointer,unsigned char * bitstream,unsigned char bit)2360 static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2361 {
2362 /*the current bit in bitstream must be 0 for this to work*/
2363 if(bit)
2364 {
2365 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2366 bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
2367 }
2368 ++(*bitpointer);
2369 }
2370 #endif /*LODEPNG_COMPILE_DECODER*/
2371
setBitOfReversedStream(size_t * bitpointer,unsigned char * bitstream,unsigned char bit)2372 static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2373 {
2374 /*the current bit in bitstream may be 0 or 1 for this to work*/
2375 if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
2376 else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
2377 ++(*bitpointer);
2378 }
2379
2380 /* ////////////////////////////////////////////////////////////////////////// */
2381 /* / PNG chunks / */
2382 /* ////////////////////////////////////////////////////////////////////////// */
2383
lodepng_chunk_length(const unsigned char * chunk)2384 unsigned lodepng_chunk_length(const unsigned char* chunk)
2385 {
2386 return lodepng_read32bitInt(&chunk[0]);
2387 }
2388
lodepng_chunk_type(char type[5],const unsigned char * chunk)2389 void lodepng_chunk_type(char type[5], const unsigned char* chunk)
2390 {
2391 unsigned i;
2392 for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
2393 type[4] = 0; /*null termination char*/
2394 }
2395
lodepng_chunk_type_equals(const unsigned char * chunk,const char * type)2396 unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
2397 {
2398 if(strlen(type) != 4) return 0;
2399 return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2400 }
2401
lodepng_chunk_ancillary(const unsigned char * chunk)2402 unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
2403 {
2404 return((chunk[4] & 32) != 0);
2405 }
2406
lodepng_chunk_private(const unsigned char * chunk)2407 unsigned char lodepng_chunk_private(const unsigned char* chunk)
2408 {
2409 return((chunk[6] & 32) != 0);
2410 }
2411
lodepng_chunk_safetocopy(const unsigned char * chunk)2412 unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
2413 {
2414 return((chunk[7] & 32) != 0);
2415 }
2416
lodepng_chunk_data(unsigned char * chunk)2417 unsigned char* lodepng_chunk_data(unsigned char* chunk)
2418 {
2419 return &chunk[8];
2420 }
2421
lodepng_chunk_data_const(const unsigned char * chunk)2422 const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
2423 {
2424 return &chunk[8];
2425 }
2426
lodepng_chunk_check_crc(const unsigned char * chunk)2427 unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
2428 {
2429 unsigned length = lodepng_chunk_length(chunk);
2430 unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
2431 /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2432 unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2433 if(CRC != checksum) return 1;
2434 else return 0;
2435 }
2436
lodepng_chunk_generate_crc(unsigned char * chunk)2437 void lodepng_chunk_generate_crc(unsigned char* chunk)
2438 {
2439 unsigned length = lodepng_chunk_length(chunk);
2440 unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
2441 lodepng_set32bitInt(chunk + 8 + length, CRC);
2442 }
2443
lodepng_chunk_next(unsigned char * chunk)2444 unsigned char* lodepng_chunk_next(unsigned char* chunk)
2445 {
2446 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2447 return &chunk[total_chunk_length];
2448 }
2449
lodepng_chunk_next_const(const unsigned char * chunk)2450 const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
2451 {
2452 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2453 return &chunk[total_chunk_length];
2454 }
2455
lodepng_chunk_append(unsigned char ** out,size_t * outlength,const unsigned char * chunk)2456 unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
2457 {
2458 unsigned i;
2459 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2460 unsigned char *chunk_start, *new_buffer;
2461 size_t new_length = (*outlength) + total_chunk_length;
2462 if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
2463
2464 new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2465 if(!new_buffer) return 83; /*alloc fail*/
2466 (*out) = new_buffer;
2467 (*outlength) = new_length;
2468 chunk_start = &(*out)[new_length - total_chunk_length];
2469
2470 for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
2471
2472 return 0;
2473 }
2474
lodepng_chunk_create(unsigned char ** out,size_t * outlength,unsigned length,const char * type,const unsigned char * data)2475 unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
2476 const char* type, const unsigned char* data)
2477 {
2478 unsigned i;
2479 unsigned char *chunk, *new_buffer;
2480 size_t new_length = (*outlength) + length + 12;
2481 if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
2482 new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2483 if(!new_buffer) return 83; /*alloc fail*/
2484 (*out) = new_buffer;
2485 (*outlength) = new_length;
2486 chunk = &(*out)[(*outlength) - length - 12];
2487
2488 /*1: length*/
2489 lodepng_set32bitInt(chunk, (unsigned)length);
2490
2491 /*2: chunk name (4 letters)*/
2492 chunk[4] = (unsigned char)type[0];
2493 chunk[5] = (unsigned char)type[1];
2494 chunk[6] = (unsigned char)type[2];
2495 chunk[7] = (unsigned char)type[3];
2496
2497 /*3: the data*/
2498 for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
2499
2500 /*4: CRC (of the chunkname characters and the data)*/
2501 lodepng_chunk_generate_crc(chunk);
2502
2503 return 0;
2504 }
2505
2506 /* ////////////////////////////////////////////////////////////////////////// */
2507 /* / Color types and such / */
2508 /* ////////////////////////////////////////////////////////////////////////// */
2509
2510 /*return type is a LodePNG error code*/
checkColorValidity(LodePNGColorType colortype,unsigned bd)2511 static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
2512 {
2513 switch(colortype)
2514 {
2515 case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
2516 case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
2517 case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
2518 case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
2519 case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
2520 default: return 31;
2521 }
2522 return 0; /*allowed color type / bits combination*/
2523 }
2524
getNumColorChannels(LodePNGColorType colortype)2525 static unsigned getNumColorChannels(LodePNGColorType colortype)
2526 {
2527 switch(colortype)
2528 {
2529 case 0: return 1; /*grey*/
2530 case 2: return 3; /*RGB*/
2531 case 3: return 1; /*palette*/
2532 case 4: return 2; /*grey + alpha*/
2533 case 6: return 4; /*RGBA*/
2534 }
2535 return 0; /*unexisting color type*/
2536 }
2537
lodepng_get_bpp_lct(LodePNGColorType colortype,unsigned bitdepth)2538 static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
2539 {
2540 /*bits per pixel is amount of channels * bits per channel*/
2541 return getNumColorChannels(colortype) * bitdepth;
2542 }
2543
2544 /* ////////////////////////////////////////////////////////////////////////// */
2545
lodepng_color_mode_init(LodePNGColorMode * info)2546 void lodepng_color_mode_init(LodePNGColorMode* info)
2547 {
2548 info->key_defined = 0;
2549 info->key_r = info->key_g = info->key_b = 0;
2550 info->colortype = LCT_RGBA;
2551 info->bitdepth = 8;
2552 info->palette = 0;
2553 info->palettesize = 0;
2554 }
2555
lodepng_color_mode_cleanup(LodePNGColorMode * info)2556 void lodepng_color_mode_cleanup(LodePNGColorMode* info)
2557 {
2558 lodepng_palette_clear(info);
2559 }
2560
lodepng_color_mode_copy(LodePNGColorMode * dest,const LodePNGColorMode * source)2561 unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
2562 {
2563 size_t i;
2564 lodepng_color_mode_cleanup(dest);
2565 *dest = *source;
2566 if(source->palette)
2567 {
2568 dest->palette = (unsigned char*)lodepng_malloc(1024);
2569 if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2570 for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
2571 }
2572 return 0;
2573 }
2574
lodepng_color_mode_equal(const LodePNGColorMode * a,const LodePNGColorMode * b)2575 static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
2576 {
2577 size_t i;
2578 if(a->colortype != b->colortype) return 0;
2579 if(a->bitdepth != b->bitdepth) return 0;
2580 if(a->key_defined != b->key_defined) return 0;
2581 if(a->key_defined)
2582 {
2583 if(a->key_r != b->key_r) return 0;
2584 if(a->key_g != b->key_g) return 0;
2585 if(a->key_b != b->key_b) return 0;
2586 }
2587 /*if one of the palette sizes is 0, then we consider it to be the same as the
2588 other: it means that e.g. the palette was not given by the user and should be
2589 considered the same as the palette inside the PNG.*/
2590 if(1/*a->palettesize != 0 && b->palettesize != 0*/) {
2591 if(a->palettesize != b->palettesize) return 0;
2592 for(i = 0; i != a->palettesize * 4; ++i)
2593 {
2594 if(a->palette[i] != b->palette[i]) return 0;
2595 }
2596 }
2597 return 1;
2598 }
2599
lodepng_palette_clear(LodePNGColorMode * info)2600 void lodepng_palette_clear(LodePNGColorMode* info)
2601 {
2602 if(info->palette) lodepng_free(info->palette);
2603 info->palette = 0;
2604 info->palettesize = 0;
2605 }
2606
lodepng_palette_add(LodePNGColorMode * info,unsigned char r,unsigned char g,unsigned char b,unsigned char a)2607 unsigned lodepng_palette_add(LodePNGColorMode* info,
2608 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2609 {
2610 unsigned char* data;
2611 /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2612 the max of 256 colors, it'll have the exact alloc size*/
2613 if(!info->palette) /*allocate palette if empty*/
2614 {
2615 /*room for 256 colors with 4 bytes each*/
2616 data = (unsigned char*)lodepng_realloc(info->palette, 1024);
2617 if(!data) return 83; /*alloc fail*/
2618 else info->palette = data;
2619 }
2620 info->palette[4 * info->palettesize + 0] = r;
2621 info->palette[4 * info->palettesize + 1] = g;
2622 info->palette[4 * info->palettesize + 2] = b;
2623 info->palette[4 * info->palettesize + 3] = a;
2624 ++info->palettesize;
2625 return 0;
2626 }
2627
lodepng_get_bpp(const LodePNGColorMode * info)2628 unsigned lodepng_get_bpp(const LodePNGColorMode* info)
2629 {
2630 /*calculate bits per pixel out of colortype and bitdepth*/
2631 return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
2632 }
2633
lodepng_get_channels(const LodePNGColorMode * info)2634 unsigned lodepng_get_channels(const LodePNGColorMode* info)
2635 {
2636 return getNumColorChannels(info->colortype);
2637 }
2638
lodepng_is_greyscale_type(const LodePNGColorMode * info)2639 unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
2640 {
2641 return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
2642 }
2643
lodepng_is_alpha_type(const LodePNGColorMode * info)2644 unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
2645 {
2646 return (info->colortype & 4) != 0; /*4 or 6*/
2647 }
2648
lodepng_is_palette_type(const LodePNGColorMode * info)2649 unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
2650 {
2651 return info->colortype == LCT_PALETTE;
2652 }
2653
lodepng_has_palette_alpha(const LodePNGColorMode * info)2654 unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
2655 {
2656 size_t i;
2657 for(i = 0; i != info->palettesize; ++i)
2658 {
2659 if(info->palette[i * 4 + 3] < 255) return 1;
2660 }
2661 return 0;
2662 }
2663
lodepng_can_have_alpha(const LodePNGColorMode * info)2664 unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
2665 {
2666 return info->key_defined
2667 || lodepng_is_alpha_type(info)
2668 || lodepng_has_palette_alpha(info);
2669 }
2670
lodepng_get_raw_size(unsigned w,unsigned h,const LodePNGColorMode * color)2671 size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
2672 {
2673 /*will not overflow for any color type if roughly w * h < 268435455*/
2674 int bpp = lodepng_get_bpp(color);
2675 size_t n = w * h;
2676 return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
2677 }
2678
lodepng_get_raw_size_lct(unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)2679 size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
2680 {
2681 /*will not overflow for any color type if roughly w * h < 268435455*/
2682 int bpp = lodepng_get_bpp_lct(colortype, bitdepth);
2683 size_t n = w * h;
2684 return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
2685 }
2686
2687
2688 #ifdef LODEPNG_COMPILE_PNG
2689 #ifdef LODEPNG_COMPILE_DECODER
2690 /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
lodepng_get_raw_size_idat(unsigned w,unsigned h,const LodePNGColorMode * color)2691 static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color)
2692 {
2693 /*will not overflow for any color type if roughly w * h < 268435455*/
2694 int bpp = lodepng_get_bpp(color);
2695 size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8;
2696 return h * line;
2697 }
2698 #endif /*LODEPNG_COMPILE_DECODER*/
2699 #endif /*LODEPNG_COMPILE_PNG*/
2700
2701 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2702
LodePNGUnknownChunks_init(LodePNGInfo * info)2703 static void LodePNGUnknownChunks_init(LodePNGInfo* info)
2704 {
2705 unsigned i;
2706 for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
2707 for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
2708 }
2709
LodePNGUnknownChunks_cleanup(LodePNGInfo * info)2710 static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
2711 {
2712 unsigned i;
2713 for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
2714 }
2715
LodePNGUnknownChunks_copy(LodePNGInfo * dest,const LodePNGInfo * src)2716 static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
2717 {
2718 unsigned i;
2719
2720 LodePNGUnknownChunks_cleanup(dest);
2721
2722 for(i = 0; i != 3; ++i)
2723 {
2724 size_t j;
2725 dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
2726 dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
2727 if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
2728 for(j = 0; j < src->unknown_chunks_size[i]; ++j)
2729 {
2730 dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
2731 }
2732 }
2733
2734 return 0;
2735 }
2736
2737 /******************************************************************************/
2738
LodePNGText_init(LodePNGInfo * info)2739 static void LodePNGText_init(LodePNGInfo* info)
2740 {
2741 info->text_num = 0;
2742 info->text_keys = NULL;
2743 info->text_strings = NULL;
2744 }
2745
LodePNGText_cleanup(LodePNGInfo * info)2746 static void LodePNGText_cleanup(LodePNGInfo* info)
2747 {
2748 size_t i;
2749 for(i = 0; i != info->text_num; ++i)
2750 {
2751 string_cleanup(&info->text_keys[i]);
2752 string_cleanup(&info->text_strings[i]);
2753 }
2754 lodepng_free(info->text_keys);
2755 lodepng_free(info->text_strings);
2756 }
2757
LodePNGText_copy(LodePNGInfo * dest,const LodePNGInfo * source)2758 static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2759 {
2760 size_t i = 0;
2761 dest->text_keys = 0;
2762 dest->text_strings = 0;
2763 dest->text_num = 0;
2764 for(i = 0; i != source->text_num; ++i)
2765 {
2766 CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
2767 }
2768 return 0;
2769 }
2770
lodepng_clear_text(LodePNGInfo * info)2771 void lodepng_clear_text(LodePNGInfo* info)
2772 {
2773 LodePNGText_cleanup(info);
2774 }
2775
lodepng_add_text(LodePNGInfo * info,const char * key,const char * str)2776 unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
2777 {
2778 char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
2779 char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
2780 if(!new_keys || !new_strings)
2781 {
2782 lodepng_free(new_keys);
2783 lodepng_free(new_strings);
2784 return 83; /*alloc fail*/
2785 }
2786
2787 ++info->text_num;
2788 info->text_keys = new_keys;
2789 info->text_strings = new_strings;
2790
2791 string_init(&info->text_keys[info->text_num - 1]);
2792 string_set(&info->text_keys[info->text_num - 1], key);
2793
2794 string_init(&info->text_strings[info->text_num - 1]);
2795 string_set(&info->text_strings[info->text_num - 1], str);
2796
2797 return 0;
2798 }
2799
2800 /******************************************************************************/
2801
LodePNGIText_init(LodePNGInfo * info)2802 static void LodePNGIText_init(LodePNGInfo* info)
2803 {
2804 info->itext_num = 0;
2805 info->itext_keys = NULL;
2806 info->itext_langtags = NULL;
2807 info->itext_transkeys = NULL;
2808 info->itext_strings = NULL;
2809 }
2810
LodePNGIText_cleanup(LodePNGInfo * info)2811 static void LodePNGIText_cleanup(LodePNGInfo* info)
2812 {
2813 size_t i;
2814 for(i = 0; i != info->itext_num; ++i)
2815 {
2816 string_cleanup(&info->itext_keys[i]);
2817 string_cleanup(&info->itext_langtags[i]);
2818 string_cleanup(&info->itext_transkeys[i]);
2819 string_cleanup(&info->itext_strings[i]);
2820 }
2821 lodepng_free(info->itext_keys);
2822 lodepng_free(info->itext_langtags);
2823 lodepng_free(info->itext_transkeys);
2824 lodepng_free(info->itext_strings);
2825 }
2826
LodePNGIText_copy(LodePNGInfo * dest,const LodePNGInfo * source)2827 static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2828 {
2829 size_t i = 0;
2830 dest->itext_keys = 0;
2831 dest->itext_langtags = 0;
2832 dest->itext_transkeys = 0;
2833 dest->itext_strings = 0;
2834 dest->itext_num = 0;
2835 for(i = 0; i != source->itext_num; ++i)
2836 {
2837 CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
2838 source->itext_transkeys[i], source->itext_strings[i]));
2839 }
2840 return 0;
2841 }
2842
lodepng_clear_itext(LodePNGInfo * info)2843 void lodepng_clear_itext(LodePNGInfo* info)
2844 {
2845 LodePNGIText_cleanup(info);
2846 }
2847
lodepng_add_itext(LodePNGInfo * info,const char * key,const char * langtag,const char * transkey,const char * str)2848 unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
2849 const char* transkey, const char* str)
2850 {
2851 char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
2852 char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
2853 char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
2854 char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
2855 if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
2856 {
2857 lodepng_free(new_keys);
2858 lodepng_free(new_langtags);
2859 lodepng_free(new_transkeys);
2860 lodepng_free(new_strings);
2861 return 83; /*alloc fail*/
2862 }
2863
2864 ++info->itext_num;
2865 info->itext_keys = new_keys;
2866 info->itext_langtags = new_langtags;
2867 info->itext_transkeys = new_transkeys;
2868 info->itext_strings = new_strings;
2869
2870 string_init(&info->itext_keys[info->itext_num - 1]);
2871 string_set(&info->itext_keys[info->itext_num - 1], key);
2872
2873 string_init(&info->itext_langtags[info->itext_num - 1]);
2874 string_set(&info->itext_langtags[info->itext_num - 1], langtag);
2875
2876 string_init(&info->itext_transkeys[info->itext_num - 1]);
2877 string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
2878
2879 string_init(&info->itext_strings[info->itext_num - 1]);
2880 string_set(&info->itext_strings[info->itext_num - 1], str);
2881
2882 return 0;
2883 }
2884 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2885
lodepng_info_init(LodePNGInfo * info)2886 void lodepng_info_init(LodePNGInfo* info)
2887 {
2888 lodepng_color_mode_init(&info->color);
2889 info->interlace_method = 0;
2890 info->compression_method = 0;
2891 info->filter_method = 0;
2892 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2893 info->background_defined = 0;
2894 info->background_r = info->background_g = info->background_b = 0;
2895
2896 LodePNGText_init(info);
2897 LodePNGIText_init(info);
2898
2899 info->time_defined = 0;
2900 info->phys_defined = 0;
2901
2902 LodePNGUnknownChunks_init(info);
2903 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2904 }
2905
lodepng_info_cleanup(LodePNGInfo * info)2906 void lodepng_info_cleanup(LodePNGInfo* info)
2907 {
2908 lodepng_color_mode_cleanup(&info->color);
2909 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2910 LodePNGText_cleanup(info);
2911 LodePNGIText_cleanup(info);
2912
2913 LodePNGUnknownChunks_cleanup(info);
2914 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2915 }
2916
lodepng_info_copy(LodePNGInfo * dest,const LodePNGInfo * source)2917 unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2918 {
2919 lodepng_info_cleanup(dest);
2920 *dest = *source;
2921 lodepng_color_mode_init(&dest->color);
2922 CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
2923
2924 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2925 CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
2926 CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
2927
2928 LodePNGUnknownChunks_init(dest);
2929 CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
2930 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2931 return 0;
2932 }
2933
lodepng_info_swap(LodePNGInfo * a,LodePNGInfo * b)2934 void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
2935 {
2936 LodePNGInfo temp = *a;
2937 *a = *b;
2938 *b = temp;
2939 }
2940
2941 /* ////////////////////////////////////////////////////////////////////////// */
2942
2943 /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
addColorBits(unsigned char * out,size_t index,unsigned bits,unsigned in)2944 static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
2945 {
2946 unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
2947 /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2948 unsigned p = index & m;
2949 in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
2950 in = in << (bits * (m - p));
2951 if(p == 0) out[index * bits / 8] = in;
2952 else out[index * bits / 8] |= in;
2953 }
2954
2955 typedef struct ColorTree ColorTree;
2956
2957 /*
2958 One node of a color tree
2959 This is the data structure used to count the number of unique colors and to get a palette
2960 index for a color. It's like an octree, but because the alpha channel is used too, each
2961 node has 16 instead of 8 children.
2962 */
2963 struct ColorTree
2964 {
2965 ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
2966 int index; /*the payload. Only has a meaningful value if this is in the last level*/
2967 };
2968
color_tree_init(ColorTree * tree)2969 static void color_tree_init(ColorTree* tree)
2970 {
2971 int i;
2972 for(i = 0; i != 16; ++i) tree->children[i] = 0;
2973 tree->index = -1;
2974 }
2975
color_tree_cleanup(ColorTree * tree)2976 static void color_tree_cleanup(ColorTree* tree)
2977 {
2978 int i;
2979 for(i = 0; i != 16; ++i)
2980 {
2981 if(tree->children[i])
2982 {
2983 color_tree_cleanup(tree->children[i]);
2984 lodepng_free(tree->children[i]);
2985 }
2986 }
2987 }
2988
2989 /*returns -1 if color not present, its index otherwise*/
color_tree_get(ColorTree * tree,unsigned char r,unsigned char g,unsigned char b,unsigned char a)2990 static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2991 {
2992 int bit = 0;
2993 for(bit = 0; bit < 8; ++bit)
2994 {
2995 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
2996 if(!tree->children[i]) return -1;
2997 else tree = tree->children[i];
2998 }
2999 return tree ? tree->index : -1;
3000 }
3001
3002 #ifdef LODEPNG_COMPILE_ENCODER
color_tree_has(ColorTree * tree,unsigned char r,unsigned char g,unsigned char b,unsigned char a)3003 static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3004 {
3005 return color_tree_get(tree, r, g, b, a) >= 0;
3006 }
3007 #endif /*LODEPNG_COMPILE_ENCODER*/
3008
3009 /*color is not allowed to already exist.
3010 Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
color_tree_add(ColorTree * tree,unsigned char r,unsigned char g,unsigned char b,unsigned char a,unsigned index)3011 static void color_tree_add(ColorTree* tree,
3012 unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
3013 {
3014 int bit;
3015 for(bit = 0; bit < 8; ++bit)
3016 {
3017 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3018 if(!tree->children[i])
3019 {
3020 tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
3021 color_tree_init(tree->children[i]);
3022 }
3023 tree = tree->children[i];
3024 }
3025 tree->index = (int)index;
3026 }
3027
3028 /*put a pixel, given its RGBA color, into image of any color type*/
rgba8ToPixel(unsigned char * out,size_t i,const LodePNGColorMode * mode,ColorTree * tree,unsigned char r,unsigned char g,unsigned char b,unsigned char a)3029 static unsigned rgba8ToPixel(unsigned char* out, size_t i,
3030 const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
3031 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3032 {
3033 if(mode->colortype == LCT_GREY)
3034 {
3035 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3036 if(mode->bitdepth == 8) out[i] = grey;
3037 else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
3038 else
3039 {
3040 /*take the most significant bits of grey*/
3041 grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
3042 addColorBits(out, i, mode->bitdepth, grey);
3043 }
3044 }
3045 else if(mode->colortype == LCT_RGB)
3046 {
3047 if(mode->bitdepth == 8)
3048 {
3049 out[i * 3 + 0] = r;
3050 out[i * 3 + 1] = g;
3051 out[i * 3 + 2] = b;
3052 }
3053 else
3054 {
3055 out[i * 6 + 0] = out[i * 6 + 1] = r;
3056 out[i * 6 + 2] = out[i * 6 + 3] = g;
3057 out[i * 6 + 4] = out[i * 6 + 5] = b;
3058 }
3059 }
3060 else if(mode->colortype == LCT_PALETTE)
3061 {
3062 int index = color_tree_get(tree, r, g, b, a);
3063 if(index < 0) return 82; /*color not in palette*/
3064 if(mode->bitdepth == 8) out[i] = index;
3065 else addColorBits(out, i, mode->bitdepth, (unsigned)index);
3066 }
3067 else if(mode->colortype == LCT_GREY_ALPHA)
3068 {
3069 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3070 if(mode->bitdepth == 8)
3071 {
3072 out[i * 2 + 0] = grey;
3073 out[i * 2 + 1] = a;
3074 }
3075 else if(mode->bitdepth == 16)
3076 {
3077 out[i * 4 + 0] = out[i * 4 + 1] = grey;
3078 out[i * 4 + 2] = out[i * 4 + 3] = a;
3079 }
3080 }
3081 else if(mode->colortype == LCT_RGBA)
3082 {
3083 if(mode->bitdepth == 8)
3084 {
3085 out[i * 4 + 0] = r;
3086 out[i * 4 + 1] = g;
3087 out[i * 4 + 2] = b;
3088 out[i * 4 + 3] = a;
3089 }
3090 else
3091 {
3092 out[i * 8 + 0] = out[i * 8 + 1] = r;
3093 out[i * 8 + 2] = out[i * 8 + 3] = g;
3094 out[i * 8 + 4] = out[i * 8 + 5] = b;
3095 out[i * 8 + 6] = out[i * 8 + 7] = a;
3096 }
3097 }
3098
3099 return 0; /*no error*/
3100 }
3101
3102 /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
rgba16ToPixel(unsigned char * out,size_t i,const LodePNGColorMode * mode,unsigned short r,unsigned short g,unsigned short b,unsigned short a)3103 static void rgba16ToPixel(unsigned char* out, size_t i,
3104 const LodePNGColorMode* mode,
3105 unsigned short r, unsigned short g, unsigned short b, unsigned short a)
3106 {
3107 if(mode->colortype == LCT_GREY)
3108 {
3109 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3110 out[i * 2 + 0] = (grey >> 8) & 255;
3111 out[i * 2 + 1] = grey & 255;
3112 }
3113 else if(mode->colortype == LCT_RGB)
3114 {
3115 out[i * 6 + 0] = (r >> 8) & 255;
3116 out[i * 6 + 1] = r & 255;
3117 out[i * 6 + 2] = (g >> 8) & 255;
3118 out[i * 6 + 3] = g & 255;
3119 out[i * 6 + 4] = (b >> 8) & 255;
3120 out[i * 6 + 5] = b & 255;
3121 }
3122 else if(mode->colortype == LCT_GREY_ALPHA)
3123 {
3124 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3125 out[i * 4 + 0] = (grey >> 8) & 255;
3126 out[i * 4 + 1] = grey & 255;
3127 out[i * 4 + 2] = (a >> 8) & 255;
3128 out[i * 4 + 3] = a & 255;
3129 }
3130 else if(mode->colortype == LCT_RGBA)
3131 {
3132 out[i * 8 + 0] = (r >> 8) & 255;
3133 out[i * 8 + 1] = r & 255;
3134 out[i * 8 + 2] = (g >> 8) & 255;
3135 out[i * 8 + 3] = g & 255;
3136 out[i * 8 + 4] = (b >> 8) & 255;
3137 out[i * 8 + 5] = b & 255;
3138 out[i * 8 + 6] = (a >> 8) & 255;
3139 out[i * 8 + 7] = a & 255;
3140 }
3141 }
3142
3143 /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
getPixelColorRGBA8(unsigned char * r,unsigned char * g,unsigned char * b,unsigned char * a,const unsigned char * in,size_t i,const LodePNGColorMode * mode)3144 static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
3145 unsigned char* b, unsigned char* a,
3146 const unsigned char* in, size_t i,
3147 const LodePNGColorMode* mode)
3148 {
3149 if(mode->colortype == LCT_GREY)
3150 {
3151 if(mode->bitdepth == 8)
3152 {
3153 *r = *g = *b = in[i];
3154 if(mode->key_defined && *r == mode->key_r) *a = 0;
3155 else *a = 255;
3156 }
3157 else if(mode->bitdepth == 16)
3158 {
3159 *r = *g = *b = in[i * 2 + 0];
3160 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3161 else *a = 255;
3162 }
3163 else
3164 {
3165 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3166 size_t j = i * mode->bitdepth;
3167 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3168 *r = *g = *b = (value * 255) / highest;
3169 if(mode->key_defined && value == mode->key_r) *a = 0;
3170 else *a = 255;
3171 }
3172 }
3173 else if(mode->colortype == LCT_RGB)
3174 {
3175 if(mode->bitdepth == 8)
3176 {
3177 *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3178 if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3179 else *a = 255;
3180 }
3181 else
3182 {
3183 *r = in[i * 6 + 0];
3184 *g = in[i * 6 + 2];
3185 *b = in[i * 6 + 4];
3186 if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3187 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3188 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3189 else *a = 255;
3190 }
3191 }
3192 else if(mode->colortype == LCT_PALETTE)
3193 {
3194 unsigned index;
3195 if(mode->bitdepth == 8) index = in[i];
3196 else
3197 {
3198 size_t j = i * mode->bitdepth;
3199 index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3200 }
3201
3202 if(index >= mode->palettesize)
3203 {
3204 /*This is an error according to the PNG spec, but common PNG decoders make it black instead.
3205 Done here too, slightly faster due to no error handling needed.*/
3206 *r = *g = *b = 0;
3207 *a = 255;
3208 }
3209 else
3210 {
3211 *r = mode->palette[index * 4 + 0];
3212 *g = mode->palette[index * 4 + 1];
3213 *b = mode->palette[index * 4 + 2];
3214 *a = mode->palette[index * 4 + 3];
3215 }
3216 }
3217 else if(mode->colortype == LCT_GREY_ALPHA)
3218 {
3219 if(mode->bitdepth == 8)
3220 {
3221 *r = *g = *b = in[i * 2 + 0];
3222 *a = in[i * 2 + 1];
3223 }
3224 else
3225 {
3226 *r = *g = *b = in[i * 4 + 0];
3227 *a = in[i * 4 + 2];
3228 }
3229 }
3230 else if(mode->colortype == LCT_RGBA)
3231 {
3232 if(mode->bitdepth == 8)
3233 {
3234 *r = in[i * 4 + 0];
3235 *g = in[i * 4 + 1];
3236 *b = in[i * 4 + 2];
3237 *a = in[i * 4 + 3];
3238 }
3239 else
3240 {
3241 *r = in[i * 8 + 0];
3242 *g = in[i * 8 + 2];
3243 *b = in[i * 8 + 4];
3244 *a = in[i * 8 + 6];
3245 }
3246 }
3247 }
3248
3249 /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3250 mode test cases, optimized to convert the colors much faster, when converting
3251 to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3252 enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3253 of the input buffer.*/
getPixelColorsRGBA8(unsigned char * buffer,size_t numpixels,unsigned has_alpha,const unsigned char * in,const LodePNGColorMode * mode)3254 static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
3255 unsigned has_alpha, const unsigned char* in,
3256 const LodePNGColorMode* mode)
3257 {
3258 unsigned num_channels = has_alpha ? 4 : 3;
3259 size_t i;
3260 if(mode->colortype == LCT_GREY)
3261 {
3262 if(mode->bitdepth == 8)
3263 {
3264 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3265 {
3266 buffer[0] = buffer[1] = buffer[2] = in[i];
3267 if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
3268 }
3269 }
3270 else if(mode->bitdepth == 16)
3271 {
3272 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3273 {
3274 buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3275 if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
3276 }
3277 }
3278 else
3279 {
3280 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3281 size_t j = 0;
3282 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3283 {
3284 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3285 buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3286 if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
3287 }
3288 }
3289 }
3290 else if(mode->colortype == LCT_RGB)
3291 {
3292 if(mode->bitdepth == 8)
3293 {
3294 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3295 {
3296 buffer[0] = in[i * 3 + 0];
3297 buffer[1] = in[i * 3 + 1];
3298 buffer[2] = in[i * 3 + 2];
3299 if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
3300 && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
3301 }
3302 }
3303 else
3304 {
3305 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3306 {
3307 buffer[0] = in[i * 6 + 0];
3308 buffer[1] = in[i * 6 + 2];
3309 buffer[2] = in[i * 6 + 4];
3310 if(has_alpha) buffer[3] = mode->key_defined
3311 && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3312 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3313 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
3314 }
3315 }
3316 }
3317 else if(mode->colortype == LCT_PALETTE)
3318 {
3319 unsigned index;
3320 size_t j = 0;
3321 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3322 {
3323 if(mode->bitdepth == 8) index = in[i];
3324 else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3325
3326 if(index >= mode->palettesize)
3327 {
3328 /*This is an error according to the PNG spec, but most PNG decoders make it black instead.
3329 Done here too, slightly faster due to no error handling needed.*/
3330 buffer[0] = buffer[1] = buffer[2] = 0;
3331 if(has_alpha) buffer[3] = 255;
3332 }
3333 else
3334 {
3335 buffer[0] = mode->palette[index * 4 + 0];
3336 buffer[1] = mode->palette[index * 4 + 1];
3337 buffer[2] = mode->palette[index * 4 + 2];
3338 if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
3339 }
3340 }
3341 }
3342 else if(mode->colortype == LCT_GREY_ALPHA)
3343 {
3344 if(mode->bitdepth == 8)
3345 {
3346 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3347 {
3348 buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3349 if(has_alpha) buffer[3] = in[i * 2 + 1];
3350 }
3351 }
3352 else
3353 {
3354 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3355 {
3356 buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3357 if(has_alpha) buffer[3] = in[i * 4 + 2];
3358 }
3359 }
3360 }
3361 else if(mode->colortype == LCT_RGBA)
3362 {
3363 if(mode->bitdepth == 8)
3364 {
3365 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3366 {
3367 buffer[0] = in[i * 4 + 0];
3368 buffer[1] = in[i * 4 + 1];
3369 buffer[2] = in[i * 4 + 2];
3370 if(has_alpha) buffer[3] = in[i * 4 + 3];
3371 }
3372 }
3373 else
3374 {
3375 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3376 {
3377 buffer[0] = in[i * 8 + 0];
3378 buffer[1] = in[i * 8 + 2];
3379 buffer[2] = in[i * 8 + 4];
3380 if(has_alpha) buffer[3] = in[i * 8 + 6];
3381 }
3382 }
3383 }
3384 }
3385
3386 /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3387 given color type, but the given color type must be 16-bit itself.*/
getPixelColorRGBA16(unsigned short * r,unsigned short * g,unsigned short * b,unsigned short * a,const unsigned char * in,size_t i,const LodePNGColorMode * mode)3388 static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3389 const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3390 {
3391 if(mode->colortype == LCT_GREY)
3392 {
3393 *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3394 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3395 else *a = 65535;
3396 }
3397 else if(mode->colortype == LCT_RGB)
3398 {
3399 *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
3400 *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
3401 *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
3402 if(mode->key_defined
3403 && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3404 && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3405 && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3406 else *a = 65535;
3407 }
3408 else if(mode->colortype == LCT_GREY_ALPHA)
3409 {
3410 *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
3411 *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
3412 }
3413 else if(mode->colortype == LCT_RGBA)
3414 {
3415 *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
3416 *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
3417 *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
3418 *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
3419 }
3420 }
3421
lodepng_convert(unsigned char * out,const unsigned char * in,const LodePNGColorMode * mode_out,const LodePNGColorMode * mode_in,unsigned w,unsigned h)3422 unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3423 const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
3424 unsigned w, unsigned h)
3425 {
3426 size_t i;
3427 ColorTree tree;
3428 size_t numpixels = w * h;
3429
3430 if(lodepng_color_mode_equal(mode_out, mode_in))
3431 {
3432 size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3433 for(i = 0; i != numbytes; ++i) out[i] = in[i];
3434 return 0;
3435 }
3436
3437 if(mode_out->colortype == LCT_PALETTE)
3438 {
3439 size_t palettesize = mode_out->palettesize;
3440 const unsigned char* palette = mode_out->palette;
3441 size_t palsize = 1u << mode_out->bitdepth;
3442 /*if the user specified output palette but did not give the values, assume
3443 they want the values of the input color type (assuming that one is palette).
3444 Note that we never create a new palette ourselves.*/
3445 if(palettesize == 0)
3446 {
3447 palettesize = mode_in->palettesize;
3448 palette = mode_in->palette;
3449 }
3450 if(palettesize < palsize) palsize = palettesize;
3451 color_tree_init(&tree);
3452 for(i = 0; i != palsize; ++i)
3453 {
3454 const unsigned char* p = &palette[i * 4];
3455 color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
3456 }
3457 }
3458
3459 if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
3460 {
3461 for(i = 0; i != numpixels; ++i)
3462 {
3463 unsigned short r = 0, g = 0, b = 0, a = 0;
3464 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3465 rgba16ToPixel(out, i, mode_out, r, g, b, a);
3466 }
3467 }
3468 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
3469 {
3470 getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
3471 }
3472 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
3473 {
3474 getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
3475 }
3476 else
3477 {
3478 unsigned char r = 0, g = 0, b = 0, a = 0;
3479 for(i = 0; i != numpixels; ++i)
3480 {
3481 getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3482 CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a));
3483 }
3484 }
3485
3486 if(mode_out->colortype == LCT_PALETTE)
3487 {
3488 color_tree_cleanup(&tree);
3489 }
3490
3491 return 0; /*no error*/
3492 }
3493
3494 #ifdef LODEPNG_COMPILE_ENCODER
3495
lodepng_color_profile_init(LodePNGColorProfile * profile)3496 void lodepng_color_profile_init(LodePNGColorProfile* profile)
3497 {
3498 profile->colored = 0;
3499 profile->key = 0;
3500 profile->alpha = 0;
3501 profile->key_r = profile->key_g = profile->key_b = 0;
3502 profile->numcolors = 0;
3503 profile->bits = 1;
3504 }
3505
3506 /*function used for debug purposes with C++*/
3507 /*void printColorProfile(LodePNGColorProfile* p)
3508 {
3509 std::cout << "colored: " << (int)p->colored << ", ";
3510 std::cout << "key: " << (int)p->key << ", ";
3511 std::cout << "key_r: " << (int)p->key_r << ", ";
3512 std::cout << "key_g: " << (int)p->key_g << ", ";
3513 std::cout << "key_b: " << (int)p->key_b << ", ";
3514 std::cout << "alpha: " << (int)p->alpha << ", ";
3515 std::cout << "numcolors: " << (int)p->numcolors << ", ";
3516 std::cout << "bits: " << (int)p->bits << std::endl;
3517 }*/
3518
3519 /*Returns how many bits needed to represent given value (max 8 bit)*/
getValueRequiredBits(unsigned char value)3520 static unsigned getValueRequiredBits(unsigned char value)
3521 {
3522 if(value == 0 || value == 255) return 1;
3523 /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3524 if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
3525 return 8;
3526 }
3527
3528 /*profile must already have been inited with mode.
3529 It's ok to set some parameters of profile to done already.*/
lodepng_get_color_profile(LodePNGColorProfile * profile,const unsigned char * in,unsigned w,unsigned h,const LodePNGColorMode * mode)3530 unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
3531 const unsigned char* in, unsigned w, unsigned h,
3532 const LodePNGColorMode* mode)
3533 {
3534 unsigned error = 0;
3535 size_t i;
3536 ColorTree tree;
3537 size_t numpixels = w * h;
3538
3539 unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
3540 unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
3541 unsigned numcolors_done = 0;
3542 unsigned bpp = lodepng_get_bpp(mode);
3543 unsigned bits_done = bpp == 1 ? 1 : 0;
3544 unsigned maxnumcolors = 257;
3545 unsigned sixteen = 0;
3546 if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
3547
3548 color_tree_init(&tree);
3549
3550 /*Check if the 16-bit input is truly 16-bit*/
3551 if(mode->bitdepth == 16)
3552 {
3553 unsigned short r, g, b, a;
3554 for(i = 0; i != numpixels; ++i)
3555 {
3556 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3557 if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
3558 (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/
3559 {
3560 sixteen = 1;
3561 break;
3562 }
3563 }
3564 }
3565
3566 if(sixteen)
3567 {
3568 unsigned short r = 0, g = 0, b = 0, a = 0;
3569 profile->bits = 16;
3570 bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3571
3572 for(i = 0; i != numpixels; ++i)
3573 {
3574 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3575
3576 if(!colored_done && (r != g || r != b))
3577 {
3578 profile->colored = 1;
3579 colored_done = 1;
3580 }
3581
3582 if(!alpha_done)
3583 {
3584 unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3585 if(a != 65535 && (a != 0 || (profile->key && !matchkey)))
3586 {
3587 profile->alpha = 1;
3588 alpha_done = 1;
3589 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3590 }
3591 else if(a == 0 && !profile->alpha && !profile->key)
3592 {
3593 profile->key = 1;
3594 profile->key_r = r;
3595 profile->key_g = g;
3596 profile->key_b = b;
3597 }
3598 else if(a == 65535 && profile->key && matchkey)
3599 {
3600 /* Color key cannot be used if an opaque pixel also has that RGB color. */
3601 profile->alpha = 1;
3602 alpha_done = 1;
3603 }
3604 }
3605
3606 if(alpha_done && numcolors_done && colored_done && bits_done) break;
3607 }
3608 }
3609 else /* < 16-bit */
3610 {
3611 for(i = 0; i != numpixels; ++i)
3612 {
3613 unsigned char r = 0, g = 0, b = 0, a = 0;
3614 getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
3615
3616 if(!bits_done && profile->bits < 8)
3617 {
3618 /*only r is checked, < 8 bits is only relevant for greyscale*/
3619 unsigned bits = getValueRequiredBits(r);
3620 if(bits > profile->bits) profile->bits = bits;
3621 }
3622 bits_done = (profile->bits >= bpp);
3623
3624 if(!colored_done && (r != g || r != b))
3625 {
3626 profile->colored = 1;
3627 colored_done = 1;
3628 if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
3629 }
3630
3631 if(!alpha_done)
3632 {
3633 unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3634 if(a != 255 && (a != 0 || (profile->key && !matchkey)))
3635 {
3636 profile->alpha = 1;
3637 alpha_done = 1;
3638 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3639 }
3640 else if(a == 0 && !profile->alpha && !profile->key)
3641 {
3642 profile->key = 1;
3643 profile->key_r = r;
3644 profile->key_g = g;
3645 profile->key_b = b;
3646 }
3647 else if(a == 255 && profile->key && matchkey)
3648 {
3649 /* Color key cannot be used if an opaque pixel also has that RGB color. */
3650 profile->alpha = 1;
3651 alpha_done = 1;
3652 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3653 }
3654 }
3655
3656 if(!numcolors_done)
3657 {
3658 if(!color_tree_has(&tree, r, g, b, a))
3659 {
3660 color_tree_add(&tree, r, g, b, a, profile->numcolors);
3661 if(profile->numcolors < 256)
3662 {
3663 unsigned char* p = profile->palette;
3664 unsigned n = profile->numcolors;
3665 p[n * 4 + 0] = r;
3666 p[n * 4 + 1] = g;
3667 p[n * 4 + 2] = b;
3668 p[n * 4 + 3] = a;
3669 }
3670 ++profile->numcolors;
3671 numcolors_done = profile->numcolors >= maxnumcolors;
3672 }
3673 }
3674
3675 if(alpha_done && numcolors_done && colored_done && bits_done) break;
3676 }
3677
3678 /*make the profile's key always 16-bit for consistency - repeat each byte twice*/
3679 profile->key_r += (profile->key_r << 8);
3680 profile->key_g += (profile->key_g << 8);
3681 profile->key_b += (profile->key_b << 8);
3682 }
3683
3684 color_tree_cleanup(&tree);
3685 return error;
3686 }
3687
3688 /*Automatically chooses color type that gives smallest amount of bits in the
3689 output image, e.g. grey if there are only greyscale pixels, palette if there
3690 are less than 256 colors, ...
3691 Updates values of mode with a potentially smaller color model. mode_out should
3692 contain the user chosen color model, but will be overwritten with the new chosen one.*/
lodepng_auto_choose_color(LodePNGColorMode * mode_out,const unsigned char * image,unsigned w,unsigned h,const LodePNGColorMode * mode_in)3693 unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
3694 const unsigned char* image, unsigned w, unsigned h,
3695 const LodePNGColorMode* mode_in)
3696 {
3697 LodePNGColorProfile prof;
3698 unsigned error = 0;
3699 unsigned i, n, palettebits, grey_ok, palette_ok;
3700
3701 lodepng_color_profile_init(&prof);
3702 error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
3703 if(error) return error;
3704 mode_out->key_defined = 0;
3705
3706 if(prof.key && w * h <= 16)
3707 {
3708 prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
3709 if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3710 }
3711 grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/
3712 n = prof.numcolors;
3713 palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
3714 palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;
3715 if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
3716 if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/
3717
3718 if(palette_ok)
3719 {
3720 unsigned char* p = prof.palette;
3721 lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
3722 for(i = 0; i != prof.numcolors; ++i)
3723 {
3724 error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
3725 if(error) break;
3726 }
3727
3728 mode_out->colortype = LCT_PALETTE;
3729 mode_out->bitdepth = palettebits;
3730
3731 if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
3732 && mode_in->bitdepth == mode_out->bitdepth)
3733 {
3734 /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
3735 lodepng_color_mode_cleanup(mode_out);
3736 lodepng_color_mode_copy(mode_out, mode_in);
3737 }
3738 }
3739 else /*8-bit or 16-bit per channel*/
3740 {
3741 mode_out->bitdepth = prof.bits;
3742 mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA)
3743 : (prof.colored ? LCT_RGB : LCT_GREY);
3744
3745 if(prof.key && !prof.alpha)
3746 {
3747 unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/
3748 mode_out->key_r = prof.key_r & mask;
3749 mode_out->key_g = prof.key_g & mask;
3750 mode_out->key_b = prof.key_b & mask;
3751 mode_out->key_defined = 1;
3752 }
3753 }
3754
3755 return error;
3756 }
3757
3758 #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3759
3760 /*
3761 Paeth predicter, used by PNG filter type 4
3762 The parameters are of type short, but should come from unsigned chars, the shorts
3763 are only needed to make the paeth calculation correct.
3764 */
paethPredictor(short a,short b,short c)3765 static unsigned char paethPredictor(short a, short b, short c)
3766 {
3767 short pa = abs(b - c);
3768 short pb = abs(a - c);
3769 short pc = abs(a + b - c - c);
3770
3771 if(pc < pa && pc < pb) return (unsigned char)c;
3772 else if(pb < pa) return (unsigned char)b;
3773 else return (unsigned char)a;
3774 }
3775
3776 /*shared values used by multiple Adam7 related functions*/
3777
3778 static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3779 static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3780 static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3781 static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3782
3783 /*
3784 Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3785 passw: output containing the width of the 7 passes
3786 passh: output containing the height of the 7 passes
3787 filter_passstart: output containing the index of the start and end of each
3788 reduced image with filter bytes
3789 padded_passstart output containing the index of the start and end of each
3790 reduced image when without filter bytes but with padded scanlines
3791 passstart: output containing the index of the start and end of each reduced
3792 image without padding between scanlines, but still padding between the images
3793 w, h: width and height of non-interlaced image
3794 bpp: bits per pixel
3795 "padded" is only relevant if bpp is less than 8 and a scanline or image does not
3796 end at a full byte
3797 */
Adam7_getpassvalues(unsigned passw[7],unsigned passh[7],size_t filter_passstart[8],size_t padded_passstart[8],size_t passstart[8],unsigned w,unsigned h,unsigned bpp)3798 static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
3799 size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
3800 {
3801 /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3802 unsigned i;
3803
3804 /*calculate width and height in pixels of each pass*/
3805 for(i = 0; i != 7; ++i)
3806 {
3807 passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
3808 passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
3809 if(passw[i] == 0) passh[i] = 0;
3810 if(passh[i] == 0) passw[i] = 0;
3811 }
3812
3813 filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
3814 for(i = 0; i != 7; ++i)
3815 {
3816 /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3817 filter_passstart[i + 1] = filter_passstart[i]
3818 + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
3819 /*bits padded if needed to fill full byte at end of each scanline*/
3820 padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
3821 /*only padded at end of reduced image*/
3822 passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
3823 }
3824 }
3825
3826 #ifdef LODEPNG_COMPILE_DECODER
3827
3828 /* ////////////////////////////////////////////////////////////////////////// */
3829 /* / PNG Decoder / */
3830 /* ////////////////////////////////////////////////////////////////////////// */
3831
3832 /*read the information from the header and store it in the LodePNGInfo. return value is error*/
lodepng_inspect(unsigned * w,unsigned * h,LodePNGState * state,const unsigned char * in,size_t insize)3833 unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
3834 const unsigned char* in, size_t insize)
3835 {
3836 LodePNGInfo* info = &state->info_png;
3837 if(insize == 0 || in == 0)
3838 {
3839 CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
3840 }
3841 if(insize < 33)
3842 {
3843 CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
3844 }
3845
3846 /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3847 lodepng_info_cleanup(info);
3848 lodepng_info_init(info);
3849
3850 if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
3851 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
3852 {
3853 CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3854 }
3855 if(lodepng_chunk_length(in + 8) != 13)
3856 {
3857 CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
3858 }
3859 if(!lodepng_chunk_type_equals(in + 8, "IHDR"))
3860 {
3861 CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
3862 }
3863
3864 /*read the values given in the header*/
3865 *w = lodepng_read32bitInt(&in[16]);
3866 *h = lodepng_read32bitInt(&in[20]);
3867 info->color.bitdepth = in[24];
3868 info->color.colortype = (LodePNGColorType)in[25];
3869 info->compression_method = in[26];
3870 info->filter_method = in[27];
3871 info->interlace_method = in[28];
3872
3873 if(*w == 0 || *h == 0)
3874 {
3875 CERROR_RETURN_ERROR(state->error, 93);
3876 }
3877
3878 if(!state->decoder.ignore_crc)
3879 {
3880 unsigned CRC = lodepng_read32bitInt(&in[29]);
3881 unsigned checksum = lodepng_crc32(&in[12], 17);
3882 if(CRC != checksum)
3883 {
3884 CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
3885 }
3886 }
3887
3888 /*error: only compression method 0 is allowed in the specification*/
3889 if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
3890 /*error: only filter method 0 is allowed in the specification*/
3891 if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
3892 /*error: only interlace methods 0 and 1 exist in the specification*/
3893 if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
3894
3895 state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
3896 return state->error;
3897 }
3898
unfilterScanline(unsigned char * recon,const unsigned char * scanline,const unsigned char * precon,size_t bytewidth,unsigned char filterType,size_t length)3899 static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
3900 size_t bytewidth, unsigned char filterType, size_t length)
3901 {
3902 /*
3903 For PNG filter method 0
3904 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
3905 the filter works byte per byte (bytewidth = 1)
3906 precon is the previous unfiltered scanline, recon the result, scanline the current one
3907 the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
3908 recon and scanline MAY be the same memory address! precon must be disjoint.
3909 */
3910
3911 size_t i;
3912 switch(filterType)
3913 {
3914 case 0:
3915 for(i = 0; i != length; ++i) recon[i] = scanline[i];
3916 break;
3917 case 1:
3918 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3919 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
3920 break;
3921 case 2:
3922 if(precon)
3923 {
3924 for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
3925 }
3926 else
3927 {
3928 for(i = 0; i != length; ++i) recon[i] = scanline[i];
3929 }
3930 break;
3931 case 3:
3932 if(precon)
3933 {
3934 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1);
3935 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1);
3936 }
3937 else
3938 {
3939 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3940 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1);
3941 }
3942 break;
3943 case 4:
3944 if(precon)
3945 {
3946 for(i = 0; i != bytewidth; ++i)
3947 {
3948 recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
3949 }
3950 for(i = bytewidth; i < length; ++i)
3951 {
3952 recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
3953 }
3954 }
3955 else
3956 {
3957 for(i = 0; i != bytewidth; ++i)
3958 {
3959 recon[i] = scanline[i];
3960 }
3961 for(i = bytewidth; i < length; ++i)
3962 {
3963 /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
3964 recon[i] = (scanline[i] + recon[i - bytewidth]);
3965 }
3966 }
3967 break;
3968 default: return 36; /*error: unexisting filter type given*/
3969 }
3970 return 0;
3971 }
3972
unfilter(unsigned char * out,const unsigned char * in,unsigned w,unsigned h,unsigned bpp)3973 static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
3974 {
3975 /*
3976 For PNG filter method 0
3977 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
3978 out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
3979 w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
3980 in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
3981 */
3982
3983 unsigned y;
3984 unsigned char* prevline = 0;
3985
3986 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
3987 size_t bytewidth = (bpp + 7) / 8;
3988 size_t linebytes = (w * bpp + 7) / 8;
3989
3990 for(y = 0; y < h; ++y)
3991 {
3992 size_t outindex = linebytes * y;
3993 size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
3994 unsigned char filterType = in[inindex];
3995
3996 CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
3997
3998 prevline = &out[outindex];
3999 }
4000
4001 return 0;
4002 }
4003
4004 /*
4005 in: Adam7 interlaced image, with no padding bits between scanlines, but between
4006 reduced images so that each reduced image starts at a byte.
4007 out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4008 bpp: bits per pixel
4009 out has the following size in bits: w * h * bpp.
4010 in is possibly bigger due to padding bits between reduced images.
4011 out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4012 (because that's likely a little bit faster)
4013 NOTE: comments about padding bits are only relevant if bpp < 8
4014 */
Adam7_deinterlace(unsigned char * out,const unsigned char * in,unsigned w,unsigned h,unsigned bpp)4015 static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4016 {
4017 unsigned passw[7], passh[7];
4018 size_t filter_passstart[8], padded_passstart[8], passstart[8];
4019 unsigned i;
4020
4021 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4022
4023 if(bpp >= 8)
4024 {
4025 for(i = 0; i != 7; ++i)
4026 {
4027 unsigned x, y, b;
4028 size_t bytewidth = bpp / 8;
4029 for(y = 0; y < passh[i]; ++y)
4030 for(x = 0; x < passw[i]; ++x)
4031 {
4032 size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4033 size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
4034 for(b = 0; b < bytewidth; ++b)
4035 {
4036 out[pixeloutstart + b] = in[pixelinstart + b];
4037 }
4038 }
4039 }
4040 }
4041 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4042 {
4043 for(i = 0; i != 7; ++i)
4044 {
4045 unsigned x, y, b;
4046 unsigned ilinebits = bpp * passw[i];
4047 unsigned olinebits = bpp * w;
4048 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4049 for(y = 0; y < passh[i]; ++y)
4050 for(x = 0; x < passw[i]; ++x)
4051 {
4052 ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4053 obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
4054 for(b = 0; b < bpp; ++b)
4055 {
4056 unsigned char bit = readBitFromReversedStream(&ibp, in);
4057 /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4058 setBitOfReversedStream0(&obp, out, bit);
4059 }
4060 }
4061 }
4062 }
4063 }
4064
removePaddingBits(unsigned char * out,const unsigned char * in,size_t olinebits,size_t ilinebits,unsigned h)4065 static void removePaddingBits(unsigned char* out, const unsigned char* in,
4066 size_t olinebits, size_t ilinebits, unsigned h)
4067 {
4068 /*
4069 After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4070 to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4071 for the Adam7 code, the color convert code and the output to the user.
4072 in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4073 have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4074 also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4075 only useful if (ilinebits - olinebits) is a value in the range 1..7
4076 */
4077 unsigned y;
4078 size_t diff = ilinebits - olinebits;
4079 size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4080 for(y = 0; y < h; ++y)
4081 {
4082 size_t x;
4083 for(x = 0; x < olinebits; ++x)
4084 {
4085 unsigned char bit = readBitFromReversedStream(&ibp, in);
4086 setBitOfReversedStream(&obp, out, bit);
4087 }
4088 ibp += diff;
4089 }
4090 }
4091
4092 /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4093 the IDAT chunks (with filter index bytes and possible padding bits)
4094 return value is error*/
postProcessScanlines(unsigned char * out,unsigned char * in,unsigned w,unsigned h,const LodePNGInfo * info_png)4095 static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4096 unsigned w, unsigned h, const LodePNGInfo* info_png)
4097 {
4098 /*
4099 This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4100 Steps:
4101 *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4102 *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4103 NOTE: the in buffer will be overwritten with intermediate data!
4104 */
4105 unsigned bpp = lodepng_get_bpp(&info_png->color);
4106 if(bpp == 0) return 31; /*error: invalid colortype*/
4107
4108 if(info_png->interlace_method == 0)
4109 {
4110 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
4111 {
4112 CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4113 removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
4114 }
4115 /*we can immediately filter into the out buffer, no other steps needed*/
4116 else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4117 }
4118 else /*interlace_method is 1 (Adam7)*/
4119 {
4120 unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4121 unsigned i;
4122
4123 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4124
4125 for(i = 0; i != 7; ++i)
4126 {
4127 CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4128 /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4129 move bytes instead of bits or move not at all*/
4130 if(bpp < 8)
4131 {
4132 /*remove padding bits in scanlines; after this there still may be padding
4133 bits between the different reduced images: each reduced image still starts nicely at a byte*/
4134 removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4135 ((passw[i] * bpp + 7) / 8) * 8, passh[i]);
4136 }
4137 }
4138
4139 Adam7_deinterlace(out, in, w, h, bpp);
4140 }
4141
4142 return 0;
4143 }
4144
readChunk_PLTE(LodePNGColorMode * color,const unsigned char * data,size_t chunkLength)4145 static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4146 {
4147 unsigned pos = 0, i;
4148 if(color->palette) lodepng_free(color->palette);
4149 color->palettesize = chunkLength / 3;
4150 color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize);
4151 if(!color->palette && color->palettesize)
4152 {
4153 color->palettesize = 0;
4154 return 83; /*alloc fail*/
4155 }
4156 if(color->palettesize > 256) return 38; /*error: palette too big*/
4157
4158 for(i = 0; i != color->palettesize; ++i)
4159 {
4160 color->palette[4 * i + 0] = data[pos++]; /*R*/
4161 color->palette[4 * i + 1] = data[pos++]; /*G*/
4162 color->palette[4 * i + 2] = data[pos++]; /*B*/
4163 color->palette[4 * i + 3] = 255; /*alpha*/
4164 }
4165
4166 return 0; /* OK */
4167 }
4168
readChunk_tRNS(LodePNGColorMode * color,const unsigned char * data,size_t chunkLength)4169 static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4170 {
4171 unsigned i;
4172 if(color->colortype == LCT_PALETTE)
4173 {
4174 /*error: more alpha values given than there are palette entries*/
4175 if(chunkLength > color->palettesize) return 38;
4176
4177 for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
4178 }
4179 else if(color->colortype == LCT_GREY)
4180 {
4181 /*error: this chunk must be 2 bytes for greyscale image*/
4182 if(chunkLength != 2) return 30;
4183
4184 color->key_defined = 1;
4185 color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
4186 }
4187 else if(color->colortype == LCT_RGB)
4188 {
4189 /*error: this chunk must be 6 bytes for RGB image*/
4190 if(chunkLength != 6) return 41;
4191
4192 color->key_defined = 1;
4193 color->key_r = 256u * data[0] + data[1];
4194 color->key_g = 256u * data[2] + data[3];
4195 color->key_b = 256u * data[4] + data[5];
4196 }
4197 else return 42; /*error: tRNS chunk not allowed for other color models*/
4198
4199 return 0; /* OK */
4200 }
4201
4202
4203 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4204 /*background color chunk (bKGD)*/
readChunk_bKGD(LodePNGInfo * info,const unsigned char * data,size_t chunkLength)4205 static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4206 {
4207 if(info->color.colortype == LCT_PALETTE)
4208 {
4209 /*error: this chunk must be 1 byte for indexed color image*/
4210 if(chunkLength != 1) return 43;
4211
4212 info->background_defined = 1;
4213 info->background_r = info->background_g = info->background_b = data[0];
4214 }
4215 else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
4216 {
4217 /*error: this chunk must be 2 bytes for greyscale image*/
4218 if(chunkLength != 2) return 44;
4219
4220 info->background_defined = 1;
4221 info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
4222 }
4223 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
4224 {
4225 /*error: this chunk must be 6 bytes for greyscale image*/
4226 if(chunkLength != 6) return 45;
4227
4228 info->background_defined = 1;
4229 info->background_r = 256u * data[0] + data[1];
4230 info->background_g = 256u * data[2] + data[3];
4231 info->background_b = 256u * data[4] + data[5];
4232 }
4233
4234 return 0; /* OK */
4235 }
4236
4237 /*text chunk (tEXt)*/
readChunk_tEXt(LodePNGInfo * info,const unsigned char * data,size_t chunkLength)4238 static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4239 {
4240 unsigned error = 0;
4241 char *key = 0, *str = 0;
4242 unsigned i;
4243
4244 while(!error) /*not really a while loop, only used to break on error*/
4245 {
4246 unsigned length, string2_begin;
4247
4248 length = 0;
4249 while(length < chunkLength && data[length] != 0) ++length;
4250 /*even though it's not allowed by the standard, no error is thrown if
4251 there's no null termination char, if the text is empty*/
4252 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4253
4254 key = (char*)lodepng_malloc(length + 1);
4255 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4256
4257 key[length] = 0;
4258 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4259
4260 string2_begin = length + 1; /*skip keyword null terminator*/
4261
4262 length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
4263 str = (char*)lodepng_malloc(length + 1);
4264 if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
4265
4266 str[length] = 0;
4267 for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
4268
4269 error = lodepng_add_text(info, key, str);
4270
4271 break;
4272 }
4273
4274 lodepng_free(key);
4275 lodepng_free(str);
4276
4277 return error;
4278 }
4279
4280 /*compressed text chunk (zTXt)*/
readChunk_zTXt(LodePNGInfo * info,const LodePNGDecompressSettings * zlibsettings,const unsigned char * data,size_t chunkLength)4281 static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4282 const unsigned char* data, size_t chunkLength)
4283 {
4284 unsigned error = 0;
4285 unsigned i;
4286
4287 unsigned length, string2_begin;
4288 char *key = 0;
4289 ucvector decoded;
4290
4291 ucvector_init(&decoded);
4292
4293 while(!error) /*not really a while loop, only used to break on error*/
4294 {
4295 for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4296 if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4297 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4298
4299 key = (char*)lodepng_malloc(length + 1);
4300 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4301
4302 key[length] = 0;
4303 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4304
4305 if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4306
4307 string2_begin = length + 2;
4308 if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4309
4310 length = chunkLength - string2_begin;
4311 /*will fail if zlib error, e.g. if length is too small*/
4312 error = zlib_decompress(&decoded.data, &decoded.size,
4313 (unsigned char*)(&data[string2_begin]),
4314 length, zlibsettings);
4315 if(error) break;
4316 ucvector_push_back(&decoded, 0);
4317
4318 error = lodepng_add_text(info, key, (char*)decoded.data);
4319
4320 break;
4321 }
4322
4323 lodepng_free(key);
4324 ucvector_cleanup(&decoded);
4325
4326 return error;
4327 }
4328
4329 /*international text chunk (iTXt)*/
readChunk_iTXt(LodePNGInfo * info,const LodePNGDecompressSettings * zlibsettings,const unsigned char * data,size_t chunkLength)4330 static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4331 const unsigned char* data, size_t chunkLength)
4332 {
4333 unsigned error = 0;
4334 unsigned i;
4335
4336 unsigned length, begin, compressed;
4337 char *key = 0, *langtag = 0, *transkey = 0;
4338 ucvector decoded;
4339 ucvector_init(&decoded);
4340
4341 while(!error) /*not really a while loop, only used to break on error*/
4342 {
4343 /*Quick check if the chunk length isn't too small. Even without check
4344 it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4345 if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
4346
4347 /*read the key*/
4348 for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4349 if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
4350 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4351
4352 key = (char*)lodepng_malloc(length + 1);
4353 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4354
4355 key[length] = 0;
4356 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4357
4358 /*read the compression method*/
4359 compressed = data[length + 1];
4360 if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4361
4362 /*even though it's not allowed by the standard, no error is thrown if
4363 there's no null termination char, if the text is empty for the next 3 texts*/
4364
4365 /*read the langtag*/
4366 begin = length + 3;
4367 length = 0;
4368 for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4369
4370 langtag = (char*)lodepng_malloc(length + 1);
4371 if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
4372
4373 langtag[length] = 0;
4374 for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
4375
4376 /*read the transkey*/
4377 begin += length + 1;
4378 length = 0;
4379 for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4380
4381 transkey = (char*)lodepng_malloc(length + 1);
4382 if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
4383
4384 transkey[length] = 0;
4385 for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
4386
4387 /*read the actual text*/
4388 begin += length + 1;
4389
4390 length = chunkLength < begin ? 0 : chunkLength - begin;
4391
4392 if(compressed)
4393 {
4394 /*will fail if zlib error, e.g. if length is too small*/
4395 error = zlib_decompress(&decoded.data, &decoded.size,
4396 (unsigned char*)(&data[begin]),
4397 length, zlibsettings);
4398 if(error) break;
4399 if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
4400 ucvector_push_back(&decoded, 0);
4401 }
4402 else
4403 {
4404 if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
4405
4406 decoded.data[length] = 0;
4407 for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
4408 }
4409
4410 error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
4411
4412 break;
4413 }
4414
4415 lodepng_free(key);
4416 lodepng_free(langtag);
4417 lodepng_free(transkey);
4418 ucvector_cleanup(&decoded);
4419
4420 return error;
4421 }
4422
readChunk_tIME(LodePNGInfo * info,const unsigned char * data,size_t chunkLength)4423 static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4424 {
4425 if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
4426
4427 info->time_defined = 1;
4428 info->time.year = 256u * data[0] + data[1];
4429 info->time.month = data[2];
4430 info->time.day = data[3];
4431 info->time.hour = data[4];
4432 info->time.minute = data[5];
4433 info->time.second = data[6];
4434
4435 return 0; /* OK */
4436 }
4437
readChunk_pHYs(LodePNGInfo * info,const unsigned char * data,size_t chunkLength)4438 static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4439 {
4440 if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
4441
4442 info->phys_defined = 1;
4443 info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
4444 info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
4445 info->phys_unit = data[8];
4446
4447 return 0; /* OK */
4448 }
4449 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4450
4451 /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
decodeGeneric(unsigned char ** out,unsigned * w,unsigned * h,LodePNGState * state,const unsigned char * in,size_t insize)4452 static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
4453 LodePNGState* state,
4454 const unsigned char* in, size_t insize)
4455 {
4456 unsigned char IEND = 0;
4457 const unsigned char* chunk;
4458 size_t i;
4459 ucvector idat; /*the data from idat chunks*/
4460 ucvector scanlines;
4461 size_t predict;
4462 size_t numpixels;
4463
4464 /*for unknown chunk order*/
4465 unsigned unknown = 0;
4466 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4467 unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4468 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4469
4470 /*provide some proper output values if error will happen*/
4471 *out = 0;
4472
4473 state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
4474 if(state->error) return;
4475
4476 numpixels = *w * *h;
4477
4478 /*multiplication overflow*/
4479 if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92);
4480 /*multiplication overflow possible further below. Allows up to 2^31-1 pixel
4481 bytes with 16-bit RGBA, the rest is room for filter bytes.*/
4482 if(numpixels > 268435455) CERROR_RETURN(state->error, 92);
4483
4484 ucvector_init(&idat);
4485 chunk = &in[33]; /*first byte of the first chunk after the header*/
4486
4487 /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4488 IDAT data is put at the start of the in buffer*/
4489 while(!IEND && !state->error)
4490 {
4491 unsigned chunkLength;
4492 const unsigned char* data; /*the data in the chunk*/
4493
4494 /*error: size of the in buffer too small to contain next chunk*/
4495 if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
4496
4497 /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4498 chunkLength = lodepng_chunk_length(chunk);
4499 /*error: chunk length larger than the max PNG chunk size*/
4500 if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
4501
4502 if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
4503 {
4504 CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
4505 }
4506
4507 data = lodepng_chunk_data_const(chunk);
4508
4509 /*IDAT chunk, containing compressed image data*/
4510 if(lodepng_chunk_type_equals(chunk, "IDAT"))
4511 {
4512 size_t oldsize = idat.size;
4513 if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4514 for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
4515 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4516 critical_pos = 3;
4517 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4518 }
4519 /*IEND chunk*/
4520 else if(lodepng_chunk_type_equals(chunk, "IEND"))
4521 {
4522 IEND = 1;
4523 }
4524 /*palette chunk (PLTE)*/
4525 else if(lodepng_chunk_type_equals(chunk, "PLTE"))
4526 {
4527 state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
4528 if(state->error) break;
4529 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4530 critical_pos = 2;
4531 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4532 }
4533 /*palette transparency chunk (tRNS)*/
4534 else if(lodepng_chunk_type_equals(chunk, "tRNS"))
4535 {
4536 state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
4537 if(state->error) break;
4538 }
4539 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4540 /*background color chunk (bKGD)*/
4541 else if(lodepng_chunk_type_equals(chunk, "bKGD"))
4542 {
4543 state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
4544 if(state->error) break;
4545 }
4546 /*text chunk (tEXt)*/
4547 else if(lodepng_chunk_type_equals(chunk, "tEXt"))
4548 {
4549 if(state->decoder.read_text_chunks)
4550 {
4551 state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
4552 if(state->error) break;
4553 }
4554 }
4555 /*compressed text chunk (zTXt)*/
4556 else if(lodepng_chunk_type_equals(chunk, "zTXt"))
4557 {
4558 if(state->decoder.read_text_chunks)
4559 {
4560 state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4561 if(state->error) break;
4562 }
4563 }
4564 /*international text chunk (iTXt)*/
4565 else if(lodepng_chunk_type_equals(chunk, "iTXt"))
4566 {
4567 if(state->decoder.read_text_chunks)
4568 {
4569 state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4570 if(state->error) break;
4571 }
4572 }
4573 else if(lodepng_chunk_type_equals(chunk, "tIME"))
4574 {
4575 state->error = readChunk_tIME(&state->info_png, data, chunkLength);
4576 if(state->error) break;
4577 }
4578 else if(lodepng_chunk_type_equals(chunk, "pHYs"))
4579 {
4580 state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
4581 if(state->error) break;
4582 }
4583 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4584 else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4585 {
4586 /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4587 if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
4588
4589 unknown = 1;
4590 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4591 if(state->decoder.remember_unknown_chunks)
4592 {
4593 state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
4594 &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
4595 if(state->error) break;
4596 }
4597 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4598 }
4599
4600 if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
4601 {
4602 if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
4603 }
4604
4605 if(!IEND) chunk = lodepng_chunk_next_const(chunk);
4606 }
4607
4608 ucvector_init(&scanlines);
4609 /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
4610 If the decompressed size does not match the prediction, the image must be corrupt.*/
4611 if(state->info_png.interlace_method == 0)
4612 {
4613 /*The extra *h is added because this are the filter bytes every scanline starts with*/
4614 predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h;
4615 }
4616 else
4617 {
4618 /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
4619 const LodePNGColorMode* color = &state->info_png.color;
4620 predict = 0;
4621 predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
4622 if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
4623 predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3);
4624 if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2);
4625 predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2);
4626 if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1);
4627 predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1);
4628 }
4629 if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
4630 if(!state->error)
4631 {
4632 state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
4633 idat.size, &state->decoder.zlibsettings);
4634 if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/
4635 }
4636 ucvector_cleanup(&idat);
4637
4638 if(!state->error)
4639 {
4640 size_t outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
4641 *out = (unsigned char*)lodepng_malloc(outsize);
4642 if(!*out) state->error = 83; /*alloc fail*/
4643 for(i = 0; i < outsize; i++) (*out)[i] = 0;
4644 if(!state->error) state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png);
4645 }
4646 ucvector_cleanup(&scanlines);
4647 }
4648
lodepng_decode(unsigned char ** out,unsigned * w,unsigned * h,LodePNGState * state,const unsigned char * in,size_t insize)4649 unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
4650 LodePNGState* state,
4651 const unsigned char* in, size_t insize)
4652 {
4653 *out = 0;
4654 decodeGeneric(out, w, h, state, in, insize);
4655 if(state->error) return state->error;
4656 if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
4657 {
4658 /*same color type, no copying or converting of data needed*/
4659 /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4660 the raw image has to the end user*/
4661 if(!state->decoder.color_convert)
4662 {
4663 state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
4664 if(state->error) return state->error;
4665 }
4666 }
4667 else
4668 {
4669 /*color conversion needed; sort of copy of the data*/
4670 unsigned char* data = *out;
4671 size_t outsize;
4672
4673 /*TODO: check if this works according to the statement in the documentation: "The converter can convert
4674 from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4675 if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
4676 && !(state->info_raw.bitdepth == 8))
4677 {
4678 return 56; /*unsupported color mode conversion*/
4679 }
4680
4681 outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
4682 *out = (unsigned char*)lodepng_malloc(outsize);
4683 if(!(*out))
4684 {
4685 state->error = 83; /*alloc fail*/
4686 }
4687 else state->error = lodepng_convert(*out, data, &state->info_raw,
4688 &state->info_png.color, *w, *h);
4689 lodepng_free(data);
4690 }
4691 return state->error;
4692 }
4693
lodepng_decode_memory(unsigned char ** out,unsigned * w,unsigned * h,const unsigned char * in,size_t insize,LodePNGColorType colortype,unsigned bitdepth)4694 unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
4695 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
4696 {
4697 unsigned error;
4698 LodePNGState state;
4699 lodepng_state_init(&state);
4700 state.info_raw.colortype = colortype;
4701 state.info_raw.bitdepth = bitdepth;
4702 error = lodepng_decode(out, w, h, &state, in, insize);
4703 lodepng_state_cleanup(&state);
4704 return error;
4705 }
4706
lodepng_decode32(unsigned char ** out,unsigned * w,unsigned * h,const unsigned char * in,size_t insize)4707 unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4708 {
4709 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
4710 }
4711
lodepng_decode24(unsigned char ** out,unsigned * w,unsigned * h,const unsigned char * in,size_t insize)4712 unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4713 {
4714 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
4715 }
4716
4717 #ifdef LODEPNG_COMPILE_DISK
lodepng_decode_file(unsigned char ** out,unsigned * w,unsigned * h,const char * filename,LodePNGColorType colortype,unsigned bitdepth)4718 unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
4719 LodePNGColorType colortype, unsigned bitdepth)
4720 {
4721 unsigned char* buffer;
4722 size_t buffersize;
4723 unsigned error;
4724 error = lodepng_load_file(&buffer, &buffersize, filename);
4725 if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
4726 lodepng_free(buffer);
4727 return error;
4728 }
4729
lodepng_decode32_file(unsigned char ** out,unsigned * w,unsigned * h,const char * filename)4730 unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4731 {
4732 return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
4733 }
4734
lodepng_decode24_file(unsigned char ** out,unsigned * w,unsigned * h,const char * filename)4735 unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4736 {
4737 return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
4738 }
4739 #endif /*LODEPNG_COMPILE_DISK*/
4740
lodepng_decoder_settings_init(LodePNGDecoderSettings * settings)4741 void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
4742 {
4743 settings->color_convert = 1;
4744 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4745 settings->read_text_chunks = 1;
4746 settings->remember_unknown_chunks = 0;
4747 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4748 settings->ignore_crc = 0;
4749 lodepng_decompress_settings_init(&settings->zlibsettings);
4750 }
4751
4752 #endif /*LODEPNG_COMPILE_DECODER*/
4753
4754 #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4755
lodepng_state_init(LodePNGState * state)4756 void lodepng_state_init(LodePNGState* state)
4757 {
4758 #ifdef LODEPNG_COMPILE_DECODER
4759 lodepng_decoder_settings_init(&state->decoder);
4760 #endif /*LODEPNG_COMPILE_DECODER*/
4761 #ifdef LODEPNG_COMPILE_ENCODER
4762 lodepng_encoder_settings_init(&state->encoder);
4763 #endif /*LODEPNG_COMPILE_ENCODER*/
4764 lodepng_color_mode_init(&state->info_raw);
4765 lodepng_info_init(&state->info_png);
4766 state->error = 1;
4767 }
4768
lodepng_state_cleanup(LodePNGState * state)4769 void lodepng_state_cleanup(LodePNGState* state)
4770 {
4771 lodepng_color_mode_cleanup(&state->info_raw);
4772 lodepng_info_cleanup(&state->info_png);
4773 }
4774
lodepng_state_copy(LodePNGState * dest,const LodePNGState * source)4775 void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
4776 {
4777 lodepng_state_cleanup(dest);
4778 *dest = *source;
4779 lodepng_color_mode_init(&dest->info_raw);
4780 lodepng_info_init(&dest->info_png);
4781 dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
4782 dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
4783 }
4784
4785 #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4786
4787 #ifdef LODEPNG_COMPILE_ENCODER
4788
4789 /* ////////////////////////////////////////////////////////////////////////// */
4790 /* / PNG Encoder / */
4791 /* ////////////////////////////////////////////////////////////////////////// */
4792
4793 /*chunkName must be string of 4 characters*/
addChunk(ucvector * out,const char * chunkName,const unsigned char * data,size_t length)4794 static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
4795 {
4796 CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
4797 out->allocsize = out->size; /*fix the allocsize again*/
4798 return 0;
4799 }
4800
writeSignature(ucvector * out)4801 static void writeSignature(ucvector* out)
4802 {
4803 /*8 bytes PNG signature, aka the magic bytes*/
4804 ucvector_push_back(out, 137);
4805 ucvector_push_back(out, 80);
4806 ucvector_push_back(out, 78);
4807 ucvector_push_back(out, 71);
4808 ucvector_push_back(out, 13);
4809 ucvector_push_back(out, 10);
4810 ucvector_push_back(out, 26);
4811 ucvector_push_back(out, 10);
4812 }
4813
addChunk_IHDR(ucvector * out,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth,unsigned interlace_method)4814 static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
4815 LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
4816 {
4817 unsigned error = 0;
4818 ucvector header;
4819 ucvector_init(&header);
4820
4821 lodepng_add32bitInt(&header, w); /*width*/
4822 lodepng_add32bitInt(&header, h); /*height*/
4823 ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
4824 ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
4825 ucvector_push_back(&header, 0); /*compression method*/
4826 ucvector_push_back(&header, 0); /*filter method*/
4827 ucvector_push_back(&header, interlace_method); /*interlace method*/
4828
4829 error = addChunk(out, "IHDR", header.data, header.size);
4830 ucvector_cleanup(&header);
4831
4832 return error;
4833 }
4834
addChunk_PLTE(ucvector * out,const LodePNGColorMode * info)4835 static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
4836 {
4837 unsigned error = 0;
4838 size_t i;
4839 ucvector PLTE;
4840 ucvector_init(&PLTE);
4841 for(i = 0; i != info->palettesize * 4; ++i)
4842 {
4843 /*add all channels except alpha channel*/
4844 if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
4845 }
4846 error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
4847 ucvector_cleanup(&PLTE);
4848
4849 return error;
4850 }
4851
addChunk_tRNS(ucvector * out,const LodePNGColorMode * info)4852 static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
4853 {
4854 unsigned error = 0;
4855 size_t i;
4856 ucvector tRNS;
4857 ucvector_init(&tRNS);
4858 if(info->colortype == LCT_PALETTE)
4859 {
4860 size_t amount = info->palettesize;
4861 /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4862 for(i = info->palettesize; i != 0; --i)
4863 {
4864 if(info->palette[4 * (i - 1) + 3] == 255) --amount;
4865 else break;
4866 }
4867 /*add only alpha channel*/
4868 for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
4869 }
4870 else if(info->colortype == LCT_GREY)
4871 {
4872 if(info->key_defined)
4873 {
4874 ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
4875 ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
4876 }
4877 }
4878 else if(info->colortype == LCT_RGB)
4879 {
4880 if(info->key_defined)
4881 {
4882 ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
4883 ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
4884 ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8));
4885 ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
4886 ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
4887 ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
4888 }
4889 }
4890
4891 error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
4892 ucvector_cleanup(&tRNS);
4893
4894 return error;
4895 }
4896
addChunk_IDAT(ucvector * out,const unsigned char * data,size_t datasize,LodePNGCompressSettings * zlibsettings)4897 static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
4898 LodePNGCompressSettings* zlibsettings)
4899 {
4900 ucvector zlibdata;
4901 unsigned error = 0;
4902
4903 /*compress with the Zlib compressor*/
4904 ucvector_init(&zlibdata);
4905 error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
4906 if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
4907 ucvector_cleanup(&zlibdata);
4908
4909 return error;
4910 }
4911
addChunk_IEND(ucvector * out)4912 static unsigned addChunk_IEND(ucvector* out)
4913 {
4914 unsigned error = 0;
4915 error = addChunk(out, "IEND", 0, 0);
4916 return error;
4917 }
4918
4919 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4920
addChunk_tEXt(ucvector * out,const char * keyword,const char * textstring)4921 static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
4922 {
4923 unsigned error = 0;
4924 size_t i;
4925 ucvector text;
4926 ucvector_init(&text);
4927 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
4928 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4929 ucvector_push_back(&text, 0); /*0 termination char*/
4930 for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
4931 error = addChunk(out, "tEXt", text.data, text.size);
4932 ucvector_cleanup(&text);
4933
4934 return error;
4935 }
4936
addChunk_zTXt(ucvector * out,const char * keyword,const char * textstring,LodePNGCompressSettings * zlibsettings)4937 static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
4938 LodePNGCompressSettings* zlibsettings)
4939 {
4940 unsigned error = 0;
4941 ucvector data, compressed;
4942 size_t i, textsize = strlen(textstring);
4943
4944 ucvector_init(&data);
4945 ucvector_init(&compressed);
4946 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4947 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4948 ucvector_push_back(&data, 0); /*0 termination char*/
4949 ucvector_push_back(&data, 0); /*compression method: 0*/
4950
4951 error = zlib_compress(&compressed.data, &compressed.size,
4952 (unsigned char*)textstring, textsize, zlibsettings);
4953 if(!error)
4954 {
4955 for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
4956 error = addChunk(out, "zTXt", data.data, data.size);
4957 }
4958
4959 ucvector_cleanup(&compressed);
4960 ucvector_cleanup(&data);
4961 return error;
4962 }
4963
addChunk_iTXt(ucvector * out,unsigned compressed,const char * keyword,const char * langtag,const char * transkey,const char * textstring,LodePNGCompressSettings * zlibsettings)4964 static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
4965 const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
4966 {
4967 unsigned error = 0;
4968 ucvector data;
4969 size_t i, textsize = strlen(textstring);
4970
4971 ucvector_init(&data);
4972
4973 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4974 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4975 ucvector_push_back(&data, 0); /*null termination char*/
4976 ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
4977 ucvector_push_back(&data, 0); /*compression method*/
4978 for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
4979 ucvector_push_back(&data, 0); /*null termination char*/
4980 for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
4981 ucvector_push_back(&data, 0); /*null termination char*/
4982
4983 if(compressed)
4984 {
4985 ucvector compressed_data;
4986 ucvector_init(&compressed_data);
4987 error = zlib_compress(&compressed_data.data, &compressed_data.size,
4988 (unsigned char*)textstring, textsize, zlibsettings);
4989 if(!error)
4990 {
4991 for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
4992 }
4993 ucvector_cleanup(&compressed_data);
4994 }
4995 else /*not compressed*/
4996 {
4997 for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
4998 }
4999
5000 if(!error) error = addChunk(out, "iTXt", data.data, data.size);
5001 ucvector_cleanup(&data);
5002 return error;
5003 }
5004
addChunk_bKGD(ucvector * out,const LodePNGInfo * info)5005 static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info)
5006 {
5007 unsigned error = 0;
5008 ucvector bKGD;
5009 ucvector_init(&bKGD);
5010 if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
5011 {
5012 ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
5013 ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
5014 }
5015 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
5016 {
5017 ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
5018 ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
5019 ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8));
5020 ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255));
5021 ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8));
5022 ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255));
5023 }
5024 else if(info->color.colortype == LCT_PALETTE)
5025 {
5026 ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/
5027 }
5028
5029 error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
5030 ucvector_cleanup(&bKGD);
5031
5032 return error;
5033 }
5034
addChunk_tIME(ucvector * out,const LodePNGTime * time)5035 static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time)
5036 {
5037 unsigned error = 0;
5038 unsigned char* data = (unsigned char*)lodepng_malloc(7);
5039 if(!data) return 83; /*alloc fail*/
5040 data[0] = (unsigned char)(time->year >> 8);
5041 data[1] = (unsigned char)(time->year & 255);
5042 data[2] = (unsigned char)time->month;
5043 data[3] = (unsigned char)time->day;
5044 data[4] = (unsigned char)time->hour;
5045 data[5] = (unsigned char)time->minute;
5046 data[6] = (unsigned char)time->second;
5047 error = addChunk(out, "tIME", data, 7);
5048 lodepng_free(data);
5049 return error;
5050 }
5051
addChunk_pHYs(ucvector * out,const LodePNGInfo * info)5052 static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
5053 {
5054 unsigned error = 0;
5055 ucvector data;
5056 ucvector_init(&data);
5057
5058 lodepng_add32bitInt(&data, info->phys_x);
5059 lodepng_add32bitInt(&data, info->phys_y);
5060 ucvector_push_back(&data, info->phys_unit);
5061
5062 error = addChunk(out, "pHYs", data.data, data.size);
5063 ucvector_cleanup(&data);
5064
5065 return error;
5066 }
5067
5068 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5069
filterScanline(unsigned char * out,const unsigned char * scanline,const unsigned char * prevline,size_t length,size_t bytewidth,unsigned char filterType)5070 static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
5071 size_t length, size_t bytewidth, unsigned char filterType)
5072 {
5073 size_t i;
5074 switch(filterType)
5075 {
5076 case 0: /*None*/
5077 for(i = 0; i != length; ++i) out[i] = scanline[i];
5078 break;
5079 case 1: /*Sub*/
5080 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5081 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
5082 break;
5083 case 2: /*Up*/
5084 if(prevline)
5085 {
5086 for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
5087 }
5088 else
5089 {
5090 for(i = 0; i != length; ++i) out[i] = scanline[i];
5091 }
5092 break;
5093 case 3: /*Average*/
5094 if(prevline)
5095 {
5096 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
5097 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
5098 }
5099 else
5100 {
5101 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5102 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
5103 }
5104 break;
5105 case 4: /*Paeth*/
5106 if(prevline)
5107 {
5108 /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5109 for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
5110 for(i = bytewidth; i < length; ++i)
5111 {
5112 out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
5113 }
5114 }
5115 else
5116 {
5117 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5118 /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5119 for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
5120 }
5121 break;
5122 default: return; /*unexisting filter type given*/
5123 }
5124 }
5125
5126 /* log2 approximation. A slight bit faster than std::log. */
flog2(float f)5127 static float flog2(float f)
5128 {
5129 float result = 0;
5130 while(f > 32) { result += 4; f /= 16; }
5131 while(f > 2) { ++result; f /= 2; }
5132 return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
5133 }
5134
filter(unsigned char * out,const unsigned char * in,unsigned w,unsigned h,const LodePNGColorMode * info,const LodePNGEncoderSettings * settings)5135 static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
5136 const LodePNGColorMode* info, const LodePNGEncoderSettings* settings)
5137 {
5138 /*
5139 For PNG filter method 0
5140 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5141 the scanlines with 1 extra byte per scanline
5142 */
5143
5144 unsigned bpp = lodepng_get_bpp(info);
5145 /*the width of a scanline in bytes, not including the filter type*/
5146 size_t linebytes = (w * bpp + 7) / 8;
5147 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5148 size_t bytewidth = (bpp + 7) / 8;
5149 const unsigned char* prevline = 0;
5150 unsigned x, y;
5151 unsigned error = 0;
5152 LodePNGFilterStrategy strategy = settings->filter_strategy;
5153
5154 /*
5155 There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5156 * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5157 use fixed filtering, with the filter None).
5158 * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5159 not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5160 all five filters and select the filter that produces the smallest sum of absolute values per row.
5161 This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5162
5163 If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5164 but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5165 heuristic is used.
5166 */
5167 if(settings->filter_palette_zero &&
5168 (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
5169
5170 if(bpp == 0) return 31; /*error: invalid color type*/
5171
5172 if(strategy == LFS_ZERO)
5173 {
5174 for(y = 0; y != h; ++y)
5175 {
5176 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5177 size_t inindex = linebytes * y;
5178 out[outindex] = 0; /*filter type byte*/
5179 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
5180 prevline = &in[inindex];
5181 }
5182 }
5183 else if(strategy == LFS_MINSUM)
5184 {
5185 /*adaptive filtering*/
5186 size_t sum[5];
5187 unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
5188 size_t smallest = 0;
5189 unsigned char type, bestType = 0;
5190
5191 for(type = 0; type != 5; ++type)
5192 {
5193 attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
5194 if(!attempt[type]) return 83; /*alloc fail*/
5195 }
5196
5197 if(!error)
5198 {
5199 for(y = 0; y != h; ++y)
5200 {
5201 /*try the 5 filter types*/
5202 for(type = 0; type != 5; ++type)
5203 {
5204 filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
5205
5206 /*calculate the sum of the result*/
5207 sum[type] = 0;
5208 if(type == 0)
5209 {
5210 for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]);
5211 }
5212 else
5213 {
5214 for(x = 0; x != linebytes; ++x)
5215 {
5216 /*For differences, each byte should be treated as signed, values above 127 are negative
5217 (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5218 This means filtertype 0 is almost never chosen, but that is justified.*/
5219 unsigned char s = attempt[type][x];
5220 sum[type] += s < 128 ? s : (255U - s);
5221 }
5222 }
5223
5224 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5225 if(type == 0 || sum[type] < smallest)
5226 {
5227 bestType = type;
5228 smallest = sum[type];
5229 }
5230 }
5231
5232 prevline = &in[y * linebytes];
5233
5234 /*now fill the out values*/
5235 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5236 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
5237 }
5238 }
5239
5240 for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
5241 }
5242 else if(strategy == LFS_ENTROPY)
5243 {
5244 float sum[5];
5245 unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
5246 float smallest = 0;
5247 unsigned type, bestType = 0;
5248 unsigned count[256];
5249
5250 for(type = 0; type != 5; ++type)
5251 {
5252 attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
5253 if(!attempt[type]) return 83; /*alloc fail*/
5254 }
5255
5256 for(y = 0; y != h; ++y)
5257 {
5258 /*try the 5 filter types*/
5259 for(type = 0; type != 5; ++type)
5260 {
5261 filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
5262 for(x = 0; x != 256; ++x) count[x] = 0;
5263 for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
5264 ++count[type]; /*the filter type itself is part of the scanline*/
5265 sum[type] = 0;
5266 for(x = 0; x != 256; ++x)
5267 {
5268 float p = count[x] / (float)(linebytes + 1);
5269 sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
5270 }
5271 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5272 if(type == 0 || sum[type] < smallest)
5273 {
5274 bestType = type;
5275 smallest = sum[type];
5276 }
5277 }
5278
5279 prevline = &in[y * linebytes];
5280
5281 /*now fill the out values*/
5282 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5283 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
5284 }
5285
5286 for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
5287 }
5288 else if(strategy == LFS_PREDEFINED)
5289 {
5290 for(y = 0; y != h; ++y)
5291 {
5292 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5293 size_t inindex = linebytes * y;
5294 unsigned char type = settings->predefined_filters[y];
5295 out[outindex] = type; /*filter type byte*/
5296 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
5297 prevline = &in[inindex];
5298 }
5299 }
5300 else if(strategy == LFS_BRUTE_FORCE)
5301 {
5302 /*brute force filter chooser.
5303 deflate the scanline after every filter attempt to see which one deflates best.
5304 This is very slow and gives only slightly smaller, sometimes even larger, result*/
5305 size_t size[5];
5306 unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
5307 size_t smallest = 0;
5308 unsigned type = 0, bestType = 0;
5309 unsigned char* dummy;
5310 LodePNGCompressSettings zlibsettings = settings->zlibsettings;
5311 /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5312 to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5313 better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5314 cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5315 zlibsettings.btype = 1;
5316 /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5317 images only, so disable it*/
5318 zlibsettings.custom_zlib = 0;
5319 zlibsettings.custom_deflate = 0;
5320 for(type = 0; type != 5; ++type)
5321 {
5322 attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
5323 if(!attempt[type]) return 83; /*alloc fail*/
5324 }
5325 for(y = 0; y != h; ++y) /*try the 5 filter types*/
5326 {
5327 for(type = 0; type != 5; ++type)
5328 {
5329 unsigned testsize = linebytes;
5330 /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5331
5332 filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
5333 size[type] = 0;
5334 dummy = 0;
5335 zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
5336 lodepng_free(dummy);
5337 /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5338 if(type == 0 || size[type] < smallest)
5339 {
5340 bestType = type;
5341 smallest = size[type];
5342 }
5343 }
5344 prevline = &in[y * linebytes];
5345 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5346 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
5347 }
5348 for(type = 0; type != 5; ++type) free(attempt[type]);
5349 }
5350 else return 88; /* unknown filter strategy */
5351
5352 return error;
5353 }
5354
addPaddingBits(unsigned char * out,const unsigned char * in,size_t olinebits,size_t ilinebits,unsigned h)5355 static void addPaddingBits(unsigned char* out, const unsigned char* in,
5356 size_t olinebits, size_t ilinebits, unsigned h)
5357 {
5358 /*The opposite of the removePaddingBits function
5359 olinebits must be >= ilinebits*/
5360 unsigned y;
5361 size_t diff = olinebits - ilinebits;
5362 size_t obp = 0, ibp = 0; /*bit pointers*/
5363 for(y = 0; y != h; ++y)
5364 {
5365 size_t x;
5366 for(x = 0; x < ilinebits; ++x)
5367 {
5368 unsigned char bit = readBitFromReversedStream(&ibp, in);
5369 setBitOfReversedStream(&obp, out, bit);
5370 }
5371 /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5372 "Use of uninitialised value of size ###" warning from valgrind*/
5373 for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
5374 }
5375 }
5376
5377 /*
5378 in: non-interlaced image with size w*h
5379 out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5380 no padding bits between scanlines, but between reduced images so that each
5381 reduced image starts at a byte.
5382 bpp: bits per pixel
5383 there are no padding bits, not between scanlines, not between reduced images
5384 in has the following size in bits: w * h * bpp.
5385 out is possibly bigger due to padding bits between reduced images
5386 NOTE: comments about padding bits are only relevant if bpp < 8
5387 */
Adam7_interlace(unsigned char * out,const unsigned char * in,unsigned w,unsigned h,unsigned bpp)5388 static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
5389 {
5390 unsigned passw[7], passh[7];
5391 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5392 unsigned i;
5393
5394 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5395
5396 if(bpp >= 8)
5397 {
5398 for(i = 0; i != 7; ++i)
5399 {
5400 unsigned x, y, b;
5401 size_t bytewidth = bpp / 8;
5402 for(y = 0; y < passh[i]; ++y)
5403 for(x = 0; x < passw[i]; ++x)
5404 {
5405 size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
5406 size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
5407 for(b = 0; b < bytewidth; ++b)
5408 {
5409 out[pixeloutstart + b] = in[pixelinstart + b];
5410 }
5411 }
5412 }
5413 }
5414 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5415 {
5416 for(i = 0; i != 7; ++i)
5417 {
5418 unsigned x, y, b;
5419 unsigned ilinebits = bpp * passw[i];
5420 unsigned olinebits = bpp * w;
5421 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
5422 for(y = 0; y < passh[i]; ++y)
5423 for(x = 0; x < passw[i]; ++x)
5424 {
5425 ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
5426 obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
5427 for(b = 0; b < bpp; ++b)
5428 {
5429 unsigned char bit = readBitFromReversedStream(&ibp, in);
5430 setBitOfReversedStream(&obp, out, bit);
5431 }
5432 }
5433 }
5434 }
5435 }
5436
5437 /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5438 return value is error**/
preProcessScanlines(unsigned char ** out,size_t * outsize,const unsigned char * in,unsigned w,unsigned h,const LodePNGInfo * info_png,const LodePNGEncoderSettings * settings)5439 static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
5440 unsigned w, unsigned h,
5441 const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings)
5442 {
5443 /*
5444 This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5445 *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5446 *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5447 */
5448 unsigned bpp = lodepng_get_bpp(&info_png->color);
5449 unsigned error = 0;
5450
5451 if(info_png->interlace_method == 0)
5452 {
5453 *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5454 *out = (unsigned char*)lodepng_malloc(*outsize);
5455 if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
5456
5457 if(!error)
5458 {
5459 /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5460 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
5461 {
5462 unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8));
5463 if(!padded) error = 83; /*alloc fail*/
5464 if(!error)
5465 {
5466 addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
5467 error = filter(*out, padded, w, h, &info_png->color, settings);
5468 }
5469 lodepng_free(padded);
5470 }
5471 else
5472 {
5473 /*we can immediately filter into the out buffer, no other steps needed*/
5474 error = filter(*out, in, w, h, &info_png->color, settings);
5475 }
5476 }
5477 }
5478 else /*interlace_method is 1 (Adam7)*/
5479 {
5480 unsigned passw[7], passh[7];
5481 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5482 unsigned char* adam7;
5483
5484 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5485
5486 *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5487 *out = (unsigned char*)lodepng_malloc(*outsize);
5488 if(!(*out)) error = 83; /*alloc fail*/
5489
5490 adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
5491 if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
5492
5493 if(!error)
5494 {
5495 unsigned i;
5496
5497 Adam7_interlace(adam7, in, w, h, bpp);
5498 for(i = 0; i != 7; ++i)
5499 {
5500 if(bpp < 8)
5501 {
5502 unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
5503 if(!padded) ERROR_BREAK(83); /*alloc fail*/
5504 addPaddingBits(padded, &adam7[passstart[i]],
5505 ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
5506 error = filter(&(*out)[filter_passstart[i]], padded,
5507 passw[i], passh[i], &info_png->color, settings);
5508 lodepng_free(padded);
5509 }
5510 else
5511 {
5512 error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
5513 passw[i], passh[i], &info_png->color, settings);
5514 }
5515
5516 if(error) break;
5517 }
5518 }
5519
5520 lodepng_free(adam7);
5521 }
5522
5523 return error;
5524 }
5525
5526 /*
5527 palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5528 returns 0 if the palette is opaque,
5529 returns 1 if the palette has a single color with alpha 0 ==> color key
5530 returns 2 if the palette is semi-translucent.
5531 */
getPaletteTranslucency(const unsigned char * palette,size_t palettesize)5532 static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize)
5533 {
5534 size_t i;
5535 unsigned key = 0;
5536 unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5537 for(i = 0; i != palettesize; ++i)
5538 {
5539 if(!key && palette[4 * i + 3] == 0)
5540 {
5541 r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
5542 key = 1;
5543 i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5544 }
5545 else if(palette[4 * i + 3] != 255) return 2;
5546 /*when key, no opaque RGB may have key's RGB*/
5547 else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
5548 }
5549 return key;
5550 }
5551
5552 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
addUnknownChunks(ucvector * out,unsigned char * data,size_t datasize)5553 static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
5554 {
5555 unsigned char* inchunk = data;
5556 while((size_t)(inchunk - data) < datasize)
5557 {
5558 CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
5559 out->allocsize = out->size; /*fix the allocsize again*/
5560 inchunk = lodepng_chunk_next(inchunk);
5561 }
5562 return 0;
5563 }
5564 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5565
lodepng_encode(unsigned char ** out,size_t * outsize,const unsigned char * image,unsigned w,unsigned h,LodePNGState * state)5566 unsigned lodepng_encode(unsigned char** out, size_t* outsize,
5567 const unsigned char* image, unsigned w, unsigned h,
5568 LodePNGState* state)
5569 {
5570 LodePNGInfo info;
5571 ucvector outv;
5572 unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
5573 size_t datasize = 0;
5574
5575 /*provide some proper output values if error will happen*/
5576 *out = 0;
5577 *outsize = 0;
5578 state->error = 0;
5579
5580 lodepng_info_init(&info);
5581 lodepng_info_copy(&info, &state->info_png);
5582
5583 if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
5584 && (info.color.palettesize == 0 || info.color.palettesize > 256))
5585 {
5586 state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
5587 return state->error;
5588 }
5589
5590 if(state->encoder.auto_convert)
5591 {
5592 state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
5593 }
5594 if(state->error) return state->error;
5595
5596 if(state->encoder.zlibsettings.btype > 2)
5597 {
5598 CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
5599 }
5600 if(state->info_png.interlace_method > 1)
5601 {
5602 CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
5603 }
5604
5605 state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
5606 if(state->error) return state->error; /*error: unexisting color type given*/
5607 state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
5608 if(state->error) return state->error; /*error: unexisting color type given*/
5609
5610 if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
5611 {
5612 unsigned char* converted;
5613 size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
5614
5615 converted = (unsigned char*)lodepng_malloc(size);
5616 if(!converted && size) state->error = 83; /*alloc fail*/
5617 if(!state->error)
5618 {
5619 state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
5620 }
5621 if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
5622 lodepng_free(converted);
5623 }
5624 else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
5625
5626 ucvector_init(&outv);
5627 while(!state->error) /*while only executed once, to break on error*/
5628 {
5629 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5630 size_t i;
5631 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5632 /*write signature and chunks*/
5633 writeSignature(&outv);
5634 /*IHDR*/
5635 addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
5636 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5637 /*unknown chunks between IHDR and PLTE*/
5638 if(info.unknown_chunks_data[0])
5639 {
5640 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
5641 if(state->error) break;
5642 }
5643 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5644 /*PLTE*/
5645 if(info.color.colortype == LCT_PALETTE)
5646 {
5647 addChunk_PLTE(&outv, &info.color);
5648 }
5649 if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA))
5650 {
5651 addChunk_PLTE(&outv, &info.color);
5652 }
5653 /*tRNS*/
5654 if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0)
5655 {
5656 addChunk_tRNS(&outv, &info.color);
5657 }
5658 if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined)
5659 {
5660 addChunk_tRNS(&outv, &info.color);
5661 }
5662 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5663 /*bKGD (must come between PLTE and the IDAt chunks*/
5664 if(info.background_defined) addChunk_bKGD(&outv, &info);
5665 /*pHYs (must come before the IDAT chunks)*/
5666 if(info.phys_defined) addChunk_pHYs(&outv, &info);
5667
5668 /*unknown chunks between PLTE and IDAT*/
5669 if(info.unknown_chunks_data[1])
5670 {
5671 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
5672 if(state->error) break;
5673 }
5674 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5675 /*IDAT (multiple IDAT chunks must be consecutive)*/
5676 state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
5677 if(state->error) break;
5678 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5679 /*tIME*/
5680 if(info.time_defined) addChunk_tIME(&outv, &info.time);
5681 /*tEXt and/or zTXt*/
5682 for(i = 0; i != info.text_num; ++i)
5683 {
5684 if(strlen(info.text_keys[i]) > 79)
5685 {
5686 state->error = 66; /*text chunk too large*/
5687 break;
5688 }
5689 if(strlen(info.text_keys[i]) < 1)
5690 {
5691 state->error = 67; /*text chunk too small*/
5692 break;
5693 }
5694 if(state->encoder.text_compression)
5695 {
5696 addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
5697 }
5698 else
5699 {
5700 addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
5701 }
5702 }
5703 /*LodePNG version id in text chunk*/
5704 if(state->encoder.add_id)
5705 {
5706 unsigned alread_added_id_text = 0;
5707 for(i = 0; i != info.text_num; ++i)
5708 {
5709 if(!strcmp(info.text_keys[i], "LodePNG"))
5710 {
5711 alread_added_id_text = 1;
5712 break;
5713 }
5714 }
5715 if(alread_added_id_text == 0)
5716 {
5717 addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
5718 }
5719 }
5720 /*iTXt*/
5721 for(i = 0; i != info.itext_num; ++i)
5722 {
5723 if(strlen(info.itext_keys[i]) > 79)
5724 {
5725 state->error = 66; /*text chunk too large*/
5726 break;
5727 }
5728 if(strlen(info.itext_keys[i]) < 1)
5729 {
5730 state->error = 67; /*text chunk too small*/
5731 break;
5732 }
5733 addChunk_iTXt(&outv, state->encoder.text_compression,
5734 info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
5735 &state->encoder.zlibsettings);
5736 }
5737
5738 /*unknown chunks between IDAT and IEND*/
5739 if(info.unknown_chunks_data[2])
5740 {
5741 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
5742 if(state->error) break;
5743 }
5744 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5745 addChunk_IEND(&outv);
5746
5747 break; /*this isn't really a while loop; no error happened so break out now!*/
5748 }
5749
5750 lodepng_info_cleanup(&info);
5751 lodepng_free(data);
5752 /*instead of cleaning the vector up, give it to the output*/
5753 *out = outv.data;
5754 *outsize = outv.size;
5755
5756 return state->error;
5757 }
5758
lodepng_encode_memory(unsigned char ** out,size_t * outsize,const unsigned char * image,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)5759 unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
5760 unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
5761 {
5762 unsigned error;
5763 LodePNGState state;
5764 lodepng_state_init(&state);
5765 state.info_raw.colortype = colortype;
5766 state.info_raw.bitdepth = bitdepth;
5767 state.info_png.color.colortype = colortype;
5768 state.info_png.color.bitdepth = bitdepth;
5769 lodepng_encode(out, outsize, image, w, h, &state);
5770 error = state.error;
5771 lodepng_state_cleanup(&state);
5772 return error;
5773 }
5774
lodepng_encode32(unsigned char ** out,size_t * outsize,const unsigned char * image,unsigned w,unsigned h)5775 unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5776 {
5777 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
5778 }
5779
lodepng_encode24(unsigned char ** out,size_t * outsize,const unsigned char * image,unsigned w,unsigned h)5780 unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5781 {
5782 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
5783 }
5784
5785 #ifdef LODEPNG_COMPILE_DISK
lodepng_encode_file(const char * filename,const unsigned char * image,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)5786 unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
5787 LodePNGColorType colortype, unsigned bitdepth)
5788 {
5789 unsigned char* buffer;
5790 size_t buffersize;
5791 unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
5792 if(!error) error = lodepng_save_file(buffer, buffersize, filename);
5793 lodepng_free(buffer);
5794 return error;
5795 }
5796
lodepng_encode32_file(const char * filename,const unsigned char * image,unsigned w,unsigned h)5797 unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5798 {
5799 return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
5800 }
5801
lodepng_encode24_file(const char * filename,const unsigned char * image,unsigned w,unsigned h)5802 unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5803 {
5804 return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
5805 }
5806 #endif /*LODEPNG_COMPILE_DISK*/
5807
lodepng_encoder_settings_init(LodePNGEncoderSettings * settings)5808 void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
5809 {
5810 lodepng_compress_settings_init(&settings->zlibsettings);
5811 settings->filter_palette_zero = 1;
5812 settings->filter_strategy = LFS_MINSUM;
5813 settings->auto_convert = 1;
5814 settings->force_palette = 0;
5815 settings->predefined_filters = 0;
5816 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5817 settings->add_id = 0;
5818 settings->text_compression = 1;
5819 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5820 }
5821
5822 #endif /*LODEPNG_COMPILE_ENCODER*/
5823 #endif /*LODEPNG_COMPILE_PNG*/
5824
5825 #ifdef LODEPNG_COMPILE_ERROR_TEXT
5826 /*
5827 This returns the description of a numerical error code in English. This is also
5828 the documentation of all the error codes.
5829 */
lodepng_error_text(unsigned code)5830 const char* lodepng_error_text(unsigned code)
5831 {
5832 switch(code)
5833 {
5834 case 0: return "no error, everything went ok";
5835 case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5836 case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
5837 case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5838 case 13: return "problem while processing dynamic deflate block";
5839 case 14: return "problem while processing dynamic deflate block";
5840 case 15: return "problem while processing dynamic deflate block";
5841 case 16: return "unexisting code while processing dynamic deflate block";
5842 case 17: return "end of out buffer memory reached while inflating";
5843 case 18: return "invalid distance code while inflating";
5844 case 19: return "end of out buffer memory reached while inflating";
5845 case 20: return "invalid deflate block BTYPE encountered while decoding";
5846 case 21: return "NLEN is not ones complement of LEN in a deflate block";
5847 /*end of out buffer memory reached while inflating:
5848 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5849 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5850 happen in a normal, well encoded, PNG image.*/
5851 case 22: return "end of out buffer memory reached while inflating";
5852 case 23: return "end of in buffer memory reached while inflating";
5853 case 24: return "invalid FCHECK in zlib header";
5854 case 25: return "invalid compression method in zlib header";
5855 case 26: return "FDICT encountered in zlib header while it's not used for PNG";
5856 case 27: return "PNG file is smaller than a PNG header";
5857 /*Checks the magic file header, the first 8 bytes of the PNG file*/
5858 case 28: return "incorrect PNG signature, it's no PNG or corrupted";
5859 case 29: return "first chunk is not the header chunk";
5860 case 30: return "chunk length too large, chunk broken off at end of file";
5861 case 31: return "illegal PNG color type or bpp";
5862 case 32: return "illegal PNG compression method";
5863 case 33: return "illegal PNG filter method";
5864 case 34: return "illegal PNG interlace method";
5865 case 35: return "chunk length of a chunk is too large or the chunk too small";
5866 case 36: return "illegal PNG filter type encountered";
5867 case 37: return "illegal bit depth for this color type given";
5868 case 38: return "the palette is too big"; /*more than 256 colors*/
5869 case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
5870 case 40: return "tRNS chunk has wrong size for greyscale image";
5871 case 41: return "tRNS chunk has wrong size for RGB image";
5872 case 42: return "tRNS chunk appeared while it was not allowed for this color type";
5873 case 43: return "bKGD chunk has wrong size for palette image";
5874 case 44: return "bKGD chunk has wrong size for greyscale image";
5875 case 45: return "bKGD chunk has wrong size for RGB image";
5876 case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
5877 case 49: return "jumped past memory while generating dynamic huffman tree";
5878 case 50: return "jumped past memory while generating dynamic huffman tree";
5879 case 51: return "jumped past memory while inflating huffman block";
5880 case 52: return "jumped past memory while inflating";
5881 case 53: return "size of zlib data too small";
5882 case 54: return "repeat symbol in tree while there was no value symbol yet";
5883 /*jumped past tree while generating huffman tree, this could be when the
5884 tree will have more leaves than symbols after generating it out of the
5885 given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
5886 case 55: return "jumped past tree while generating huffman tree";
5887 case 56: return "given output image colortype or bitdepth not supported for color conversion";
5888 case 57: return "invalid CRC encountered (checking CRC can be disabled)";
5889 case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
5890 case 59: return "requested color conversion not supported";
5891 case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
5892 case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
5893 /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
5894 case 62: return "conversion from color to greyscale not supported";
5895 case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
5896 /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
5897 case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
5898 case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
5899 case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
5900 case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
5901 case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
5902 case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
5903 case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
5904 case 73: return "invalid tIME chunk size";
5905 case 74: return "invalid pHYs chunk size";
5906 /*length could be wrong, or data chopped off*/
5907 case 75: return "no null termination char found while decoding text chunk";
5908 case 76: return "iTXt chunk too short to contain required bytes";
5909 case 77: return "integer overflow in buffer size";
5910 case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
5911 case 79: return "failed to open file for writing";
5912 case 80: return "tried creating a tree of 0 symbols";
5913 case 81: return "lazy matching at pos 0 is impossible";
5914 case 82: return "color conversion to palette requested while a color isn't in palette";
5915 case 83: return "memory allocation failed";
5916 case 84: return "given image too small to contain all pixels to be encoded";
5917 case 86: return "impossible offset in lz77 encoding (internal bug)";
5918 case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
5919 case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
5920 case 89: return "text chunk keyword too short or long: must have size 1-79";
5921 /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
5922 case 90: return "windowsize must be a power of two";
5923 case 91: return "invalid decompressed idat size";
5924 case 92: return "too many pixels, not supported";
5925 case 93: return "zero width or height is invalid";
5926 case 94: return "header chunk must have a size of 13 bytes";
5927 }
5928 return "unknown error code";
5929 }
5930 #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
5931
5932 /* ////////////////////////////////////////////////////////////////////////// */
5933 /* ////////////////////////////////////////////////////////////////////////// */
5934 /* // C++ Wrapper // */
5935 /* ////////////////////////////////////////////////////////////////////////// */
5936 /* ////////////////////////////////////////////////////////////////////////// */
5937
5938 #ifdef LODEPNG_COMPILE_CPP
5939 namespace lodepng
5940 {
5941
5942 #ifdef LODEPNG_COMPILE_DISK
load_file(std::vector<unsigned char> & buffer,const std::string & filename)5943 unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename)
5944 {
5945 std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
5946 if(!file) return 78;
5947
5948 /*get filesize*/
5949 std::streamsize size = 0;
5950 if(file.seekg(0, std::ios::end).good()) size = file.tellg();
5951 if(file.seekg(0, std::ios::beg).good()) size -= file.tellg();
5952
5953 /*read contents of the file into the vector*/
5954 buffer.resize(size_t(size));
5955 if(size > 0) file.read((char*)(&buffer[0]), size);
5956
5957 return 0; /* OK */
5958 }
5959
5960 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
save_file(const std::vector<unsigned char> & buffer,const std::string & filename)5961 unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename)
5962 {
5963 std::ofstream file(filename.c_str(), std::ios::out|std::ios::binary);
5964 if(!file) return 79;
5965 file.write(buffer.empty() ? 0 : (char*)&buffer[0], std::streamsize(buffer.size()));
5966 return 0;
5967 }
5968 #endif /* LODEPNG_COMPILE_DISK */
5969
5970 #ifdef LODEPNG_COMPILE_ZLIB
5971 #ifdef LODEPNG_COMPILE_DECODER
decompress(std::vector<unsigned char> & out,const unsigned char * in,size_t insize,const LodePNGDecompressSettings & settings)5972 unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
5973 const LodePNGDecompressSettings& settings)
5974 {
5975 unsigned char* buffer = 0;
5976 size_t buffersize = 0;
5977 unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
5978 if(buffer)
5979 {
5980 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
5981 lodepng_free(buffer);
5982 }
5983 return error;
5984 }
5985
decompress(std::vector<unsigned char> & out,const std::vector<unsigned char> & in,const LodePNGDecompressSettings & settings)5986 unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
5987 const LodePNGDecompressSettings& settings)
5988 {
5989 return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
5990 }
5991 #endif /* LODEPNG_COMPILE_DECODER */
5992
5993 #ifdef LODEPNG_COMPILE_ENCODER
compress(std::vector<unsigned char> & out,const unsigned char * in,size_t insize,const LodePNGCompressSettings & settings)5994 unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
5995 const LodePNGCompressSettings& settings)
5996 {
5997 unsigned char* buffer = 0;
5998 size_t buffersize = 0;
5999 unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
6000 if(buffer)
6001 {
6002 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6003 lodepng_free(buffer);
6004 }
6005 return error;
6006 }
6007
compress(std::vector<unsigned char> & out,const std::vector<unsigned char> & in,const LodePNGCompressSettings & settings)6008 unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
6009 const LodePNGCompressSettings& settings)
6010 {
6011 return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
6012 }
6013 #endif /* LODEPNG_COMPILE_ENCODER */
6014 #endif /* LODEPNG_COMPILE_ZLIB */
6015
6016
6017 #ifdef LODEPNG_COMPILE_PNG
6018
State()6019 State::State()
6020 {
6021 lodepng_state_init(this);
6022 }
6023
State(const State & other)6024 State::State(const State& other)
6025 {
6026 lodepng_state_init(this);
6027 lodepng_state_copy(this, &other);
6028 }
6029
~State()6030 State::~State()
6031 {
6032 lodepng_state_cleanup(this);
6033 }
6034
operator =(const State & other)6035 State& State::operator=(const State& other)
6036 {
6037 lodepng_state_copy(this, &other);
6038 return *this;
6039 }
6040
6041 #ifdef LODEPNG_COMPILE_DECODER
6042
decode(std::vector<unsigned char> & out,unsigned & w,unsigned & h,const unsigned char * in,size_t insize,LodePNGColorType colortype,unsigned bitdepth)6043 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
6044 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
6045 {
6046 unsigned char* buffer;
6047 unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
6048 if(buffer && !error)
6049 {
6050 State state;
6051 state.info_raw.colortype = colortype;
6052 state.info_raw.bitdepth = bitdepth;
6053 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6054 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6055 lodepng_free(buffer);
6056 }
6057 return error;
6058 }
6059
decode(std::vector<unsigned char> & out,unsigned & w,unsigned & h,const std::vector<unsigned char> & in,LodePNGColorType colortype,unsigned bitdepth)6060 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6061 const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth)
6062 {
6063 return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
6064 }
6065
decode(std::vector<unsigned char> & out,unsigned & w,unsigned & h,State & state,const unsigned char * in,size_t insize)6066 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6067 State& state,
6068 const unsigned char* in, size_t insize)
6069 {
6070 unsigned char* buffer = NULL;
6071 unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
6072 if(buffer && !error)
6073 {
6074 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6075 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6076 }
6077 lodepng_free(buffer);
6078 return error;
6079 }
6080
decode(std::vector<unsigned char> & out,unsigned & w,unsigned & h,State & state,const std::vector<unsigned char> & in)6081 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6082 State& state,
6083 const std::vector<unsigned char>& in)
6084 {
6085 return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
6086 }
6087
6088 #ifdef LODEPNG_COMPILE_DISK
decode(std::vector<unsigned char> & out,unsigned & w,unsigned & h,const std::string & filename,LodePNGColorType colortype,unsigned bitdepth)6089 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
6090 LodePNGColorType colortype, unsigned bitdepth)
6091 {
6092 std::vector<unsigned char> buffer;
6093 unsigned error = load_file(buffer, filename);
6094 if(error) return error;
6095 return decode(out, w, h, buffer, colortype, bitdepth);
6096 }
6097 #endif /* LODEPNG_COMPILE_DECODER */
6098 #endif /* LODEPNG_COMPILE_DISK */
6099
6100 #ifdef LODEPNG_COMPILE_ENCODER
encode(std::vector<unsigned char> & out,const unsigned char * in,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)6101 unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
6102 LodePNGColorType colortype, unsigned bitdepth)
6103 {
6104 unsigned char* buffer;
6105 size_t buffersize;
6106 unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
6107 if(buffer)
6108 {
6109 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6110 lodepng_free(buffer);
6111 }
6112 return error;
6113 }
6114
encode(std::vector<unsigned char> & out,const std::vector<unsigned char> & in,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)6115 unsigned encode(std::vector<unsigned char>& out,
6116 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6117 LodePNGColorType colortype, unsigned bitdepth)
6118 {
6119 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6120 return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6121 }
6122
encode(std::vector<unsigned char> & out,const unsigned char * in,unsigned w,unsigned h,State & state)6123 unsigned encode(std::vector<unsigned char>& out,
6124 const unsigned char* in, unsigned w, unsigned h,
6125 State& state)
6126 {
6127 unsigned char* buffer;
6128 size_t buffersize;
6129 unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
6130 if(buffer)
6131 {
6132 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6133 lodepng_free(buffer);
6134 }
6135 return error;
6136 }
6137
encode(std::vector<unsigned char> & out,const std::vector<unsigned char> & in,unsigned w,unsigned h,State & state)6138 unsigned encode(std::vector<unsigned char>& out,
6139 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6140 State& state)
6141 {
6142 if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
6143 return encode(out, in.empty() ? 0 : &in[0], w, h, state);
6144 }
6145
6146 #ifdef LODEPNG_COMPILE_DISK
encode(const std::string & filename,const unsigned char * in,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)6147 unsigned encode(const std::string& filename,
6148 const unsigned char* in, unsigned w, unsigned h,
6149 LodePNGColorType colortype, unsigned bitdepth)
6150 {
6151 std::vector<unsigned char> buffer;
6152 unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
6153 if(!error) error = save_file(buffer, filename);
6154 return error;
6155 }
6156
encode(const std::string & filename,const std::vector<unsigned char> & in,unsigned w,unsigned h,LodePNGColorType colortype,unsigned bitdepth)6157 unsigned encode(const std::string& filename,
6158 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6159 LodePNGColorType colortype, unsigned bitdepth)
6160 {
6161 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6162 return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6163 }
6164 } // namespace lpng
6165 #endif /* LODEPNG_COMPILE_DISK */
6166 #endif /* LODEPNG_COMPILE_ENCODER */
6167 #endif /* LODEPNG_COMPILE_PNG */
6168 } /* namespace lodepng */
6169 #endif /*LODEPNG_COMPILE_CPP*/
6170