Debian Codegraph @

external/lodepng/lodepng.cpp

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