Debian Codegraph @

src/lodepng.cpp

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