]> code.delx.au - refind/blob - libeg/lodepng.c
Updated LodePNG to latest version (20151024).
[refind] / libeg / lodepng.c
1 /*
2 LodePNG version 20151024
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 = "20151024";
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 huffman 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 = (int)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, (int)maxbitlen - 1, (int)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
2300 #ifndef LODEPNG_NO_COMPILE_CRC
2301 /* CRC polynomial: 0xedb88320 */
2302 static unsigned lodepng_crc32_table[256] = {
2303 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
2304 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
2305 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
2306 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
2307 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
2308 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
2309 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
2310 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
2311 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2312 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
2313 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
2314 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
2315 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
2316 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
2317 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
2318 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
2319 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
2320 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
2321 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
2322 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
2323 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
2324 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
2325 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
2326 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2327 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2328 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2329 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2330 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2331 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2332 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
2333 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
2334 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
2335 };
2336
2337 /*Return the CRC of the bytes buf[0..len-1].*/
2338 unsigned lodepng_crc32(const unsigned char* buf, size_t len)
2339 {
2340 unsigned c = 0xffffffffL;
2341 size_t n;
2342
2343 for(n = 0; n < len; ++n)
2344 {
2345 c = lodepng_crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
2346 }
2347 return c ^ 0xffffffffL;
2348 }
2349 #endif /* !LODEPNG_NO_COMPILE_CRC */
2350
2351 /* ////////////////////////////////////////////////////////////////////////// */
2352 /* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2353 /* ////////////////////////////////////////////////////////////////////////// */
2354
2355 static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
2356 {
2357 unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2358 ++(*bitpointer);
2359 return result;
2360 }
2361
2362 static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
2363 {
2364 unsigned result = 0;
2365 size_t i;
2366 for(i = nbits - 1; i < nbits; --i)
2367 {
2368 result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
2369 }
2370 return result;
2371 }
2372
2373 #ifdef LODEPNG_COMPILE_DECODER
2374 static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2375 {
2376 /*the current bit in bitstream must be 0 for this to work*/
2377 if(bit)
2378 {
2379 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2380 bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
2381 }
2382 ++(*bitpointer);
2383 }
2384 #endif /*LODEPNG_COMPILE_DECODER*/
2385
2386 static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2387 {
2388 /*the current bit in bitstream may be 0 or 1 for this to work*/
2389 if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
2390 else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
2391 ++(*bitpointer);
2392 }
2393
2394 /* ////////////////////////////////////////////////////////////////////////// */
2395 /* / PNG chunks / */
2396 /* ////////////////////////////////////////////////////////////////////////// */
2397
2398 unsigned lodepng_chunk_length(const unsigned char* chunk)
2399 {
2400 return lodepng_read32bitInt(&chunk[0]);
2401 }
2402
2403 void lodepng_chunk_type(char type[5], const unsigned char* chunk)
2404 {
2405 unsigned i;
2406 for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
2407 type[4] = 0; /*null termination char*/
2408 }
2409
2410 unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
2411 {
2412 if(strlen(type) != 4) return 0;
2413 return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2414 }
2415
2416 unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
2417 {
2418 return((chunk[4] & 32) != 0);
2419 }
2420
2421 unsigned char lodepng_chunk_private(const unsigned char* chunk)
2422 {
2423 return((chunk[6] & 32) != 0);
2424 }
2425
2426 unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
2427 {
2428 return((chunk[7] & 32) != 0);
2429 }
2430
2431 unsigned char* lodepng_chunk_data(unsigned char* chunk)
2432 {
2433 return &chunk[8];
2434 }
2435
2436 const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
2437 {
2438 return &chunk[8];
2439 }
2440
2441 unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
2442 {
2443 unsigned length = lodepng_chunk_length(chunk);
2444 unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
2445 /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2446 unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2447 if(CRC != checksum) return 1;
2448 else return 0;
2449 }
2450
2451 void lodepng_chunk_generate_crc(unsigned char* chunk)
2452 {
2453 unsigned length = lodepng_chunk_length(chunk);
2454 unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
2455 lodepng_set32bitInt(chunk + 8 + length, CRC);
2456 }
2457
2458 unsigned char* lodepng_chunk_next(unsigned char* chunk)
2459 {
2460 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2461 return &chunk[total_chunk_length];
2462 }
2463
2464 const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
2465 {
2466 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2467 return &chunk[total_chunk_length];
2468 }
2469
2470 unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
2471 {
2472 unsigned i;
2473 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2474 unsigned char *chunk_start, *new_buffer;
2475 size_t new_length = (*outlength) + total_chunk_length;
2476 if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
2477
2478 new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2479 if(!new_buffer) return 83; /*alloc fail*/
2480 (*out) = new_buffer;
2481 (*outlength) = new_length;
2482 chunk_start = &(*out)[new_length - total_chunk_length];
2483
2484 for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
2485
2486 return 0;
2487 }
2488
2489 unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
2490 const char* type, const unsigned char* data)
2491 {
2492 unsigned i;
2493 unsigned char *chunk, *new_buffer;
2494 size_t new_length = (*outlength) + length + 12;
2495 if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
2496 new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2497 if(!new_buffer) return 83; /*alloc fail*/
2498 (*out) = new_buffer;
2499 (*outlength) = new_length;
2500 chunk = &(*out)[(*outlength) - length - 12];
2501
2502 /*1: length*/
2503 lodepng_set32bitInt(chunk, (unsigned)length);
2504
2505 /*2: chunk name (4 letters)*/
2506 chunk[4] = (unsigned char)type[0];
2507 chunk[5] = (unsigned char)type[1];
2508 chunk[6] = (unsigned char)type[2];
2509 chunk[7] = (unsigned char)type[3];
2510
2511 /*3: the data*/
2512 for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
2513
2514 /*4: CRC (of the chunkname characters and the data)*/
2515 lodepng_chunk_generate_crc(chunk);
2516
2517 return 0;
2518 }
2519
2520 /* ////////////////////////////////////////////////////////////////////////// */
2521 /* / Color types and such / */
2522 /* ////////////////////////////////////////////////////////////////////////// */
2523
2524 /*return type is a LodePNG error code*/
2525 static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
2526 {
2527 switch(colortype)
2528 {
2529 case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
2530 case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
2531 case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
2532 case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
2533 case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
2534 default: return 31;
2535 }
2536 return 0; /*allowed color type / bits combination*/
2537 }
2538
2539 static unsigned getNumColorChannels(LodePNGColorType colortype)
2540 {
2541 switch(colortype)
2542 {
2543 case 0: return 1; /*grey*/
2544 case 2: return 3; /*RGB*/
2545 case 3: return 1; /*palette*/
2546 case 4: return 2; /*grey + alpha*/
2547 case 6: return 4; /*RGBA*/
2548 }
2549 return 0; /*unexisting color type*/
2550 }
2551
2552 static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
2553 {
2554 /*bits per pixel is amount of channels * bits per channel*/
2555 return getNumColorChannels(colortype) * bitdepth;
2556 }
2557
2558 /* ////////////////////////////////////////////////////////////////////////// */
2559
2560 void lodepng_color_mode_init(LodePNGColorMode* info)
2561 {
2562 info->key_defined = 0;
2563 info->key_r = info->key_g = info->key_b = 0;
2564 info->colortype = LCT_RGBA;
2565 info->bitdepth = 8;
2566 info->palette = 0;
2567 info->palettesize = 0;
2568 }
2569
2570 void lodepng_color_mode_cleanup(LodePNGColorMode* info)
2571 {
2572 lodepng_palette_clear(info);
2573 }
2574
2575 unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
2576 {
2577 size_t i;
2578 lodepng_color_mode_cleanup(dest);
2579 *dest = *source;
2580 if(source->palette)
2581 {
2582 dest->palette = (unsigned char*)lodepng_malloc(1024);
2583 if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2584 for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
2585 }
2586 return 0;
2587 }
2588
2589 static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
2590 {
2591 size_t i;
2592 if(a->colortype != b->colortype) return 0;
2593 if(a->bitdepth != b->bitdepth) return 0;
2594 if(a->key_defined != b->key_defined) return 0;
2595 if(a->key_defined)
2596 {
2597 if(a->key_r != b->key_r) return 0;
2598 if(a->key_g != b->key_g) return 0;
2599 if(a->key_b != b->key_b) return 0;
2600 }
2601 /*if one of the palette sizes is 0, then we consider it to be the same as the
2602 other: it means that e.g. the palette was not given by the user and should be
2603 considered the same as the palette inside the PNG.*/
2604 if(1/*a->palettesize != 0 && b->palettesize != 0*/) {
2605 if(a->palettesize != b->palettesize) return 0;
2606 for(i = 0; i != a->palettesize * 4; ++i)
2607 {
2608 if(a->palette[i] != b->palette[i]) return 0;
2609 }
2610 }
2611 return 1;
2612 }
2613
2614 void lodepng_palette_clear(LodePNGColorMode* info)
2615 {
2616 if(info->palette) lodepng_free(info->palette);
2617 info->palette = 0;
2618 info->palettesize = 0;
2619 }
2620
2621 unsigned lodepng_palette_add(LodePNGColorMode* info,
2622 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2623 {
2624 unsigned char* data;
2625 /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2626 the max of 256 colors, it'll have the exact alloc size*/
2627 if(!info->palette) /*allocate palette if empty*/
2628 {
2629 /*room for 256 colors with 4 bytes each*/
2630 data = (unsigned char*)lodepng_realloc(info->palette, 1024);
2631 if(!data) return 83; /*alloc fail*/
2632 else info->palette = data;
2633 }
2634 info->palette[4 * info->palettesize + 0] = r;
2635 info->palette[4 * info->palettesize + 1] = g;
2636 info->palette[4 * info->palettesize + 2] = b;
2637 info->palette[4 * info->palettesize + 3] = a;
2638 ++info->palettesize;
2639 return 0;
2640 }
2641
2642 unsigned lodepng_get_bpp(const LodePNGColorMode* info)
2643 {
2644 /*calculate bits per pixel out of colortype and bitdepth*/
2645 return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
2646 }
2647
2648 unsigned lodepng_get_channels(const LodePNGColorMode* info)
2649 {
2650 return getNumColorChannels(info->colortype);
2651 }
2652
2653 unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
2654 {
2655 return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
2656 }
2657
2658 unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
2659 {
2660 return (info->colortype & 4) != 0; /*4 or 6*/
2661 }
2662
2663 unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
2664 {
2665 return info->colortype == LCT_PALETTE;
2666 }
2667
2668 unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
2669 {
2670 size_t i;
2671 for(i = 0; i != info->palettesize; ++i)
2672 {
2673 if(info->palette[i * 4 + 3] < 255) return 1;
2674 }
2675 return 0;
2676 }
2677
2678 unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
2679 {
2680 return info->key_defined
2681 || lodepng_is_alpha_type(info)
2682 || lodepng_has_palette_alpha(info);
2683 }
2684
2685 size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
2686 {
2687 return (w * h * lodepng_get_bpp(color) + 7) / 8;
2688 }
2689
2690 size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
2691 {
2692 return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8;
2693 }
2694
2695
2696 #ifdef LODEPNG_COMPILE_PNG
2697 #ifdef LODEPNG_COMPILE_DECODER
2698 /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
2699 static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color)
2700 {
2701 return h * ((w * lodepng_get_bpp(color) + 7) / 8);
2702 }
2703 #endif /*LODEPNG_COMPILE_DECODER*/
2704 #endif /*LODEPNG_COMPILE_PNG*/
2705
2706 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2707
2708 static void LodePNGUnknownChunks_init(LodePNGInfo* info)
2709 {
2710 unsigned i;
2711 for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
2712 for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
2713 }
2714
2715 static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
2716 {
2717 unsigned i;
2718 for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
2719 }
2720
2721 static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
2722 {
2723 unsigned i;
2724
2725 LodePNGUnknownChunks_cleanup(dest);
2726
2727 for(i = 0; i != 3; ++i)
2728 {
2729 size_t j;
2730 dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
2731 dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
2732 if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
2733 for(j = 0; j < src->unknown_chunks_size[i]; ++j)
2734 {
2735 dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
2736 }
2737 }
2738
2739 return 0;
2740 }
2741
2742 /******************************************************************************/
2743
2744 static void LodePNGText_init(LodePNGInfo* info)
2745 {
2746 info->text_num = 0;
2747 info->text_keys = NULL;
2748 info->text_strings = NULL;
2749 }
2750
2751 static void LodePNGText_cleanup(LodePNGInfo* info)
2752 {
2753 size_t i;
2754 for(i = 0; i != info->text_num; ++i)
2755 {
2756 string_cleanup(&info->text_keys[i]);
2757 string_cleanup(&info->text_strings[i]);
2758 }
2759 lodepng_free(info->text_keys);
2760 lodepng_free(info->text_strings);
2761 }
2762
2763 static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2764 {
2765 size_t i = 0;
2766 dest->text_keys = 0;
2767 dest->text_strings = 0;
2768 dest->text_num = 0;
2769 for(i = 0; i != source->text_num; ++i)
2770 {
2771 CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
2772 }
2773 return 0;
2774 }
2775
2776 void lodepng_clear_text(LodePNGInfo* info)
2777 {
2778 LodePNGText_cleanup(info);
2779 }
2780
2781 unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
2782 {
2783 char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
2784 char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
2785 if(!new_keys || !new_strings)
2786 {
2787 lodepng_free(new_keys);
2788 lodepng_free(new_strings);
2789 return 83; /*alloc fail*/
2790 }
2791
2792 ++info->text_num;
2793 info->text_keys = new_keys;
2794 info->text_strings = new_strings;
2795
2796 string_init(&info->text_keys[info->text_num - 1]);
2797 string_set(&info->text_keys[info->text_num - 1], key);
2798
2799 string_init(&info->text_strings[info->text_num - 1]);
2800 string_set(&info->text_strings[info->text_num - 1], str);
2801
2802 return 0;
2803 }
2804
2805 /******************************************************************************/
2806
2807 static void LodePNGIText_init(LodePNGInfo* info)
2808 {
2809 info->itext_num = 0;
2810 info->itext_keys = NULL;
2811 info->itext_langtags = NULL;
2812 info->itext_transkeys = NULL;
2813 info->itext_strings = NULL;
2814 }
2815
2816 static void LodePNGIText_cleanup(LodePNGInfo* info)
2817 {
2818 size_t i;
2819 for(i = 0; i != info->itext_num; ++i)
2820 {
2821 string_cleanup(&info->itext_keys[i]);
2822 string_cleanup(&info->itext_langtags[i]);
2823 string_cleanup(&info->itext_transkeys[i]);
2824 string_cleanup(&info->itext_strings[i]);
2825 }
2826 lodepng_free(info->itext_keys);
2827 lodepng_free(info->itext_langtags);
2828 lodepng_free(info->itext_transkeys);
2829 lodepng_free(info->itext_strings);
2830 }
2831
2832 static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2833 {
2834 size_t i = 0;
2835 dest->itext_keys = 0;
2836 dest->itext_langtags = 0;
2837 dest->itext_transkeys = 0;
2838 dest->itext_strings = 0;
2839 dest->itext_num = 0;
2840 for(i = 0; i != source->itext_num; ++i)
2841 {
2842 CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
2843 source->itext_transkeys[i], source->itext_strings[i]));
2844 }
2845 return 0;
2846 }
2847
2848 void lodepng_clear_itext(LodePNGInfo* info)
2849 {
2850 LodePNGIText_cleanup(info);
2851 }
2852
2853 unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
2854 const char* transkey, const char* str)
2855 {
2856 char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
2857 char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
2858 char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
2859 char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
2860 if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
2861 {
2862 lodepng_free(new_keys);
2863 lodepng_free(new_langtags);
2864 lodepng_free(new_transkeys);
2865 lodepng_free(new_strings);
2866 return 83; /*alloc fail*/
2867 }
2868
2869 ++info->itext_num;
2870 info->itext_keys = new_keys;
2871 info->itext_langtags = new_langtags;
2872 info->itext_transkeys = new_transkeys;
2873 info->itext_strings = new_strings;
2874
2875 string_init(&info->itext_keys[info->itext_num - 1]);
2876 string_set(&info->itext_keys[info->itext_num - 1], key);
2877
2878 string_init(&info->itext_langtags[info->itext_num - 1]);
2879 string_set(&info->itext_langtags[info->itext_num - 1], langtag);
2880
2881 string_init(&info->itext_transkeys[info->itext_num - 1]);
2882 string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
2883
2884 string_init(&info->itext_strings[info->itext_num - 1]);
2885 string_set(&info->itext_strings[info->itext_num - 1], str);
2886
2887 return 0;
2888 }
2889 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2890
2891 void lodepng_info_init(LodePNGInfo* info)
2892 {
2893 lodepng_color_mode_init(&info->color);
2894 info->interlace_method = 0;
2895 info->compression_method = 0;
2896 info->filter_method = 0;
2897 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2898 info->background_defined = 0;
2899 info->background_r = info->background_g = info->background_b = 0;
2900
2901 LodePNGText_init(info);
2902 LodePNGIText_init(info);
2903
2904 info->time_defined = 0;
2905 info->phys_defined = 0;
2906
2907 LodePNGUnknownChunks_init(info);
2908 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2909 }
2910
2911 void lodepng_info_cleanup(LodePNGInfo* info)
2912 {
2913 lodepng_color_mode_cleanup(&info->color);
2914 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2915 LodePNGText_cleanup(info);
2916 LodePNGIText_cleanup(info);
2917
2918 LodePNGUnknownChunks_cleanup(info);
2919 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2920 }
2921
2922 unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2923 {
2924 lodepng_info_cleanup(dest);
2925 *dest = *source;
2926 lodepng_color_mode_init(&dest->color);
2927 CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
2928
2929 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2930 CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
2931 CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
2932
2933 LodePNGUnknownChunks_init(dest);
2934 CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
2935 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2936 return 0;
2937 }
2938
2939 void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
2940 {
2941 LodePNGInfo temp = *a;
2942 *a = *b;
2943 *b = temp;
2944 }
2945
2946 /* ////////////////////////////////////////////////////////////////////////// */
2947
2948 /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
2949 static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
2950 {
2951 unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
2952 /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2953 unsigned p = index & m;
2954 in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
2955 in = in << (bits * (m - p));
2956 if(p == 0) out[index * bits / 8] = in;
2957 else out[index * bits / 8] |= in;
2958 }
2959
2960 typedef struct ColorTree ColorTree;
2961
2962 /*
2963 One node of a color tree
2964 This is the data structure used to count the number of unique colors and to get a palette
2965 index for a color. It's like an octree, but because the alpha channel is used too, each
2966 node has 16 instead of 8 children.
2967 */
2968 struct ColorTree
2969 {
2970 ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
2971 int index; /*the payload. Only has a meaningful value if this is in the last level*/
2972 };
2973
2974 static void color_tree_init(ColorTree* tree)
2975 {
2976 int i;
2977 for(i = 0; i != 16; ++i) tree->children[i] = 0;
2978 tree->index = -1;
2979 }
2980
2981 static void color_tree_cleanup(ColorTree* tree)
2982 {
2983 int i;
2984 for(i = 0; i != 16; ++i)
2985 {
2986 if(tree->children[i])
2987 {
2988 color_tree_cleanup(tree->children[i]);
2989 lodepng_free(tree->children[i]);
2990 }
2991 }
2992 }
2993
2994 /*returns -1 if color not present, its index otherwise*/
2995 static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2996 {
2997 int bit = 0;
2998 for(bit = 0; bit < 8; ++bit)
2999 {
3000 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3001 if(!tree->children[i]) return -1;
3002 else tree = tree->children[i];
3003 }
3004 return tree ? tree->index : -1;
3005 }
3006
3007 #ifdef LODEPNG_COMPILE_ENCODER
3008 static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3009 {
3010 return color_tree_get(tree, r, g, b, a) >= 0;
3011 }
3012 #endif /*LODEPNG_COMPILE_ENCODER*/
3013
3014 /*color is not allowed to already exist.
3015 Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
3016 static void color_tree_add(ColorTree* tree,
3017 unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
3018 {
3019 int bit;
3020 for(bit = 0; bit < 8; ++bit)
3021 {
3022 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3023 if(!tree->children[i])
3024 {
3025 tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
3026 color_tree_init(tree->children[i]);
3027 }
3028 tree = tree->children[i];
3029 }
3030 tree->index = (int)index;
3031 }
3032
3033 /*put a pixel, given its RGBA color, into image of any color type*/
3034 static unsigned rgba8ToPixel(unsigned char* out, size_t i,
3035 const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
3036 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3037 {
3038 if(mode->colortype == LCT_GREY)
3039 {
3040 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3041 if(mode->bitdepth == 8) out[i] = grey;
3042 else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
3043 else
3044 {
3045 /*take the most significant bits of grey*/
3046 grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
3047 addColorBits(out, i, mode->bitdepth, grey);
3048 }
3049 }
3050 else if(mode->colortype == LCT_RGB)
3051 {
3052 if(mode->bitdepth == 8)
3053 {
3054 out[i * 3 + 0] = r;
3055 out[i * 3 + 1] = g;
3056 out[i * 3 + 2] = b;
3057 }
3058 else
3059 {
3060 out[i * 6 + 0] = out[i * 6 + 1] = r;
3061 out[i * 6 + 2] = out[i * 6 + 3] = g;
3062 out[i * 6 + 4] = out[i * 6 + 5] = b;
3063 }
3064 }
3065 else if(mode->colortype == LCT_PALETTE)
3066 {
3067 int index = color_tree_get(tree, r, g, b, a);
3068 if(index < 0) return 82; /*color not in palette*/
3069 if(mode->bitdepth == 8) out[i] = index;
3070 else addColorBits(out, i, mode->bitdepth, (unsigned)index);
3071 }
3072 else if(mode->colortype == LCT_GREY_ALPHA)
3073 {
3074 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3075 if(mode->bitdepth == 8)
3076 {
3077 out[i * 2 + 0] = grey;
3078 out[i * 2 + 1] = a;
3079 }
3080 else if(mode->bitdepth == 16)
3081 {
3082 out[i * 4 + 0] = out[i * 4 + 1] = grey;
3083 out[i * 4 + 2] = out[i * 4 + 3] = a;
3084 }
3085 }
3086 else if(mode->colortype == LCT_RGBA)
3087 {
3088 if(mode->bitdepth == 8)
3089 {
3090 out[i * 4 + 0] = r;
3091 out[i * 4 + 1] = g;
3092 out[i * 4 + 2] = b;
3093 out[i * 4 + 3] = a;
3094 }
3095 else
3096 {
3097 out[i * 8 + 0] = out[i * 8 + 1] = r;
3098 out[i * 8 + 2] = out[i * 8 + 3] = g;
3099 out[i * 8 + 4] = out[i * 8 + 5] = b;
3100 out[i * 8 + 6] = out[i * 8 + 7] = a;
3101 }
3102 }
3103
3104 return 0; /*no error*/
3105 }
3106
3107 /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3108 static void rgba16ToPixel(unsigned char* out, size_t i,
3109 const LodePNGColorMode* mode,
3110 unsigned short r, unsigned short g, unsigned short b, unsigned short a)
3111 {
3112 if(mode->colortype == LCT_GREY)
3113 {
3114 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3115 out[i * 2 + 0] = (grey >> 8) & 255;
3116 out[i * 2 + 1] = grey & 255;
3117 }
3118 else if(mode->colortype == LCT_RGB)
3119 {
3120 out[i * 6 + 0] = (r >> 8) & 255;
3121 out[i * 6 + 1] = r & 255;
3122 out[i * 6 + 2] = (g >> 8) & 255;
3123 out[i * 6 + 3] = g & 255;
3124 out[i * 6 + 4] = (b >> 8) & 255;
3125 out[i * 6 + 5] = b & 255;
3126 }
3127 else if(mode->colortype == LCT_GREY_ALPHA)
3128 {
3129 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3130 out[i * 4 + 0] = (grey >> 8) & 255;
3131 out[i * 4 + 1] = grey & 255;
3132 out[i * 4 + 2] = (a >> 8) & 255;
3133 out[i * 4 + 3] = a & 255;
3134 }
3135 else if(mode->colortype == LCT_RGBA)
3136 {
3137 out[i * 8 + 0] = (r >> 8) & 255;
3138 out[i * 8 + 1] = r & 255;
3139 out[i * 8 + 2] = (g >> 8) & 255;
3140 out[i * 8 + 3] = g & 255;
3141 out[i * 8 + 4] = (b >> 8) & 255;
3142 out[i * 8 + 5] = b & 255;
3143 out[i * 8 + 6] = (a >> 8) & 255;
3144 out[i * 8 + 7] = a & 255;
3145 }
3146 }
3147
3148 /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3149 static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
3150 unsigned char* b, unsigned char* a,
3151 const unsigned char* in, size_t i,
3152 const LodePNGColorMode* mode)
3153 {
3154 if(mode->colortype == LCT_GREY)
3155 {
3156 if(mode->bitdepth == 8)
3157 {
3158 *r = *g = *b = in[i];
3159 if(mode->key_defined && *r == mode->key_r) *a = 0;
3160 else *a = 255;
3161 }
3162 else if(mode->bitdepth == 16)
3163 {
3164 *r = *g = *b = in[i * 2 + 0];
3165 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3166 else *a = 255;
3167 }
3168 else
3169 {
3170 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3171 size_t j = i * mode->bitdepth;
3172 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3173 *r = *g = *b = (value * 255) / highest;
3174 if(mode->key_defined && value == mode->key_r) *a = 0;
3175 else *a = 255;
3176 }
3177 }
3178 else if(mode->colortype == LCT_RGB)
3179 {
3180 if(mode->bitdepth == 8)
3181 {
3182 *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3183 if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3184 else *a = 255;
3185 }
3186 else
3187 {
3188 *r = in[i * 6 + 0];
3189 *g = in[i * 6 + 2];
3190 *b = in[i * 6 + 4];
3191 if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3192 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3193 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3194 else *a = 255;
3195 }
3196 }
3197 else if(mode->colortype == LCT_PALETTE)
3198 {
3199 unsigned index;
3200 if(mode->bitdepth == 8) index = in[i];
3201 else
3202 {
3203 size_t j = i * mode->bitdepth;
3204 index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3205 }
3206
3207 if(index >= mode->palettesize)
3208 {
3209 /*This is an error according to the PNG spec, but common PNG decoders make it black instead.
3210 Done here too, slightly faster due to no error handling needed.*/
3211 *r = *g = *b = 0;
3212 *a = 255;
3213 }
3214 else
3215 {
3216 *r = mode->palette[index * 4 + 0];
3217 *g = mode->palette[index * 4 + 1];
3218 *b = mode->palette[index * 4 + 2];
3219 *a = mode->palette[index * 4 + 3];
3220 }
3221 }
3222 else if(mode->colortype == LCT_GREY_ALPHA)
3223 {
3224 if(mode->bitdepth == 8)
3225 {
3226 *r = *g = *b = in[i * 2 + 0];
3227 *a = in[i * 2 + 1];
3228 }
3229 else
3230 {
3231 *r = *g = *b = in[i * 4 + 0];
3232 *a = in[i * 4 + 2];
3233 }
3234 }
3235 else if(mode->colortype == LCT_RGBA)
3236 {
3237 if(mode->bitdepth == 8)
3238 {
3239 *r = in[i * 4 + 0];
3240 *g = in[i * 4 + 1];
3241 *b = in[i * 4 + 2];
3242 *a = in[i * 4 + 3];
3243 }
3244 else
3245 {
3246 *r = in[i * 8 + 0];
3247 *g = in[i * 8 + 2];
3248 *b = in[i * 8 + 4];
3249 *a = in[i * 8 + 6];
3250 }
3251 }
3252 }
3253
3254 /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3255 mode test cases, optimized to convert the colors much faster, when converting
3256 to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3257 enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3258 of the input buffer.*/
3259 static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
3260 unsigned has_alpha, const unsigned char* in,
3261 const LodePNGColorMode* mode)
3262 {
3263 unsigned num_channels = has_alpha ? 4 : 3;
3264 size_t i;
3265 if(mode->colortype == LCT_GREY)
3266 {
3267 if(mode->bitdepth == 8)
3268 {
3269 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3270 {
3271 buffer[0] = buffer[1] = buffer[2] = in[i];
3272 if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
3273 }
3274 }
3275 else if(mode->bitdepth == 16)
3276 {
3277 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3278 {
3279 buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3280 if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
3281 }
3282 }
3283 else
3284 {
3285 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3286 size_t j = 0;
3287 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3288 {
3289 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3290 buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3291 if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
3292 }
3293 }
3294 }
3295 else if(mode->colortype == LCT_RGB)
3296 {
3297 if(mode->bitdepth == 8)
3298 {
3299 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3300 {
3301 buffer[0] = in[i * 3 + 0];
3302 buffer[1] = in[i * 3 + 1];
3303 buffer[2] = in[i * 3 + 2];
3304 if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
3305 && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
3306 }
3307 }
3308 else
3309 {
3310 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3311 {
3312 buffer[0] = in[i * 6 + 0];
3313 buffer[1] = in[i * 6 + 2];
3314 buffer[2] = in[i * 6 + 4];
3315 if(has_alpha) buffer[3] = mode->key_defined
3316 && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3317 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3318 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
3319 }
3320 }
3321 }
3322 else if(mode->colortype == LCT_PALETTE)
3323 {
3324 unsigned index;
3325 size_t j = 0;
3326 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3327 {
3328 if(mode->bitdepth == 8) index = in[i];
3329 else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3330
3331 if(index >= mode->palettesize)
3332 {
3333 /*This is an error according to the PNG spec, but most PNG decoders make it black instead.
3334 Done here too, slightly faster due to no error handling needed.*/
3335 buffer[0] = buffer[1] = buffer[2] = 0;
3336 if(has_alpha) buffer[3] = 255;
3337 }
3338 else
3339 {
3340 buffer[0] = mode->palette[index * 4 + 0];
3341 buffer[1] = mode->palette[index * 4 + 1];
3342 buffer[2] = mode->palette[index * 4 + 2];
3343 if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
3344 }
3345 }
3346 }
3347 else if(mode->colortype == LCT_GREY_ALPHA)
3348 {
3349 if(mode->bitdepth == 8)
3350 {
3351 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3352 {
3353 buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3354 if(has_alpha) buffer[3] = in[i * 2 + 1];
3355 }
3356 }
3357 else
3358 {
3359 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3360 {
3361 buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3362 if(has_alpha) buffer[3] = in[i * 4 + 2];
3363 }
3364 }
3365 }
3366 else if(mode->colortype == LCT_RGBA)
3367 {
3368 if(mode->bitdepth == 8)
3369 {
3370 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3371 {
3372 buffer[0] = in[i * 4 + 0];
3373 buffer[1] = in[i * 4 + 1];
3374 buffer[2] = in[i * 4 + 2];
3375 if(has_alpha) buffer[3] = in[i * 4 + 3];
3376 }
3377 }
3378 else
3379 {
3380 for(i = 0; i != numpixels; ++i, buffer += num_channels)
3381 {
3382 buffer[0] = in[i * 8 + 0];
3383 buffer[1] = in[i * 8 + 2];
3384 buffer[2] = in[i * 8 + 4];
3385 if(has_alpha) buffer[3] = in[i * 8 + 6];
3386 }
3387 }
3388 }
3389 }
3390
3391 /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3392 given color type, but the given color type must be 16-bit itself.*/
3393 static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3394 const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3395 {
3396 if(mode->colortype == LCT_GREY)
3397 {
3398 *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3399 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3400 else *a = 65535;
3401 }
3402 else if(mode->colortype == LCT_RGB)
3403 {
3404 *r = 256 * in[i * 6 + 0] + in[i * 6 + 1];
3405 *g = 256 * in[i * 6 + 2] + in[i * 6 + 3];
3406 *b = 256 * in[i * 6 + 4] + in[i * 6 + 5];
3407 if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3408 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3409 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3410 else *a = 65535;
3411 }
3412 else if(mode->colortype == LCT_GREY_ALPHA)
3413 {
3414 *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1];
3415 *a = 256 * in[i * 4 + 2] + in[i * 4 + 3];
3416 }
3417 else if(mode->colortype == LCT_RGBA)
3418 {
3419 *r = 256 * in[i * 8 + 0] + in[i * 8 + 1];
3420 *g = 256 * in[i * 8 + 2] + in[i * 8 + 3];
3421 *b = 256 * in[i * 8 + 4] + in[i * 8 + 5];
3422 *a = 256 * in[i * 8 + 6] + in[i * 8 + 7];
3423 }
3424 }
3425
3426 unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3427 const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
3428 unsigned w, unsigned h)
3429 {
3430 size_t i;
3431 ColorTree tree;
3432 size_t numpixels = w * h;
3433
3434 if(lodepng_color_mode_equal(mode_out, mode_in))
3435 {
3436 size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3437 for(i = 0; i != numbytes; ++i) out[i] = in[i];
3438 return 0;
3439 }
3440
3441 if(mode_out->colortype == LCT_PALETTE)
3442 {
3443 size_t palettesize = mode_out->palettesize;
3444 const unsigned char* palette = mode_out->palette;
3445 size_t palsize = 1u << mode_out->bitdepth;
3446 /*if the user specified output palette but did not give the values, assume
3447 they want the values of the input color type (assuming that one is palette).
3448 Note that we never create a new palette ourselves.*/
3449 if(palettesize == 0) {
3450 palettesize = mode_in->palettesize;
3451 palette = mode_in->palette;
3452 }
3453 if(palettesize < palsize) palsize = palettesize;
3454 color_tree_init(&tree);
3455 for(i = 0; i != palsize; ++i)
3456 {
3457 const unsigned char* p = &palette[i * 4];
3458 color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
3459 }
3460 }
3461
3462 if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
3463 {
3464 for(i = 0; i != numpixels; ++i)
3465 {
3466 unsigned short r = 0, g = 0, b = 0, a = 0;
3467 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3468 rgba16ToPixel(out, i, mode_out, r, g, b, a);
3469 }
3470 }
3471 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
3472 {
3473 getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
3474 }
3475 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
3476 {
3477 getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
3478 }
3479 else
3480 {
3481 unsigned char r = 0, g = 0, b = 0, a = 0;
3482 for(i = 0; i != numpixels; ++i)
3483 {
3484 getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3485 CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a));
3486 }
3487 }
3488
3489 if(mode_out->colortype == LCT_PALETTE)
3490 {
3491 color_tree_cleanup(&tree);
3492 }
3493
3494 return 0; /*no error*/
3495 }
3496
3497 #ifdef LODEPNG_COMPILE_ENCODER
3498
3499 void lodepng_color_profile_init(LodePNGColorProfile* profile)
3500 {
3501 profile->colored = 0;
3502 profile->key = 0;
3503 profile->alpha = 0;
3504 profile->key_r = profile->key_g = profile->key_b = 0;
3505 profile->numcolors = 0;
3506 profile->bits = 1;
3507 }
3508
3509 /*function used for debug purposes with C++*/
3510 /*void printColorProfile(LodePNGColorProfile* p)
3511 {
3512 std::cout << "colored: " << (int)p->colored << ", ";
3513 std::cout << "key: " << (int)p->key << ", ";
3514 std::cout << "key_r: " << (int)p->key_r << ", ";
3515 std::cout << "key_g: " << (int)p->key_g << ", ";
3516 std::cout << "key_b: " << (int)p->key_b << ", ";
3517 std::cout << "alpha: " << (int)p->alpha << ", ";
3518 std::cout << "numcolors: " << (int)p->numcolors << ", ";
3519 std::cout << "bits: " << (int)p->bits << std::endl;
3520 }*/
3521
3522 /*Returns how many bits needed to represent given value (max 8 bit)*/
3523 static unsigned getValueRequiredBits(unsigned char value)
3524 {
3525 if(value == 0 || value == 255) return 1;
3526 /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3527 if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
3528 return 8;
3529 }
3530
3531 /*profile must already have been inited with mode.
3532 It's ok to set some parameters of profile to done already.*/
3533 unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
3534 const unsigned char* in, unsigned w, unsigned h,
3535 const LodePNGColorMode* mode)
3536 {
3537 unsigned error = 0;
3538 size_t i;
3539 ColorTree tree;
3540 size_t numpixels = w * h;
3541
3542 unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
3543 unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
3544 unsigned numcolors_done = 0;
3545 unsigned bpp = lodepng_get_bpp(mode);
3546 unsigned bits_done = bpp == 1 ? 1 : 0;
3547 unsigned maxnumcolors = 257;
3548 unsigned sixteen = 0;
3549 if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
3550
3551 color_tree_init(&tree);
3552
3553 /*Check if the 16-bit input is truly 16-bit*/
3554 if(mode->bitdepth == 16)
3555 {
3556 unsigned short r, g, b, a;
3557 for(i = 0; i != numpixels; ++i)
3558 {
3559 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3560 if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
3561 (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/
3562 {
3563 sixteen = 1;
3564 break;
3565 }
3566 }
3567 }
3568
3569 if(sixteen)
3570 {
3571 unsigned short r = 0, g = 0, b = 0, a = 0;
3572 profile->bits = 16;
3573 bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3574
3575 for(i = 0; i != numpixels; ++i)
3576 {
3577 getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3578
3579 if(!colored_done && (r != g || r != b))
3580 {
3581 profile->colored = 1;
3582 colored_done = 1;
3583 }
3584
3585 if(!alpha_done)
3586 {
3587 unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3588 if(a != 65535 && (a != 0 || (profile->key && !matchkey)))
3589 {
3590 profile->alpha = 1;
3591 alpha_done = 1;
3592 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3593 }
3594 else if(a == 0 && !profile->alpha && !profile->key)
3595 {
3596 profile->key = 1;
3597 profile->key_r = r;
3598 profile->key_g = g;
3599 profile->key_b = b;
3600 }
3601 else if(a == 65535 && profile->key && matchkey)
3602 {
3603 /* Color key cannot be used if an opaque pixel also has that RGB color. */
3604 profile->alpha = 1;
3605 alpha_done = 1;
3606 }
3607 }
3608
3609 if(alpha_done && numcolors_done && colored_done && bits_done) break;
3610 }
3611 }
3612 else /* < 16-bit */
3613 {
3614 for(i = 0; i != numpixels; ++i)
3615 {
3616 unsigned char r = 0, g = 0, b = 0, a = 0;
3617 getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
3618
3619 if(!bits_done && profile->bits < 8)
3620 {
3621 /*only r is checked, < 8 bits is only relevant for greyscale*/
3622 unsigned bits = getValueRequiredBits(r);
3623 if(bits > profile->bits) profile->bits = bits;
3624 }
3625 bits_done = (profile->bits >= bpp);
3626
3627 if(!colored_done && (r != g || r != b))
3628 {
3629 profile->colored = 1;
3630 colored_done = 1;
3631 if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
3632 }
3633
3634 if(!alpha_done)
3635 {
3636 unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3637 if(a != 255 && (a != 0 || (profile->key && !matchkey)))
3638 {
3639 profile->alpha = 1;
3640 alpha_done = 1;
3641 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3642 }
3643 else if(a == 0 && !profile->alpha && !profile->key)
3644 {
3645 profile->key = 1;
3646 profile->key_r = r;
3647 profile->key_g = g;
3648 profile->key_b = b;
3649 }
3650 else if(a == 255 && profile->key && matchkey)
3651 {
3652 /* Color key cannot be used if an opaque pixel also has that RGB color. */
3653 profile->alpha = 1;
3654 alpha_done = 1;
3655 if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3656 }
3657 }
3658
3659 if(!numcolors_done)
3660 {
3661 if(!color_tree_has(&tree, r, g, b, a))
3662 {
3663 color_tree_add(&tree, r, g, b, a, profile->numcolors);
3664 if(profile->numcolors < 256)
3665 {
3666 unsigned char* p = profile->palette;
3667 unsigned n = profile->numcolors;
3668 p[n * 4 + 0] = r;
3669 p[n * 4 + 1] = g;
3670 p[n * 4 + 2] = b;
3671 p[n * 4 + 3] = a;
3672 }
3673 ++profile->numcolors;
3674 numcolors_done = profile->numcolors >= maxnumcolors;
3675 }
3676 }
3677
3678 if(alpha_done && numcolors_done && colored_done && bits_done) break;
3679 }
3680
3681 /*make the profile's key always 16-bit for consistency - repeat each byte twice*/
3682 profile->key_r += (profile->key_r << 8);
3683 profile->key_g += (profile->key_g << 8);
3684 profile->key_b += (profile->key_b << 8);
3685 }
3686
3687 color_tree_cleanup(&tree);
3688 return error;
3689 }
3690
3691 /*Automatically chooses color type that gives smallest amount of bits in the
3692 output image, e.g. grey if there are only greyscale pixels, palette if there
3693 are less than 256 colors, ...
3694 Updates values of mode with a potentially smaller color model. mode_out should
3695 contain the user chosen color model, but will be overwritten with the new chosen one.*/
3696 unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
3697 const unsigned char* image, unsigned w, unsigned h,
3698 const LodePNGColorMode* mode_in)
3699 {
3700 LodePNGColorProfile prof;
3701 unsigned error = 0;
3702 unsigned i, n, palettebits, grey_ok, palette_ok;
3703
3704 lodepng_color_profile_init(&prof);
3705 error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
3706 if(error) return error;
3707 mode_out->key_defined = 0;
3708
3709 if(prof.key && w * h <= 16)
3710 {
3711 prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
3712 if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3713 }
3714 grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/
3715 n = prof.numcolors;
3716 palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
3717 palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;
3718 if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
3719 if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/
3720
3721 if(palette_ok)
3722 {
3723 unsigned char* p = prof.palette;
3724 lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
3725 for(i = 0; i != prof.numcolors; ++i)
3726 {
3727 error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
3728 if(error) break;
3729 }
3730
3731 mode_out->colortype = LCT_PALETTE;
3732 mode_out->bitdepth = palettebits;
3733
3734 if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
3735 && mode_in->bitdepth == mode_out->bitdepth)
3736 {
3737 /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
3738 lodepng_color_mode_cleanup(mode_out);
3739 lodepng_color_mode_copy(mode_out, mode_in);
3740 }
3741 }
3742 else /*8-bit or 16-bit per channel*/
3743 {
3744 mode_out->bitdepth = prof.bits;
3745 mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA)
3746 : (prof.colored ? LCT_RGB : LCT_GREY);
3747
3748 if(prof.key && !prof.alpha)
3749 {
3750 unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/
3751 mode_out->key_r = prof.key_r & mask;
3752 mode_out->key_g = prof.key_g & mask;
3753 mode_out->key_b = prof.key_b & mask;
3754 mode_out->key_defined = 1;
3755 }
3756 }
3757
3758 return error;
3759 }
3760
3761 #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3762
3763 /*
3764 Paeth predicter, used by PNG filter type 4
3765 The parameters are of type short, but should come from unsigned chars, the shorts
3766 are only needed to make the paeth calculation correct.
3767 */
3768 static unsigned char paethPredictor(short a, short b, short c)
3769 {
3770 short pa = abs(b - c);
3771 short pb = abs(a - c);
3772 short pc = abs(a + b - c - c);
3773
3774 if(pc < pa && pc < pb) return (unsigned char)c;
3775 else if(pb < pa) return (unsigned char)b;
3776 else return (unsigned char)a;
3777 }
3778
3779 /*shared values used by multiple Adam7 related functions*/
3780
3781 static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3782 static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3783 static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3784 static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3785
3786 /*
3787 Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3788 passw: output containing the width of the 7 passes
3789 passh: output containing the height of the 7 passes
3790 filter_passstart: output containing the index of the start and end of each
3791 reduced image with filter bytes
3792 padded_passstart output containing the index of the start and end of each
3793 reduced image when without filter bytes but with padded scanlines
3794 passstart: output containing the index of the start and end of each reduced
3795 image without padding between scanlines, but still padding between the images
3796 w, h: width and height of non-interlaced image
3797 bpp: bits per pixel
3798 "padded" is only relevant if bpp is less than 8 and a scanline or image does not
3799 end at a full byte
3800 */
3801 static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
3802 size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
3803 {
3804 /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3805 unsigned i;
3806
3807 /*calculate width and height in pixels of each pass*/
3808 for(i = 0; i != 7; ++i)
3809 {
3810 passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
3811 passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
3812 if(passw[i] == 0) passh[i] = 0;
3813 if(passh[i] == 0) passw[i] = 0;
3814 }
3815
3816 filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
3817 for(i = 0; i != 7; ++i)
3818 {
3819 /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3820 filter_passstart[i + 1] = filter_passstart[i]
3821 + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
3822 /*bits padded if needed to fill full byte at end of each scanline*/
3823 padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
3824 /*only padded at end of reduced image*/
3825 passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
3826 }
3827 }
3828
3829 #ifdef LODEPNG_COMPILE_DECODER
3830
3831 /* ////////////////////////////////////////////////////////////////////////// */
3832 /* / PNG Decoder / */
3833 /* ////////////////////////////////////////////////////////////////////////// */
3834
3835 /*read the information from the header and store it in the LodePNGInfo. return value is error*/
3836 unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
3837 const unsigned char* in, size_t insize)
3838 {
3839 LodePNGInfo* info = &state->info_png;
3840 if(insize == 0 || in == 0)
3841 {
3842 CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
3843 }
3844 if(insize < 33)
3845 {
3846 CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
3847 }
3848
3849 /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3850 lodepng_info_cleanup(info);
3851 lodepng_info_init(info);
3852
3853 if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
3854 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
3855 {
3856 CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3857 }
3858 if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R')
3859 {
3860 CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
3861 }
3862
3863 /*read the values given in the header*/
3864 *w = lodepng_read32bitInt(&in[16]);
3865 *h = lodepng_read32bitInt(&in[20]);
3866 info->color.bitdepth = in[24];
3867 info->color.colortype = (LodePNGColorType)in[25];
3868 info->compression_method = in[26];
3869 info->filter_method = in[27];
3870 info->interlace_method = in[28];
3871
3872 if(*w == 0 || *h == 0)
3873 {
3874 CERROR_RETURN_ERROR(state->error, 93);
3875 }
3876
3877 if(!state->decoder.ignore_crc)
3878 {
3879 unsigned CRC = lodepng_read32bitInt(&in[29]);
3880 unsigned checksum = lodepng_crc32(&in[12], 17);
3881 if(CRC != checksum)
3882 {
3883 CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
3884 }
3885 }
3886
3887 /*error: only compression method 0 is allowed in the specification*/
3888 if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
3889 /*error: only filter method 0 is allowed in the specification*/
3890 if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
3891 /*error: only interlace methods 0 and 1 exist in the specification*/
3892 if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
3893
3894 state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
3895 return state->error;
3896 }
3897
3898 static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
3899 size_t bytewidth, unsigned char filterType, size_t length)
3900 {
3901 /*
3902 For PNG filter method 0
3903 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
3904 the filter works byte per byte (bytewidth = 1)
3905 precon is the previous unfiltered scanline, recon the result, scanline the current one
3906 the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
3907 recon and scanline MAY be the same memory address! precon must be disjoint.
3908 */
3909
3910 size_t i;
3911 switch(filterType)
3912 {
3913 case 0:
3914 for(i = 0; i != length; ++i) recon[i] = scanline[i];
3915 break;
3916 case 1:
3917 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3918 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
3919 break;
3920 case 2:
3921 if(precon)
3922 {
3923 for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
3924 }
3925 else
3926 {
3927 for(i = 0; i != length; ++i) recon[i] = scanline[i];
3928 }
3929 break;
3930 case 3:
3931 if(precon)
3932 {
3933 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + precon[i] / 2;
3934 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
3935 }
3936 else
3937 {
3938 for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3939 for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth] / 2;
3940 }
3941 break;
3942 case 4:
3943 if(precon)
3944 {
3945 for(i = 0; i != bytewidth; ++i)
3946 {
3947 recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
3948 }
3949 for(i = bytewidth; i < length; ++i)
3950 {
3951 recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
3952 }
3953 }
3954 else
3955 {
3956 for(i = 0; i != bytewidth; ++i)
3957 {
3958 recon[i] = scanline[i];
3959 }
3960 for(i = bytewidth; i < length; ++i)
3961 {
3962 /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
3963 recon[i] = (scanline[i] + recon[i - bytewidth]);
3964 }
3965 }
3966 break;
3967 default: return 36; /*error: unexisting filter type given*/
3968 }
3969 return 0;
3970 }
3971
3972 static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
3973 {
3974 /*
3975 For PNG filter method 0
3976 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
3977 out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
3978 w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
3979 in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
3980 */
3981
3982 unsigned y;
3983 unsigned char* prevline = 0;
3984
3985 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
3986 size_t bytewidth = (bpp + 7) / 8;
3987 size_t linebytes = (w * bpp + 7) / 8;
3988
3989 for(y = 0; y < h; ++y)
3990 {
3991 size_t outindex = linebytes * y;
3992 size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
3993 unsigned char filterType = in[inindex];
3994
3995 CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
3996
3997 prevline = &out[outindex];
3998 }
3999
4000 return 0;
4001 }
4002
4003 /*
4004 in: Adam7 interlaced image, with no padding bits between scanlines, but between
4005 reduced images so that each reduced image starts at a byte.
4006 out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4007 bpp: bits per pixel
4008 out has the following size in bits: w * h * bpp.
4009 in is possibly bigger due to padding bits between reduced images.
4010 out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4011 (because that's likely a little bit faster)
4012 NOTE: comments about padding bits are only relevant if bpp < 8
4013 */
4014 static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4015 {
4016 unsigned passw[7], passh[7];
4017 size_t filter_passstart[8], padded_passstart[8], passstart[8];
4018 unsigned i;
4019
4020 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4021
4022 if(bpp >= 8)
4023 {
4024 for(i = 0; i != 7; ++i)
4025 {
4026 unsigned x, y, b;
4027 size_t bytewidth = bpp / 8;
4028 for(y = 0; y < passh[i]; ++y)
4029 for(x = 0; x < passw[i]; ++x)
4030 {
4031 size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4032 size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
4033 for(b = 0; b < bytewidth; ++b)
4034 {
4035 out[pixeloutstart + b] = in[pixelinstart + b];
4036 }
4037 }
4038 }
4039 }
4040 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4041 {
4042 for(i = 0; i != 7; ++i)
4043 {
4044 unsigned x, y, b;
4045 unsigned ilinebits = bpp * passw[i];
4046 unsigned olinebits = bpp * w;
4047 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4048 for(y = 0; y < passh[i]; ++y)
4049 for(x = 0; x < passw[i]; ++x)
4050 {
4051 ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4052 obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
4053 for(b = 0; b < bpp; ++b)
4054 {
4055 unsigned char bit = readBitFromReversedStream(&ibp, in);
4056 /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4057 setBitOfReversedStream0(&obp, out, bit);
4058 }
4059 }
4060 }
4061 }
4062 }
4063
4064 static void removePaddingBits(unsigned char* out, const unsigned char* in,
4065 size_t olinebits, size_t ilinebits, unsigned h)
4066 {
4067 /*
4068 After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4069 to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4070 for the Adam7 code, the color convert code and the output to the user.
4071 in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4072 have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4073 also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4074 only useful if (ilinebits - olinebits) is a value in the range 1..7
4075 */
4076 unsigned y;
4077 size_t diff = ilinebits - olinebits;
4078 size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4079 for(y = 0; y < h; ++y)
4080 {
4081 size_t x;
4082 for(x = 0; x < olinebits; ++x)
4083 {
4084 unsigned char bit = readBitFromReversedStream(&ibp, in);
4085 setBitOfReversedStream(&obp, out, bit);
4086 }
4087 ibp += diff;
4088 }
4089 }
4090
4091 /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4092 the IDAT chunks (with filter index bytes and possible padding bits)
4093 return value is error*/
4094 static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4095 unsigned w, unsigned h, const LodePNGInfo* info_png)
4096 {
4097 /*
4098 This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4099 Steps:
4100 *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4101 *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4102 NOTE: the in buffer will be overwritten with intermediate data!
4103 */
4104 unsigned bpp = lodepng_get_bpp(&info_png->color);
4105 if(bpp == 0) return 31; /*error: invalid colortype*/
4106
4107 if(info_png->interlace_method == 0)
4108 {
4109 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
4110 {
4111 CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4112 removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
4113 }
4114 /*we can immediately filter into the out buffer, no other steps needed*/
4115 else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4116 }
4117 else /*interlace_method is 1 (Adam7)*/
4118 {
4119 unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4120 unsigned i;
4121
4122 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4123
4124 for(i = 0; i != 7; ++i)
4125 {
4126 CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4127 /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4128 move bytes instead of bits or move not at all*/
4129 if(bpp < 8)
4130 {
4131 /*remove padding bits in scanlines; after this there still may be padding
4132 bits between the different reduced images: each reduced image still starts nicely at a byte*/
4133 removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4134 ((passw[i] * bpp + 7) / 8) * 8, passh[i]);
4135 }
4136 }
4137
4138 Adam7_deinterlace(out, in, w, h, bpp);
4139 }
4140
4141 return 0;
4142 }
4143
4144 static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4145 {
4146 unsigned pos = 0, i;
4147 if(color->palette) lodepng_free(color->palette);
4148 color->palettesize = chunkLength / 3;
4149 color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize);
4150 if(!color->palette && color->palettesize)
4151 {
4152 color->palettesize = 0;
4153 return 83; /*alloc fail*/
4154 }
4155 if(color->palettesize > 256) return 38; /*error: palette too big*/
4156
4157 for(i = 0; i != color->palettesize; ++i)
4158 {
4159 color->palette[4 * i + 0] = data[pos++]; /*R*/
4160 color->palette[4 * i + 1] = data[pos++]; /*G*/
4161 color->palette[4 * i + 2] = data[pos++]; /*B*/
4162 color->palette[4 * i + 3] = 255; /*alpha*/
4163 }
4164
4165 return 0; /* OK */
4166 }
4167
4168 static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4169 {
4170 unsigned i;
4171 if(color->colortype == LCT_PALETTE)
4172 {
4173 /*error: more alpha values given than there are palette entries*/
4174 if(chunkLength > color->palettesize) return 38;
4175
4176 for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
4177 }
4178 else if(color->colortype == LCT_GREY)
4179 {
4180 /*error: this chunk must be 2 bytes for greyscale image*/
4181 if(chunkLength != 2) return 30;
4182
4183 color->key_defined = 1;
4184 color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
4185 }
4186 else if(color->colortype == LCT_RGB)
4187 {
4188 /*error: this chunk must be 6 bytes for RGB image*/
4189 if(chunkLength != 6) return 41;
4190
4191 color->key_defined = 1;
4192 color->key_r = 256u * data[0] + data[1];
4193 color->key_g = 256u * data[2] + data[3];
4194 color->key_b = 256u * data[4] + data[5];
4195 }
4196 else return 42; /*error: tRNS chunk not allowed for other color models*/
4197
4198 return 0; /* OK */
4199 }
4200
4201
4202 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4203 /*background color chunk (bKGD)*/
4204 static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4205 {
4206 if(info->color.colortype == LCT_PALETTE)
4207 {
4208 /*error: this chunk must be 1 byte for indexed color image*/
4209 if(chunkLength != 1) return 43;
4210
4211 info->background_defined = 1;
4212 info->background_r = info->background_g = info->background_b = data[0];
4213 }
4214 else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
4215 {
4216 /*error: this chunk must be 2 bytes for greyscale image*/
4217 if(chunkLength != 2) return 44;
4218
4219 info->background_defined = 1;
4220 info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
4221 }
4222 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
4223 {
4224 /*error: this chunk must be 6 bytes for greyscale image*/
4225 if(chunkLength != 6) return 45;
4226
4227 info->background_defined = 1;
4228 info->background_r = 256u * data[0] + data[1];
4229 info->background_g = 256u * data[2] + data[3];
4230 info->background_b = 256u * data[4] + data[5];
4231 }
4232
4233 return 0; /* OK */
4234 }
4235
4236 /*text chunk (tEXt)*/
4237 static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4238 {
4239 unsigned error = 0;
4240 char *key = 0, *str = 0;
4241 unsigned i;
4242
4243 while(!error) /*not really a while loop, only used to break on error*/
4244 {
4245 unsigned length, string2_begin;
4246
4247 length = 0;
4248 while(length < chunkLength && data[length] != 0) ++length;
4249 /*even though it's not allowed by the standard, no error is thrown if
4250 there's no null termination char, if the text is empty*/
4251 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4252
4253 key = (char*)lodepng_malloc(length + 1);
4254 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4255
4256 key[length] = 0;
4257 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4258
4259 string2_begin = length + 1; /*skip keyword null terminator*/
4260
4261 length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
4262 str = (char*)lodepng_malloc(length + 1);
4263 if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
4264
4265 str[length] = 0;
4266 for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
4267
4268 error = lodepng_add_text(info, key, str);
4269
4270 break;
4271 }
4272
4273 lodepng_free(key);
4274 lodepng_free(str);
4275
4276 return error;
4277 }
4278
4279 /*compressed text chunk (zTXt)*/
4280 static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4281 const unsigned char* data, size_t chunkLength)
4282 {
4283 unsigned error = 0;
4284 unsigned i;
4285
4286 unsigned length, string2_begin;
4287 char *key = 0;
4288 ucvector decoded;
4289
4290 ucvector_init(&decoded);
4291
4292 while(!error) /*not really a while loop, only used to break on error*/
4293 {
4294 for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4295 if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4296 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4297
4298 key = (char*)lodepng_malloc(length + 1);
4299 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4300
4301 key[length] = 0;
4302 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4303
4304 if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4305
4306 string2_begin = length + 2;
4307 if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4308
4309 length = chunkLength - string2_begin;
4310 /*will fail if zlib error, e.g. if length is too small*/
4311 error = zlib_decompress(&decoded.data, &decoded.size,
4312 (unsigned char*)(&data[string2_begin]),
4313 length, zlibsettings);
4314 if(error) break;
4315 ucvector_push_back(&decoded, 0);
4316
4317 error = lodepng_add_text(info, key, (char*)decoded.data);
4318
4319 break;
4320 }
4321
4322 lodepng_free(key);
4323 ucvector_cleanup(&decoded);
4324
4325 return error;
4326 }
4327
4328 /*international text chunk (iTXt)*/
4329 static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4330 const unsigned char* data, size_t chunkLength)
4331 {
4332 unsigned error = 0;
4333 unsigned i;
4334
4335 unsigned length, begin, compressed;
4336 char *key = 0, *langtag = 0, *transkey = 0;
4337 ucvector decoded;
4338 ucvector_init(&decoded);
4339
4340 while(!error) /*not really a while loop, only used to break on error*/
4341 {
4342 /*Quick check if the chunk length isn't too small. Even without check
4343 it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4344 if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
4345
4346 /*read the key*/
4347 for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4348 if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
4349 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4350
4351 key = (char*)lodepng_malloc(length + 1);
4352 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4353
4354 key[length] = 0;
4355 for(i = 0; i != length; ++i) key[i] = (char)data[i];
4356
4357 /*read the compression method*/
4358 compressed = data[length + 1];
4359 if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4360
4361 /*even though it's not allowed by the standard, no error is thrown if
4362 there's no null termination char, if the text is empty for the next 3 texts*/
4363
4364 /*read the langtag*/
4365 begin = length + 3;
4366 length = 0;
4367 for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4368
4369 langtag = (char*)lodepng_malloc(length + 1);
4370 if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
4371
4372 langtag[length] = 0;
4373 for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
4374
4375 /*read the transkey*/
4376 begin += length + 1;
4377 length = 0;
4378 for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4379
4380 transkey = (char*)lodepng_malloc(length + 1);
4381 if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
4382
4383 transkey[length] = 0;
4384 for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
4385
4386 /*read the actual text*/
4387 begin += length + 1;
4388
4389 length = chunkLength < begin ? 0 : chunkLength - begin;
4390
4391 if(compressed)
4392 {
4393 /*will fail if zlib error, e.g. if length is too small*/
4394 error = zlib_decompress(&decoded.data, &decoded.size,
4395 (unsigned char*)(&data[begin]),
4396 length, zlibsettings);
4397 if(error) break;
4398 if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
4399 ucvector_push_back(&decoded, 0);
4400 }
4401 else
4402 {
4403 if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
4404
4405 decoded.data[length] = 0;
4406 for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
4407 }
4408
4409 error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
4410
4411 break;
4412 }
4413
4414 lodepng_free(key);
4415 lodepng_free(langtag);
4416 lodepng_free(transkey);
4417 ucvector_cleanup(&decoded);
4418
4419 return error;
4420 }
4421
4422 static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4423 {
4424 if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
4425
4426 info->time_defined = 1;
4427 info->time.year = 256u * data[0] + data[1];
4428 info->time.month = data[2];
4429 info->time.day = data[3];
4430 info->time.hour = data[4];
4431 info->time.minute = data[5];
4432 info->time.second = data[6];
4433
4434 return 0; /* OK */
4435 }
4436
4437 static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4438 {
4439 if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
4440
4441 info->phys_defined = 1;
4442 info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
4443 info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
4444 info->phys_unit = data[8];
4445
4446 return 0; /* OK */
4447 }
4448 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4449
4450 /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4451 static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
4452 LodePNGState* state,
4453 const unsigned char* in, size_t insize)
4454 {
4455 unsigned char IEND = 0;
4456 const unsigned char* chunk;
4457 size_t i;
4458 ucvector idat; /*the data from idat chunks*/
4459 ucvector scanlines;
4460 size_t predict;
4461 size_t numpixels;
4462
4463 /*for unknown chunk order*/
4464 unsigned unknown = 0;
4465 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4466 unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4467 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4468
4469 /*provide some proper output values if error will happen*/
4470 *out = 0;
4471
4472 state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
4473 if(state->error) return;
4474
4475 numpixels = *w * *h;
4476
4477 /*multiplication overflow*/
4478 if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92);
4479 /*multiplication overflow possible further below. Allows up to 2^31-1 pixel
4480 bytes with 16-bit RGBA, the rest is room for filter bytes.*/
4481 if(numpixels > 268435455) CERROR_RETURN(state->error, 92);
4482
4483 ucvector_init(&idat);
4484 chunk = &in[33]; /*first byte of the first chunk after the header*/
4485
4486 /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4487 IDAT data is put at the start of the in buffer*/
4488 while(!IEND && !state->error)
4489 {
4490 unsigned chunkLength;
4491 const unsigned char* data; /*the data in the chunk*/
4492
4493 /*error: size of the in buffer too small to contain next chunk*/
4494 if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
4495
4496 /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4497 chunkLength = lodepng_chunk_length(chunk);
4498 /*error: chunk length larger than the max PNG chunk size*/
4499 if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
4500
4501 if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
4502 {
4503 CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
4504 }
4505
4506 data = lodepng_chunk_data_const(chunk);
4507
4508 /*IDAT chunk, containing compressed image data*/
4509 if(lodepng_chunk_type_equals(chunk, "IDAT"))
4510 {
4511 size_t oldsize = idat.size;
4512 if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4513 for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
4514 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4515 critical_pos = 3;
4516 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4517 }
4518 /*IEND chunk*/
4519 else if(lodepng_chunk_type_equals(chunk, "IEND"))
4520 {
4521 IEND = 1;
4522 }
4523 /*palette chunk (PLTE)*/
4524 else if(lodepng_chunk_type_equals(chunk, "PLTE"))
4525 {
4526 state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
4527 if(state->error) break;
4528 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4529 critical_pos = 2;
4530 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4531 }
4532 /*palette transparency chunk (tRNS)*/
4533 else if(lodepng_chunk_type_equals(chunk, "tRNS"))
4534 {
4535 state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
4536 if(state->error) break;
4537 }
4538 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4539 /*background color chunk (bKGD)*/
4540 else if(lodepng_chunk_type_equals(chunk, "bKGD"))
4541 {
4542 state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
4543 if(state->error) break;
4544 }
4545 /*text chunk (tEXt)*/
4546 else if(lodepng_chunk_type_equals(chunk, "tEXt"))
4547 {
4548 if(state->decoder.read_text_chunks)
4549 {
4550 state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
4551 if(state->error) break;
4552 }
4553 }
4554 /*compressed text chunk (zTXt)*/
4555 else if(lodepng_chunk_type_equals(chunk, "zTXt"))
4556 {
4557 if(state->decoder.read_text_chunks)
4558 {
4559 state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4560 if(state->error) break;
4561 }
4562 }
4563 /*international text chunk (iTXt)*/
4564 else if(lodepng_chunk_type_equals(chunk, "iTXt"))
4565 {
4566 if(state->decoder.read_text_chunks)
4567 {
4568 state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4569 if(state->error) break;
4570 }
4571 }
4572 else if(lodepng_chunk_type_equals(chunk, "tIME"))
4573 {
4574 state->error = readChunk_tIME(&state->info_png, data, chunkLength);
4575 if(state->error) break;
4576 }
4577 else if(lodepng_chunk_type_equals(chunk, "pHYs"))
4578 {
4579 state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
4580 if(state->error) break;
4581 }
4582 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4583 else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4584 {
4585 /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4586 if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
4587
4588 unknown = 1;
4589 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4590 if(state->decoder.remember_unknown_chunks)
4591 {
4592 state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
4593 &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
4594 if(state->error) break;
4595 }
4596 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4597 }
4598
4599 if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
4600 {
4601 if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
4602 }
4603
4604 if(!IEND) chunk = lodepng_chunk_next_const(chunk);
4605 }
4606
4607 ucvector_init(&scanlines);
4608 /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
4609 If the decompressed size does not match the prediction, the image must be corrupt.*/
4610 if(state->info_png.interlace_method == 0)
4611 {
4612 /*The extra *h is added because this are the filter bytes every scanline starts with*/
4613 predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h;
4614 }
4615 else
4616 {
4617 /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
4618 const LodePNGColorMode* color = &state->info_png.color;
4619 predict = 0;
4620 predict += lodepng_get_raw_size_idat((*w + 7) / 8, (*h + 7) / 8, color) + (*h + 7) / 8;
4621 if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) / 8, (*h + 7) / 8, color) + (*h + 7) / 8;
4622 predict += lodepng_get_raw_size_idat((*w + 3) / 4, (*h + 3) / 8, color) + (*h + 3) / 8;
4623 if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) / 4, (*h + 3) / 4, color) + (*h + 3) / 4;
4624 predict += lodepng_get_raw_size_idat((*w + 1) / 2, (*h + 1) / 4, color) + (*h + 1) / 4;
4625 if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) / 2, (*h + 1) / 2, color) + (*h + 1) / 2;
4626 predict += lodepng_get_raw_size_idat((*w + 0) / 1, (*h + 0) / 2, color) + (*h + 0) / 2;
4627 }
4628 if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
4629 if(!state->error)
4630 {
4631 state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
4632 idat.size, &state->decoder.zlibsettings);
4633 if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/
4634 }
4635 ucvector_cleanup(&idat);
4636
4637 if(!state->error)
4638 {
4639 size_t outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
4640 ucvector outv;
4641 ucvector_init(&outv);
4642 if(!ucvector_resizev(&outv, outsize, 0)) state->error = 83; /*alloc fail*/
4643 if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png);
4644 *out = outv.data;
4645 }
4646 ucvector_cleanup(&scanlines);
4647 }
4648
4649 unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
4650 LodePNGState* state,
4651 const unsigned char* in, size_t insize)
4652 {
4653 *out = 0;
4654 decodeGeneric(out, w, h, state, in, insize);
4655 if(state->error) return state->error;
4656 if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
4657 {
4658 /*same color type, no copying or converting of data needed*/
4659 /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4660 the raw image has to the end user*/
4661 if(!state->decoder.color_convert)
4662 {
4663 state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
4664 if(state->error) return state->error;
4665 }
4666 }
4667 else
4668 {
4669 /*color conversion needed; sort of copy of the data*/
4670 unsigned char* data = *out;
4671 size_t outsize;
4672
4673 /*TODO: check if this works according to the statement in the documentation: "The converter can convert
4674 from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4675 if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
4676 && !(state->info_raw.bitdepth == 8))
4677 {
4678 return 56; /*unsupported color mode conversion*/
4679 }
4680
4681 outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
4682 *out = (unsigned char*)lodepng_malloc(outsize);
4683 if(!(*out))
4684 {
4685 state->error = 83; /*alloc fail*/
4686 }
4687 else state->error = lodepng_convert(*out, data, &state->info_raw,
4688 &state->info_png.color, *w, *h);
4689 lodepng_free(data);
4690 }
4691 return state->error;
4692 }
4693
4694 unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
4695 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
4696 {
4697 unsigned error;
4698 LodePNGState state;
4699 lodepng_state_init(&state);
4700 state.info_raw.colortype = colortype;
4701 state.info_raw.bitdepth = bitdepth;
4702 error = lodepng_decode(out, w, h, &state, in, insize);
4703 lodepng_state_cleanup(&state);
4704 return error;
4705 }
4706
4707 unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4708 {
4709 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
4710 }
4711
4712 unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4713 {
4714 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
4715 }
4716
4717 #ifdef LODEPNG_COMPILE_DISK
4718 unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
4719 LodePNGColorType colortype, unsigned bitdepth)
4720 {
4721 unsigned char* buffer;
4722 size_t buffersize;
4723 unsigned error;
4724 error = lodepng_load_file(&buffer, &buffersize, filename);
4725 if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
4726 lodepng_free(buffer);
4727 return error;
4728 }
4729
4730 unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4731 {
4732 return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
4733 }
4734
4735 unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4736 {
4737 return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
4738 }
4739 #endif /*LODEPNG_COMPILE_DISK*/
4740
4741 void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
4742 {
4743 settings->color_convert = 1;
4744 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4745 settings->read_text_chunks = 1;
4746 settings->remember_unknown_chunks = 0;
4747 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4748 settings->ignore_crc = 0;
4749 lodepng_decompress_settings_init(&settings->zlibsettings);
4750 }
4751
4752 #endif /*LODEPNG_COMPILE_DECODER*/
4753
4754 #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4755
4756 void lodepng_state_init(LodePNGState* state)
4757 {
4758 #ifdef LODEPNG_COMPILE_DECODER
4759 lodepng_decoder_settings_init(&state->decoder);
4760 #endif /*LODEPNG_COMPILE_DECODER*/
4761 #ifdef LODEPNG_COMPILE_ENCODER
4762 lodepng_encoder_settings_init(&state->encoder);
4763 #endif /*LODEPNG_COMPILE_ENCODER*/
4764 lodepng_color_mode_init(&state->info_raw);
4765 lodepng_info_init(&state->info_png);
4766 state->error = 1;
4767 }
4768
4769 void lodepng_state_cleanup(LodePNGState* state)
4770 {
4771 lodepng_color_mode_cleanup(&state->info_raw);
4772 lodepng_info_cleanup(&state->info_png);
4773 }
4774
4775 void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
4776 {
4777 lodepng_state_cleanup(dest);
4778 *dest = *source;
4779 lodepng_color_mode_init(&dest->info_raw);
4780 lodepng_info_init(&dest->info_png);
4781 dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
4782 dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
4783 }
4784
4785 #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4786
4787 #ifdef LODEPNG_COMPILE_ENCODER
4788
4789 /* ////////////////////////////////////////////////////////////////////////// */
4790 /* / PNG Encoder / */
4791 /* ////////////////////////////////////////////////////////////////////////// */
4792
4793 /*chunkName must be string of 4 characters*/
4794 static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
4795 {
4796 CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
4797 out->allocsize = out->size; /*fix the allocsize again*/
4798 return 0;
4799 }
4800
4801 static void writeSignature(ucvector* out)
4802 {
4803 /*8 bytes PNG signature, aka the magic bytes*/
4804 ucvector_push_back(out, 137);
4805 ucvector_push_back(out, 80);
4806 ucvector_push_back(out, 78);
4807 ucvector_push_back(out, 71);
4808 ucvector_push_back(out, 13);
4809 ucvector_push_back(out, 10);
4810 ucvector_push_back(out, 26);
4811 ucvector_push_back(out, 10);
4812 }
4813
4814 static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
4815 LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
4816 {
4817 unsigned error = 0;
4818 ucvector header;
4819 ucvector_init(&header);
4820
4821 lodepng_add32bitInt(&header, w); /*width*/
4822 lodepng_add32bitInt(&header, h); /*height*/
4823 ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
4824 ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
4825 ucvector_push_back(&header, 0); /*compression method*/
4826 ucvector_push_back(&header, 0); /*filter method*/
4827 ucvector_push_back(&header, interlace_method); /*interlace method*/
4828
4829 error = addChunk(out, "IHDR", header.data, header.size);
4830 ucvector_cleanup(&header);
4831
4832 return error;
4833 }
4834
4835 static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
4836 {
4837 unsigned error = 0;
4838 size_t i;
4839 ucvector PLTE;
4840 ucvector_init(&PLTE);
4841 for(i = 0; i != info->palettesize * 4; ++i)
4842 {
4843 /*add all channels except alpha channel*/
4844 if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
4845 }
4846 error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
4847 ucvector_cleanup(&PLTE);
4848
4849 return error;
4850 }
4851
4852 static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
4853 {
4854 unsigned error = 0;
4855 size_t i;
4856 ucvector tRNS;
4857 ucvector_init(&tRNS);
4858 if(info->colortype == LCT_PALETTE)
4859 {
4860 size_t amount = info->palettesize;
4861 /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4862 for(i = info->palettesize; i != 0; --i)
4863 {
4864 if(info->palette[4 * (i - 1) + 3] == 255) --amount;
4865 else break;
4866 }
4867 /*add only alpha channel*/
4868 for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
4869 }
4870 else if(info->colortype == LCT_GREY)
4871 {
4872 if(info->key_defined)
4873 {
4874 ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4875 ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4876 }
4877 }
4878 else if(info->colortype == LCT_RGB)
4879 {
4880 if(info->key_defined)
4881 {
4882 ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4883 ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4884 ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256));
4885 ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256));
4886 ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256));
4887 ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256));
4888 }
4889 }
4890
4891 error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
4892 ucvector_cleanup(&tRNS);
4893
4894 return error;
4895 }
4896
4897 static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
4898 LodePNGCompressSettings* zlibsettings)
4899 {
4900 ucvector zlibdata;
4901 unsigned error = 0;
4902
4903 /*compress with the Zlib compressor*/
4904 ucvector_init(&zlibdata);
4905 error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
4906 if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
4907 ucvector_cleanup(&zlibdata);
4908
4909 return error;
4910 }
4911
4912 static unsigned addChunk_IEND(ucvector* out)
4913 {
4914 unsigned error = 0;
4915 error = addChunk(out, "IEND", 0, 0);
4916 return error;
4917 }
4918
4919 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4920
4921 static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
4922 {
4923 unsigned error = 0;
4924 size_t i;
4925 ucvector text;
4926 ucvector_init(&text);
4927 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
4928 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4929 ucvector_push_back(&text, 0); /*0 termination char*/
4930 for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
4931 error = addChunk(out, "tEXt", text.data, text.size);
4932 ucvector_cleanup(&text);
4933
4934 return error;
4935 }
4936
4937 static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
4938 LodePNGCompressSettings* zlibsettings)
4939 {
4940 unsigned error = 0;
4941 ucvector data, compressed;
4942 size_t i, textsize = strlen(textstring);
4943
4944 ucvector_init(&data);
4945 ucvector_init(&compressed);
4946 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4947 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4948 ucvector_push_back(&data, 0); /*0 termination char*/
4949 ucvector_push_back(&data, 0); /*compression method: 0*/
4950
4951 error = zlib_compress(&compressed.data, &compressed.size,
4952 (unsigned char*)textstring, textsize, zlibsettings);
4953 if(!error)
4954 {
4955 for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
4956 error = addChunk(out, "zTXt", data.data, data.size);
4957 }
4958
4959 ucvector_cleanup(&compressed);
4960 ucvector_cleanup(&data);
4961 return error;
4962 }
4963
4964 static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
4965 const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
4966 {
4967 unsigned error = 0;
4968 ucvector data;
4969 size_t i, textsize = strlen(textstring);
4970
4971 ucvector_init(&data);
4972
4973 for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4974 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4975 ucvector_push_back(&data, 0); /*null termination char*/
4976 ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
4977 ucvector_push_back(&data, 0); /*compression method*/
4978 for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
4979 ucvector_push_back(&data, 0); /*null termination char*/
4980 for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
4981 ucvector_push_back(&data, 0); /*null termination char*/
4982
4983 if(compressed)
4984 {
4985 ucvector compressed_data;
4986 ucvector_init(&compressed_data);
4987 error = zlib_compress(&compressed_data.data, &compressed_data.size,
4988 (unsigned char*)textstring, textsize, zlibsettings);
4989 if(!error)
4990 {
4991 for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
4992 }
4993 ucvector_cleanup(&compressed_data);
4994 }
4995 else /*not compressed*/
4996 {
4997 for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
4998 }
4999
5000 if(!error) error = addChunk(out, "iTXt", data.data, data.size);
5001 ucvector_cleanup(&data);
5002 return error;
5003 }
5004
5005 static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info)
5006 {
5007 unsigned error = 0;
5008 ucvector bKGD;
5009 ucvector_init(&bKGD);
5010 if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
5011 {
5012 ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5013 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5014 }
5015 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
5016 {
5017 ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5018 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5019 ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256));
5020 ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256));
5021 ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256));
5022 ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256));
5023 }
5024 else if(info->color.colortype == LCT_PALETTE)
5025 {
5026 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/
5027 }
5028
5029 error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
5030 ucvector_cleanup(&bKGD);
5031
5032 return error;
5033 }
5034
5035 static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time)
5036 {
5037 unsigned error = 0;
5038 unsigned char* data = (unsigned char*)lodepng_malloc(7);
5039 if(!data) return 83; /*alloc fail*/
5040 data[0] = (unsigned char)(time->year / 256);
5041 data[1] = (unsigned char)(time->year % 256);
5042 data[2] = (unsigned char)time->month;
5043 data[3] = (unsigned char)time->day;
5044 data[4] = (unsigned char)time->hour;
5045 data[5] = (unsigned char)time->minute;
5046 data[6] = (unsigned char)time->second;
5047 error = addChunk(out, "tIME", data, 7);
5048 lodepng_free(data);
5049 return error;
5050 }
5051
5052 static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
5053 {
5054 unsigned error = 0;
5055 ucvector data;
5056 ucvector_init(&data);
5057
5058 lodepng_add32bitInt(&data, info->phys_x);
5059 lodepng_add32bitInt(&data, info->phys_y);
5060 ucvector_push_back(&data, info->phys_unit);
5061
5062 error = addChunk(out, "pHYs", data.data, data.size);
5063 ucvector_cleanup(&data);
5064
5065 return error;
5066 }
5067
5068 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5069
5070 static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
5071 size_t length, size_t bytewidth, unsigned char filterType)
5072 {
5073 size_t i;
5074 switch(filterType)
5075 {
5076 case 0: /*None*/
5077 for(i = 0; i != length; ++i) out[i] = scanline[i];
5078 break;
5079 case 1: /*Sub*/
5080 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5081 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
5082 break;
5083 case 2: /*Up*/
5084 if(prevline)
5085 {
5086 for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
5087 }
5088 else
5089 {
5090 for(i = 0; i != length; ++i) out[i] = scanline[i];
5091 }
5092 break;
5093 case 3: /*Average*/
5094 if(prevline)
5095 {
5096 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - prevline[i] / 2;
5097 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2);
5098 }
5099 else
5100 {
5101 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5102 for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth] / 2;
5103 }
5104 break;
5105 case 4: /*Paeth*/
5106 if(prevline)
5107 {
5108 /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5109 for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
5110 for(i = bytewidth; i < length; ++i)
5111 {
5112 out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
5113 }
5114 }
5115 else
5116 {
5117 for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5118 /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5119 for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
5120 }
5121 break;
5122 default: return; /*unexisting filter type given*/
5123 }
5124 }
5125
5126 /* log2 approximation. A slight bit faster than std::log. */
5127 static float flog2(float f)
5128 {
5129 float result = 0;
5130 while(f > 32) { result += 4; f /= 16; }
5131 while(f > 2) { ++result; f /= 2; }
5132 return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
5133 }
5134
5135 static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
5136 const LodePNGColorMode* info, const LodePNGEncoderSettings* settings)
5137 {
5138 /*
5139 For PNG filter method 0
5140 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5141 the scanlines with 1 extra byte per scanline
5142 */
5143
5144 unsigned bpp = lodepng_get_bpp(info);
5145 /*the width of a scanline in bytes, not including the filter type*/
5146 size_t linebytes = (w * bpp + 7) / 8;
5147 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5148 size_t bytewidth = (bpp + 7) / 8;
5149 const unsigned char* prevline = 0;
5150 unsigned x, y;
5151 unsigned error = 0;
5152 LodePNGFilterStrategy strategy = settings->filter_strategy;
5153
5154 /*
5155 There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5156 * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5157 use fixed filtering, with the filter None).
5158 * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5159 not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5160 all five filters and select the filter that produces the smallest sum of absolute values per row.
5161 This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5162
5163 If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5164 but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5165 heuristic is used.
5166 */
5167 if(settings->filter_palette_zero &&
5168 (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
5169
5170 if(bpp == 0) return 31; /*error: invalid color type*/
5171
5172 if(strategy == LFS_ZERO)
5173 {
5174 for(y = 0; y != h; ++y)
5175 {
5176 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5177 size_t inindex = linebytes * y;
5178 out[outindex] = 0; /*filter type byte*/
5179 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
5180 prevline = &in[inindex];
5181 }
5182 }
5183 else if(strategy == LFS_MINSUM)
5184 {
5185 /*adaptive filtering*/
5186 size_t sum[5];
5187 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5188 size_t smallest = 0;
5189 unsigned char type, bestType = 0;
5190
5191 for(type = 0; type != 5; ++type)
5192 {
5193 ucvector_init(&attempt[type]);
5194 if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5195 }
5196
5197 if(!error)
5198 {
5199 for(y = 0; y != h; ++y)
5200 {
5201 /*try the 5 filter types*/
5202 for(type = 0; type != 5; ++type)
5203 {
5204 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5205
5206 /*calculate the sum of the result*/
5207 sum[type] = 0;
5208 if(type == 0)
5209 {
5210 for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type].data[x]);
5211 }
5212 else
5213 {
5214 for(x = 0; x != linebytes; ++x)
5215 {
5216 /*For differences, each byte should be treated as signed, values above 127 are negative
5217 (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5218 This means filtertype 0 is almost never chosen, but that is justified.*/
5219 unsigned char s = attempt[type].data[x];
5220 sum[type] += s < 128 ? s : (255U - s);
5221 }
5222 }
5223
5224 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5225 if(type == 0 || sum[type] < smallest)
5226 {
5227 bestType = type;
5228 smallest = sum[type];
5229 }
5230 }
5231
5232 prevline = &in[y * linebytes];
5233
5234 /*now fill the out values*/
5235 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5236 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5237 }
5238 }
5239
5240 for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5241 }
5242 else if(strategy == LFS_ENTROPY)
5243 {
5244 float sum[5];
5245 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5246 float smallest = 0;
5247 unsigned type, bestType = 0;
5248 unsigned count[256];
5249
5250 for(type = 0; type != 5; ++type)
5251 {
5252 ucvector_init(&attempt[type]);
5253 if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5254 }
5255
5256 for(y = 0; y != h; ++y)
5257 {
5258 /*try the 5 filter types*/
5259 for(type = 0; type != 5; ++type)
5260 {
5261 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5262 for(x = 0; x != 256; ++x) count[x] = 0;
5263 for(x = 0; x != linebytes; ++x) ++count[attempt[type].data[x]];
5264 ++count[type]; /*the filter type itself is part of the scanline*/
5265 sum[type] = 0;
5266 for(x = 0; x != 256; ++x)
5267 {
5268 float p = count[x] / (float)(linebytes + 1);
5269 sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
5270 }
5271 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5272 if(type == 0 || sum[type] < smallest)
5273 {
5274 bestType = type;
5275 smallest = sum[type];
5276 }
5277 }
5278
5279 prevline = &in[y * linebytes];
5280
5281 /*now fill the out values*/
5282 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5283 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5284 }
5285
5286 for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5287 }
5288 else if(strategy == LFS_PREDEFINED)
5289 {
5290 for(y = 0; y != h; ++y)
5291 {
5292 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5293 size_t inindex = linebytes * y;
5294 unsigned char type = settings->predefined_filters[y];
5295 out[outindex] = type; /*filter type byte*/
5296 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
5297 prevline = &in[inindex];
5298 }
5299 }
5300 else if(strategy == LFS_BRUTE_FORCE)
5301 {
5302 /*brute force filter chooser.
5303 deflate the scanline after every filter attempt to see which one deflates best.
5304 This is very slow and gives only slightly smaller, sometimes even larger, result*/
5305 size_t size[5];
5306 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5307 size_t smallest = 0;
5308 unsigned type = 0, bestType = 0;
5309 unsigned char* dummy;
5310 LodePNGCompressSettings zlibsettings = settings->zlibsettings;
5311 /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5312 to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5313 better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5314 cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5315 zlibsettings.btype = 1;
5316 /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5317 images only, so disable it*/
5318 zlibsettings.custom_zlib = 0;
5319 zlibsettings.custom_deflate = 0;
5320 for(type = 0; type != 5; ++type)
5321 {
5322 ucvector_init(&attempt[type]);
5323 ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/
5324 }
5325 for(y = 0; y != h; ++y) /*try the 5 filter types*/
5326 {
5327 for(type = 0; type != 5; ++type)
5328 {
5329 unsigned testsize = attempt[type].size;
5330 /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5331
5332 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5333 size[type] = 0;
5334 dummy = 0;
5335 zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings);
5336 lodepng_free(dummy);
5337 /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5338 if(type == 0 || size[type] < smallest)
5339 {
5340 bestType = type;
5341 smallest = size[type];
5342 }
5343 }
5344 prevline = &in[y * linebytes];
5345 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5346 for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5347 }
5348 for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5349 }
5350 else return 88; /* unknown filter strategy */
5351
5352 return error;
5353 }
5354
5355 static void addPaddingBits(unsigned char* out, const unsigned char* in,
5356 size_t olinebits, size_t ilinebits, unsigned h)
5357 {
5358 /*The opposite of the removePaddingBits function
5359 olinebits must be >= ilinebits*/
5360 unsigned y;
5361 size_t diff = olinebits - ilinebits;
5362 size_t obp = 0, ibp = 0; /*bit pointers*/
5363 for(y = 0; y != h; ++y)
5364 {
5365 size_t x;
5366 for(x = 0; x < ilinebits; ++x)
5367 {
5368 unsigned char bit = readBitFromReversedStream(&ibp, in);
5369 setBitOfReversedStream(&obp, out, bit);
5370 }
5371 /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5372 "Use of uninitialised value of size ###" warning from valgrind*/
5373 for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
5374 }
5375 }
5376
5377 /*
5378 in: non-interlaced image with size w*h
5379 out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5380 no padding bits between scanlines, but between reduced images so that each
5381 reduced image starts at a byte.
5382 bpp: bits per pixel
5383 there are no padding bits, not between scanlines, not between reduced images
5384 in has the following size in bits: w * h * bpp.
5385 out is possibly bigger due to padding bits between reduced images
5386 NOTE: comments about padding bits are only relevant if bpp < 8
5387 */
5388 static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
5389 {
5390 unsigned passw[7], passh[7];
5391 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5392 unsigned i;
5393
5394 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5395
5396 if(bpp >= 8)
5397 {
5398 for(i = 0; i != 7; ++i)
5399 {
5400 unsigned x, y, b;
5401 size_t bytewidth = bpp / 8;
5402 for(y = 0; y < passh[i]; ++y)
5403 for(x = 0; x < passw[i]; ++x)
5404 {
5405 size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
5406 size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
5407 for(b = 0; b < bytewidth; ++b)
5408 {
5409 out[pixeloutstart + b] = in[pixelinstart + b];
5410 }
5411 }
5412 }
5413 }
5414 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5415 {
5416 for(i = 0; i != 7; ++i)
5417 {
5418 unsigned x, y, b;
5419 unsigned ilinebits = bpp * passw[i];
5420 unsigned olinebits = bpp * w;
5421 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
5422 for(y = 0; y < passh[i]; ++y)
5423 for(x = 0; x < passw[i]; ++x)
5424 {
5425 ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
5426 obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
5427 for(b = 0; b < bpp; ++b)
5428 {
5429 unsigned char bit = readBitFromReversedStream(&ibp, in);
5430 setBitOfReversedStream(&obp, out, bit);
5431 }
5432 }
5433 }
5434 }
5435 }
5436
5437 /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5438 return value is error**/
5439 static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
5440 unsigned w, unsigned h,
5441 const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings)
5442 {
5443 /*
5444 This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5445 *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5446 *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5447 */
5448 unsigned bpp = lodepng_get_bpp(&info_png->color);
5449 unsigned error = 0;
5450
5451 if(info_png->interlace_method == 0)
5452 {
5453 *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5454 *out = (unsigned char*)lodepng_malloc(*outsize);
5455 if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
5456
5457 if(!error)
5458 {
5459 /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5460 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
5461 {
5462 unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8));
5463 if(!padded) error = 83; /*alloc fail*/
5464 if(!error)
5465 {
5466 addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
5467 error = filter(*out, padded, w, h, &info_png->color, settings);
5468 }
5469 lodepng_free(padded);
5470 }
5471 else
5472 {
5473 /*we can immediately filter into the out buffer, no other steps needed*/
5474 error = filter(*out, in, w, h, &info_png->color, settings);
5475 }
5476 }
5477 }
5478 else /*interlace_method is 1 (Adam7)*/
5479 {
5480 unsigned passw[7], passh[7];
5481 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5482 unsigned char* adam7;
5483
5484 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5485
5486 *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5487 *out = (unsigned char*)lodepng_malloc(*outsize);
5488 if(!(*out)) error = 83; /*alloc fail*/
5489
5490 adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
5491 if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
5492
5493 if(!error)
5494 {
5495 unsigned i;
5496
5497 Adam7_interlace(adam7, in, w, h, bpp);
5498 for(i = 0; i != 7; ++i)
5499 {
5500 if(bpp < 8)
5501 {
5502 unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
5503 if(!padded) ERROR_BREAK(83); /*alloc fail*/
5504 addPaddingBits(padded, &adam7[passstart[i]],
5505 ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
5506 error = filter(&(*out)[filter_passstart[i]], padded,
5507 passw[i], passh[i], &info_png->color, settings);
5508 lodepng_free(padded);
5509 }
5510 else
5511 {
5512 error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
5513 passw[i], passh[i], &info_png->color, settings);
5514 }
5515
5516 if(error) break;
5517 }
5518 }
5519
5520 lodepng_free(adam7);
5521 }
5522
5523 return error;
5524 }
5525
5526 /*
5527 palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5528 returns 0 if the palette is opaque,
5529 returns 1 if the palette has a single color with alpha 0 ==> color key
5530 returns 2 if the palette is semi-translucent.
5531 */
5532 static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize)
5533 {
5534 size_t i;
5535 unsigned key = 0;
5536 unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5537 for(i = 0; i != palettesize; ++i)
5538 {
5539 if(!key && palette[4 * i + 3] == 0)
5540 {
5541 r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
5542 key = 1;
5543 i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5544 }
5545 else if(palette[4 * i + 3] != 255) return 2;
5546 /*when key, no opaque RGB may have key's RGB*/
5547 else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
5548 }
5549 return key;
5550 }
5551
5552 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5553 static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
5554 {
5555 unsigned char* inchunk = data;
5556 while((size_t)(inchunk - data) < datasize)
5557 {
5558 CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
5559 out->allocsize = out->size; /*fix the allocsize again*/
5560 inchunk = lodepng_chunk_next(inchunk);
5561 }
5562 return 0;
5563 }
5564 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5565
5566 unsigned lodepng_encode(unsigned char** out, size_t* outsize,
5567 const unsigned char* image, unsigned w, unsigned h,
5568 LodePNGState* state)
5569 {
5570 LodePNGInfo info;
5571 ucvector outv;
5572 unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
5573 size_t datasize = 0;
5574
5575 /*provide some proper output values if error will happen*/
5576 *out = 0;
5577 *outsize = 0;
5578 state->error = 0;
5579
5580 lodepng_info_init(&info);
5581 lodepng_info_copy(&info, &state->info_png);
5582
5583 if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
5584 && (info.color.palettesize == 0 || info.color.palettesize > 256))
5585 {
5586 state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
5587 return state->error;
5588 }
5589
5590 if(state->encoder.auto_convert)
5591 {
5592 state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
5593 }
5594 if(state->error) return state->error;
5595
5596 if(state->encoder.zlibsettings.btype > 2)
5597 {
5598 CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
5599 }
5600 if(state->info_png.interlace_method > 1)
5601 {
5602 CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
5603 }
5604
5605 state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
5606 if(state->error) return state->error; /*error: unexisting color type given*/
5607 state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
5608 if(state->error) return state->error; /*error: unexisting color type given*/
5609
5610 if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
5611 {
5612 unsigned char* converted;
5613 size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
5614
5615 converted = (unsigned char*)lodepng_malloc(size);
5616 if(!converted && size) state->error = 83; /*alloc fail*/
5617 if(!state->error)
5618 {
5619 state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
5620 }
5621 if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
5622 lodepng_free(converted);
5623 }
5624 else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
5625
5626 ucvector_init(&outv);
5627 while(!state->error) /*while only executed once, to break on error*/
5628 {
5629 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5630 size_t i;
5631 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5632 /*write signature and chunks*/
5633 writeSignature(&outv);
5634 /*IHDR*/
5635 addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
5636 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5637 /*unknown chunks between IHDR and PLTE*/
5638 if(info.unknown_chunks_data[0])
5639 {
5640 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
5641 if(state->error) break;
5642 }
5643 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5644 /*PLTE*/
5645 if(info.color.colortype == LCT_PALETTE)
5646 {
5647 addChunk_PLTE(&outv, &info.color);
5648 }
5649 if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA))
5650 {
5651 addChunk_PLTE(&outv, &info.color);
5652 }
5653 /*tRNS*/
5654 if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0)
5655 {
5656 addChunk_tRNS(&outv, &info.color);
5657 }
5658 if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined)
5659 {
5660 addChunk_tRNS(&outv, &info.color);
5661 }
5662 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5663 /*bKGD (must come between PLTE and the IDAt chunks*/
5664 if(info.background_defined) addChunk_bKGD(&outv, &info);
5665 /*pHYs (must come before the IDAT chunks)*/
5666 if(info.phys_defined) addChunk_pHYs(&outv, &info);
5667
5668 /*unknown chunks between PLTE and IDAT*/
5669 if(info.unknown_chunks_data[1])
5670 {
5671 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
5672 if(state->error) break;
5673 }
5674 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5675 /*IDAT (multiple IDAT chunks must be consecutive)*/
5676 state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
5677 if(state->error) break;
5678 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5679 /*tIME*/
5680 if(info.time_defined) addChunk_tIME(&outv, &info.time);
5681 /*tEXt and/or zTXt*/
5682 for(i = 0; i != info.text_num; ++i)
5683 {
5684 if(strlen(info.text_keys[i]) > 79)
5685 {
5686 state->error = 66; /*text chunk too large*/
5687 break;
5688 }
5689 if(strlen(info.text_keys[i]) < 1)
5690 {
5691 state->error = 67; /*text chunk too small*/
5692 break;
5693 }
5694 if(state->encoder.text_compression)
5695 {
5696 addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
5697 }
5698 else
5699 {
5700 addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
5701 }
5702 }
5703 /*LodePNG version id in text chunk*/
5704 if(state->encoder.add_id)
5705 {
5706 unsigned alread_added_id_text = 0;
5707 for(i = 0; i != info.text_num; ++i)
5708 {
5709 if(!strcmp(info.text_keys[i], "LodePNG"))
5710 {
5711 alread_added_id_text = 1;
5712 break;
5713 }
5714 }
5715 if(alread_added_id_text == 0)
5716 {
5717 addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
5718 }
5719 }
5720 /*iTXt*/
5721 for(i = 0; i != info.itext_num; ++i)
5722 {
5723 if(strlen(info.itext_keys[i]) > 79)
5724 {
5725 state->error = 66; /*text chunk too large*/
5726 break;
5727 }
5728 if(strlen(info.itext_keys[i]) < 1)
5729 {
5730 state->error = 67; /*text chunk too small*/
5731 break;
5732 }
5733 addChunk_iTXt(&outv, state->encoder.text_compression,
5734 info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
5735 &state->encoder.zlibsettings);
5736 }
5737
5738 /*unknown chunks between IDAT and IEND*/
5739 if(info.unknown_chunks_data[2])
5740 {
5741 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
5742 if(state->error) break;
5743 }
5744 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5745 addChunk_IEND(&outv);
5746
5747 break; /*this isn't really a while loop; no error happened so break out now!*/
5748 }
5749
5750 lodepng_info_cleanup(&info);
5751 lodepng_free(data);
5752 /*instead of cleaning the vector up, give it to the output*/
5753 *out = outv.data;
5754 *outsize = outv.size;
5755
5756 return state->error;
5757 }
5758
5759 unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
5760 unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
5761 {
5762 unsigned error;
5763 LodePNGState state;
5764 lodepng_state_init(&state);
5765 state.info_raw.colortype = colortype;
5766 state.info_raw.bitdepth = bitdepth;
5767 state.info_png.color.colortype = colortype;
5768 state.info_png.color.bitdepth = bitdepth;
5769 lodepng_encode(out, outsize, image, w, h, &state);
5770 error = state.error;
5771 lodepng_state_cleanup(&state);
5772 return error;
5773 }
5774
5775 unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5776 {
5777 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
5778 }
5779
5780 unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5781 {
5782 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
5783 }
5784
5785 #ifdef LODEPNG_COMPILE_DISK
5786 unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
5787 LodePNGColorType colortype, unsigned bitdepth)
5788 {
5789 unsigned char* buffer;
5790 size_t buffersize;
5791 unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
5792 if(!error) error = lodepng_save_file(buffer, buffersize, filename);
5793 lodepng_free(buffer);
5794 return error;
5795 }
5796
5797 unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5798 {
5799 return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
5800 }
5801
5802 unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5803 {
5804 return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
5805 }
5806 #endif /*LODEPNG_COMPILE_DISK*/
5807
5808 void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
5809 {
5810 lodepng_compress_settings_init(&settings->zlibsettings);
5811 settings->filter_palette_zero = 1;
5812 settings->filter_strategy = LFS_MINSUM;
5813 settings->auto_convert = 1;
5814 settings->force_palette = 0;
5815 settings->predefined_filters = 0;
5816 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5817 settings->add_id = 0;
5818 settings->text_compression = 1;
5819 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5820 }
5821
5822 #endif /*LODEPNG_COMPILE_ENCODER*/
5823 #endif /*LODEPNG_COMPILE_PNG*/
5824
5825 #ifdef LODEPNG_COMPILE_ERROR_TEXT
5826 /*
5827 This returns the description of a numerical error code in English. This is also
5828 the documentation of all the error codes.
5829 */
5830 const char* lodepng_error_text(unsigned code)
5831 {
5832 switch(code)
5833 {
5834 case 0: return "no error, everything went ok";
5835 case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5836 case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
5837 case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5838 case 13: return "problem while processing dynamic deflate block";
5839 case 14: return "problem while processing dynamic deflate block";
5840 case 15: return "problem while processing dynamic deflate block";
5841 case 16: return "unexisting code while processing dynamic deflate block";
5842 case 17: return "end of out buffer memory reached while inflating";
5843 case 18: return "invalid distance code while inflating";
5844 case 19: return "end of out buffer memory reached while inflating";
5845 case 20: return "invalid deflate block BTYPE encountered while decoding";
5846 case 21: return "NLEN is not ones complement of LEN in a deflate block";
5847 /*end of out buffer memory reached while inflating:
5848 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5849 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5850 happen in a normal, well encoded, PNG image.*/
5851 case 22: return "end of out buffer memory reached while inflating";
5852 case 23: return "end of in buffer memory reached while inflating";
5853 case 24: return "invalid FCHECK in zlib header";
5854 case 25: return "invalid compression method in zlib header";
5855 case 26: return "FDICT encountered in zlib header while it's not used for PNG";
5856 case 27: return "PNG file is smaller than a PNG header";
5857 /*Checks the magic file header, the first 8 bytes of the PNG file*/
5858 case 28: return "incorrect PNG signature, it's no PNG or corrupted";
5859 case 29: return "first chunk is not the header chunk";
5860 case 30: return "chunk length too large, chunk broken off at end of file";
5861 case 31: return "illegal PNG color type or bpp";
5862 case 32: return "illegal PNG compression method";
5863 case 33: return "illegal PNG filter method";
5864 case 34: return "illegal PNG interlace method";
5865 case 35: return "chunk length of a chunk is too large or the chunk too small";
5866 case 36: return "illegal PNG filter type encountered";
5867 case 37: return "illegal bit depth for this color type given";
5868 case 38: return "the palette is too big"; /*more than 256 colors*/
5869 case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
5870 case 40: return "tRNS chunk has wrong size for greyscale image";
5871 case 41: return "tRNS chunk has wrong size for RGB image";
5872 case 42: return "tRNS chunk appeared while it was not allowed for this color type";
5873 case 43: return "bKGD chunk has wrong size for palette image";
5874 case 44: return "bKGD chunk has wrong size for greyscale image";
5875 case 45: return "bKGD chunk has wrong size for RGB image";
5876 /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/
5877 case 48: return "empty input or file doesn't exist";
5878 case 49: return "jumped past memory while generating dynamic huffman tree";
5879 case 50: return "jumped past memory while generating dynamic huffman tree";
5880 case 51: return "jumped past memory while inflating huffman block";
5881 case 52: return "jumped past memory while inflating";
5882 case 53: return "size of zlib data too small";
5883 case 54: return "repeat symbol in tree while there was no value symbol yet";
5884 /*jumped past tree while generating huffman tree, this could be when the
5885 tree will have more leaves than symbols after generating it out of the
5886 given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
5887 case 55: return "jumped past tree while generating huffman tree";
5888 case 56: return "given output image colortype or bitdepth not supported for color conversion";
5889 case 57: return "invalid CRC encountered (checking CRC can be disabled)";
5890 case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
5891 case 59: return "requested color conversion not supported";
5892 case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
5893 case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
5894 /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
5895 case 62: return "conversion from color to greyscale not supported";
5896 case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
5897 /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
5898 case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
5899 case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
5900 case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
5901 case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
5902 case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
5903 case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
5904 case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
5905 case 73: return "invalid tIME chunk size";
5906 case 74: return "invalid pHYs chunk size";
5907 /*length could be wrong, or data chopped off*/
5908 case 75: return "no null termination char found while decoding text chunk";
5909 case 76: return "iTXt chunk too short to contain required bytes";
5910 case 77: return "integer overflow in buffer size";
5911 case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
5912 case 79: return "failed to open file for writing";
5913 case 80: return "tried creating a tree of 0 symbols";
5914 case 81: return "lazy matching at pos 0 is impossible";
5915 case 82: return "color conversion to palette requested while a color isn't in palette";
5916 case 83: return "memory allocation failed";
5917 case 84: return "given image too small to contain all pixels to be encoded";
5918 case 86: return "impossible offset in lz77 encoding (internal bug)";
5919 case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
5920 case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
5921 case 89: return "text chunk keyword too short or long: must have size 1-79";
5922 /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
5923 case 90: return "windowsize must be a power of two";
5924 case 91: return "invalid decompressed idat size";
5925 case 92: return "too many pixels, not supported";
5926 case 93: return "zero width or height is invalid";
5927 }
5928 return "unknown error code";
5929 }
5930 #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
5931
5932 /* ////////////////////////////////////////////////////////////////////////// */
5933 /* ////////////////////////////////////////////////////////////////////////// */
5934 /* // C++ Wrapper // */
5935 /* ////////////////////////////////////////////////////////////////////////// */
5936 /* ////////////////////////////////////////////////////////////////////////// */
5937
5938 #ifdef LODEPNG_COMPILE_CPP
5939 namespace lodepng
5940 {
5941
5942 #ifdef LODEPNG_COMPILE_DISK
5943 void load_file(std::vector<unsigned char>& buffer, const std::string& filename)
5944 {
5945 std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
5946
5947 /*get filesize*/
5948 std::streamsize size = 0;
5949 if(file.seekg(0, std::ios::end).good()) size = file.tellg();
5950 if(file.seekg(0, std::ios::beg).good()) size -= file.tellg();
5951
5952 /*read contents of the file into the vector*/
5953 buffer.resize(size_t(size));
5954 if(size > 0) file.read((char*)(&buffer[0]), size);
5955 }
5956
5957 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
5958 unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename)
5959 {
5960 std::ofstream file(filename.c_str(), std::ios::out|std::ios::binary);
5961 if(!file) return 79;
5962 file.write(buffer.empty() ? 0 : (char*)&buffer[0], std::streamsize(buffer.size()));
5963 return 0;
5964 }
5965 #endif /* LODEPNG_COMPILE_DISK */
5966
5967 #ifdef LODEPNG_COMPILE_ZLIB
5968 #ifdef LODEPNG_COMPILE_DECODER
5969 unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
5970 const LodePNGDecompressSettings& settings)
5971 {
5972 unsigned char* buffer = 0;
5973 size_t buffersize = 0;
5974 unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
5975 if(buffer)
5976 {
5977 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
5978 lodepng_free(buffer);
5979 }
5980 return error;
5981 }
5982
5983 unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
5984 const LodePNGDecompressSettings& settings)
5985 {
5986 return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
5987 }
5988 #endif /* LODEPNG_COMPILE_DECODER */
5989
5990 #ifdef LODEPNG_COMPILE_ENCODER
5991 unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
5992 const LodePNGCompressSettings& settings)
5993 {
5994 unsigned char* buffer = 0;
5995 size_t buffersize = 0;
5996 unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
5997 if(buffer)
5998 {
5999 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6000 lodepng_free(buffer);
6001 }
6002 return error;
6003 }
6004
6005 unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
6006 const LodePNGCompressSettings& settings)
6007 {
6008 return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
6009 }
6010 #endif /* LODEPNG_COMPILE_ENCODER */
6011 #endif /* LODEPNG_COMPILE_ZLIB */
6012
6013
6014 #ifdef LODEPNG_COMPILE_PNG
6015
6016 State::State()
6017 {
6018 lodepng_state_init(this);
6019 }
6020
6021 State::State(const State& other)
6022 {
6023 lodepng_state_init(this);
6024 lodepng_state_copy(this, &other);
6025 }
6026
6027 State::~State()
6028 {
6029 lodepng_state_cleanup(this);
6030 }
6031
6032 State& State::operator=(const State& other)
6033 {
6034 lodepng_state_copy(this, &other);
6035 return *this;
6036 }
6037
6038 #ifdef LODEPNG_COMPILE_DECODER
6039
6040 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
6041 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
6042 {
6043 unsigned char* buffer;
6044 unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
6045 if(buffer && !error)
6046 {
6047 State state;
6048 state.info_raw.colortype = colortype;
6049 state.info_raw.bitdepth = bitdepth;
6050 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6051 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6052 lodepng_free(buffer);
6053 }
6054 return error;
6055 }
6056
6057 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6058 const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth)
6059 {
6060 return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
6061 }
6062
6063 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6064 State& state,
6065 const unsigned char* in, size_t insize)
6066 {
6067 unsigned char* buffer = NULL;
6068 unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
6069 if(buffer && !error)
6070 {
6071 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6072 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6073 }
6074 lodepng_free(buffer);
6075 return error;
6076 }
6077
6078 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6079 State& state,
6080 const std::vector<unsigned char>& in)
6081 {
6082 return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
6083 }
6084
6085 #ifdef LODEPNG_COMPILE_DISK
6086 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
6087 LodePNGColorType colortype, unsigned bitdepth)
6088 {
6089 std::vector<unsigned char> buffer;
6090 load_file(buffer, filename);
6091 return decode(out, w, h, buffer, colortype, bitdepth);
6092 }
6093 #endif /* LODEPNG_COMPILE_DECODER */
6094 #endif /* LODEPNG_COMPILE_DISK */
6095
6096 #ifdef LODEPNG_COMPILE_ENCODER
6097 unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
6098 LodePNGColorType colortype, unsigned bitdepth)
6099 {
6100 unsigned char* buffer;
6101 size_t buffersize;
6102 unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
6103 if(buffer)
6104 {
6105 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6106 lodepng_free(buffer);
6107 }
6108 return error;
6109 }
6110
6111 unsigned encode(std::vector<unsigned char>& out,
6112 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6113 LodePNGColorType colortype, unsigned bitdepth)
6114 {
6115 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6116 return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6117 }
6118
6119 unsigned encode(std::vector<unsigned char>& out,
6120 const unsigned char* in, unsigned w, unsigned h,
6121 State& state)
6122 {
6123 unsigned char* buffer;
6124 size_t buffersize;
6125 unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
6126 if(buffer)
6127 {
6128 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6129 lodepng_free(buffer);
6130 }
6131 return error;
6132 }
6133
6134 unsigned encode(std::vector<unsigned char>& out,
6135 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6136 State& state)
6137 {
6138 if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
6139 return encode(out, in.empty() ? 0 : &in[0], w, h, state);
6140 }
6141
6142 #ifdef LODEPNG_COMPILE_DISK
6143 unsigned encode(const std::string& filename,
6144 const unsigned char* in, unsigned w, unsigned h,
6145 LodePNGColorType colortype, unsigned bitdepth)
6146 {
6147 std::vector<unsigned char> buffer;
6148 unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
6149 if(!error) error = save_file(buffer, filename);
6150 return error;
6151 }
6152
6153 unsigned encode(const std::string& filename,
6154 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6155 LodePNGColorType colortype, unsigned bitdepth)
6156 {
6157 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6158 return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6159 }
6160 #endif /* LODEPNG_COMPILE_DISK */
6161 #endif /* LODEPNG_COMPILE_ENCODER */
6162 #endif /* LODEPNG_COMPILE_PNG */
6163 } /* namespace lodepng */
6164 #endif /*LODEPNG_COMPILE_CPP*/