stb_image: update stb_image.h to v2.02
[fbvis.git] / lodepng.c
bloba4c13b45987c2905978500e587d65034ee19fb7f
1 /*
2 LodePNG version 20121216
4 Copyright (c) 2005-2012 Lode Vandevenne
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.
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:
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.
19 2. Altered source versions must be plainly marked as such, and must not be
20 misrepresented as being the original software.
22 3. This notice may not be removed or altered from any source
23 distribution.
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.
31 #include "lodepng.h"
33 #include <stdio.h>
34 #include <stdlib.h>
36 #ifdef LODEPNG_COMPILE_CPP
37 #include <fstream>
38 #endif /*LODEPNG_COMPILE_CPP*/
40 #define VERSION_STRING "20121216"
43 This source file is built up in the following large parts. The code sections
44 with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
45 -Tools for C and common code for PNG and Zlib
46 -C Code for Zlib (huffman, deflate, ...)
47 -C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
48 -The C++ wrapper around all of the above
51 /*The malloc, realloc and free functions defined here with "my" in front of the
52 name, so that you can easily change them to others related to your platform in
53 this one location if needed. Everything else in the code calls these.*/
55 static void* mymalloc(size_t size)
57 return malloc(size);
60 static void* myrealloc(void* ptr, size_t new_size)
62 return realloc(ptr, new_size);
65 static void myfree(void* ptr)
67 free(ptr);
70 /* ////////////////////////////////////////////////////////////////////////// */
71 /* ////////////////////////////////////////////////////////////////////////// */
72 /* // Tools for C, and common code for PNG and Zlib. // */
73 /* ////////////////////////////////////////////////////////////////////////// */
74 /* ////////////////////////////////////////////////////////////////////////// */
77 Often in case of an error a value is assigned to a variable and then it breaks
78 out of a loop (to go to the cleanup phase of a function). This macro does that.
79 It makes the error handling code shorter and more readable.
81 Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
83 #define CERROR_BREAK(errorvar, code)\
85 errorvar = code;\
86 break;\
89 /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
90 #define ERROR_BREAK(code) CERROR_BREAK(error, code)
92 /*Set error var to the error code, and return it.*/
93 #define CERROR_RETURN_ERROR(errorvar, code)\
95 errorvar = code;\
96 return code;\
99 /*Try the code, if it returns error, also return the error.*/
100 #define CERROR_TRY_RETURN(call)\
102 unsigned error = call;\
103 if(error) return error;\
107 About uivector, ucvector and string:
108 -All of them wrap dynamic arrays or text strings in a similar way.
109 -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
110 -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
111 -They're not used in the interface, only internally in this file as static functions.
112 -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
115 #ifdef LODEPNG_COMPILE_ZLIB
116 /*dynamic vector of unsigned ints*/
117 typedef struct uivector
119 unsigned* data;
120 size_t size; /*size in number of unsigned longs*/
121 size_t allocsize; /*allocated size in bytes*/
122 } uivector;
124 static void uivector_cleanup(void* p)
126 ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
127 myfree(((uivector*)p)->data);
128 ((uivector*)p)->data = NULL;
131 /*returns 1 if success, 0 if failure ==> nothing done*/
132 static unsigned uivector_resize(uivector* p, size_t size)
134 if(size * sizeof(unsigned) > p->allocsize)
136 size_t newsize = size * sizeof(unsigned) * 2;
137 void* data = myrealloc(p->data, newsize);
138 if(data)
140 p->allocsize = newsize;
141 p->data = (unsigned*)data;
142 p->size = size;
144 else return 0;
146 else p->size = size;
147 return 1;
150 /*resize and give all new elements the value*/
151 static unsigned uivector_resizev(uivector* p, size_t size, unsigned value)
153 size_t oldsize = p->size, i;
154 if(!uivector_resize(p, size)) return 0;
155 for(i = oldsize; i < size; i++) p->data[i] = value;
156 return 1;
159 static void uivector_init(uivector* p)
161 p->data = NULL;
162 p->size = p->allocsize = 0;
165 #ifdef LODEPNG_COMPILE_ENCODER
166 /*returns 1 if success, 0 if failure ==> nothing done*/
167 static unsigned uivector_push_back(uivector* p, unsigned c)
169 if(!uivector_resize(p, p->size + 1)) return 0;
170 p->data[p->size - 1] = c;
171 return 1;
174 /*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/
175 static unsigned uivector_copy(uivector* p, const uivector* q)
177 size_t i;
178 if(!uivector_resize(p, q->size)) return 0;
179 for(i = 0; i < q->size; i++) p->data[i] = q->data[i];
180 return 1;
183 static void uivector_swap(uivector* p, uivector* q)
185 size_t tmp;
186 unsigned* tmpp;
187 tmp = p->size; p->size = q->size; q->size = tmp;
188 tmp = p->allocsize; p->allocsize = q->allocsize; q->allocsize = tmp;
189 tmpp = p->data; p->data = q->data; q->data = tmpp;
191 #endif /*LODEPNG_COMPILE_ENCODER*/
192 #endif /*LODEPNG_COMPILE_ZLIB*/
194 /* /////////////////////////////////////////////////////////////////////////// */
196 /*dynamic vector of unsigned chars*/
197 typedef struct ucvector
199 unsigned char* data;
200 size_t size; /*used size*/
201 size_t allocsize; /*allocated size*/
202 } ucvector;
204 /*returns 1 if success, 0 if failure ==> nothing done*/
205 static unsigned ucvector_resize(ucvector* p, size_t size)
207 if(size * sizeof(unsigned char) > p->allocsize)
209 size_t newsize = size * sizeof(unsigned char) * 2;
210 void* data = myrealloc(p->data, newsize);
211 if(data)
213 p->allocsize = newsize;
214 p->data = (unsigned char*)data;
215 p->size = size;
217 else return 0; /*error: not enough memory*/
219 else p->size = size;
220 return 1;
223 #ifdef LODEPNG_COMPILE_PNG
225 static void ucvector_cleanup(void* p)
227 ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
228 myfree(((ucvector*)p)->data);
229 ((ucvector*)p)->data = NULL;
232 static void ucvector_init(ucvector* p)
234 p->data = NULL;
235 p->size = p->allocsize = 0;
238 #ifdef LODEPNG_COMPILE_DECODER
239 /*resize and give all new elements the value*/
240 static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value)
242 size_t oldsize = p->size, i;
243 if(!ucvector_resize(p, size)) return 0;
244 for(i = oldsize; i < size; i++) p->data[i] = value;
245 return 1;
247 #endif /*LODEPNG_COMPILE_DECODER*/
248 #endif /*LODEPNG_COMPILE_PNG*/
250 #ifdef LODEPNG_COMPILE_ZLIB
251 /*you can both convert from vector to buffer&size and vica versa. If you use
252 init_buffer to take over a buffer and size, it is not needed to use cleanup*/
253 static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size)
255 p->data = buffer;
256 p->allocsize = p->size = size;
258 #endif /*LODEPNG_COMPILE_ZLIB*/
260 #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
261 /*returns 1 if success, 0 if failure ==> nothing done*/
262 static unsigned ucvector_push_back(ucvector* p, unsigned char c)
264 if(!ucvector_resize(p, p->size + 1)) return 0;
265 p->data[p->size - 1] = c;
266 return 1;
268 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
271 /* ////////////////////////////////////////////////////////////////////////// */
273 #ifdef LODEPNG_COMPILE_PNG
274 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
275 /*returns 1 if success, 0 if failure ==> nothing done*/
276 static unsigned string_resize(char** out, size_t size)
278 char* data = (char*)myrealloc(*out, size + 1);
279 if(data)
281 data[size] = 0; /*null termination char*/
282 *out = data;
284 return data != 0;
287 /*init a {char*, size_t} pair for use as string*/
288 static void string_init(char** out)
290 *out = NULL;
291 string_resize(out, 0);
294 /*free the above pair again*/
295 static void string_cleanup(char** out)
297 myfree(*out);
298 *out = NULL;
301 static void string_set(char** out, const char* in)
303 size_t insize = strlen(in), i = 0;
304 if(string_resize(out, insize))
306 for(i = 0; i < insize; i++)
308 (*out)[i] = in[i];
312 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
313 #endif /*LODEPNG_COMPILE_PNG*/
315 /* ////////////////////////////////////////////////////////////////////////// */
317 unsigned lodepng_read32bitInt(const unsigned char* buffer)
319 return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
322 #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
323 /*buffer must have at least 4 allocated bytes available*/
324 static void lodepng_set32bitInt(unsigned char* buffer, unsigned value)
326 buffer[0] = (unsigned char)((value >> 24) & 0xff);
327 buffer[1] = (unsigned char)((value >> 16) & 0xff);
328 buffer[2] = (unsigned char)((value >> 8) & 0xff);
329 buffer[3] = (unsigned char)((value ) & 0xff);
331 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
333 #ifdef LODEPNG_COMPILE_ENCODER
334 static void lodepng_add32bitInt(ucvector* buffer, unsigned value)
336 ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
337 lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
339 #endif /*LODEPNG_COMPILE_ENCODER*/
341 /* ////////////////////////////////////////////////////////////////////////// */
342 /* / File IO / */
343 /* ////////////////////////////////////////////////////////////////////////// */
345 #ifdef LODEPNG_COMPILE_DISK
347 unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename)
349 FILE* file;
350 long size;
352 /*provide some proper output values if error will happen*/
353 *out = 0;
354 *outsize = 0;
356 file = fopen(filename, "rb");
357 if(!file) return 78;
359 /*get filesize:*/
360 fseek(file , 0 , SEEK_END);
361 size = ftell(file);
362 rewind(file);
364 /*read contents of the file into the vector*/
365 *outsize = 0;
366 *out = (unsigned char*)mymalloc((size_t)size);
367 if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file);
369 fclose(file);
370 if(!(*out) && size) return 83; /*the above malloc failed*/
371 return 0;
374 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
375 unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename)
377 FILE* file;
378 file = fopen(filename, "wb" );
379 if(!file) return 79;
380 fwrite((char*)buffer , 1 , buffersize, file);
381 fclose(file);
382 return 0;
385 #endif /*LODEPNG_COMPILE_DISK*/
387 /* ////////////////////////////////////////////////////////////////////////// */
388 /* ////////////////////////////////////////////////////////////////////////// */
389 /* // End of common code and tools. Begin of Zlib related code. // */
390 /* ////////////////////////////////////////////////////////////////////////// */
391 /* ////////////////////////////////////////////////////////////////////////// */
393 #ifdef LODEPNG_COMPILE_ZLIB
394 #ifdef LODEPNG_COMPILE_ENCODER
395 /*TODO: this ignores potential out of memory errors*/
396 static void addBitToStream(size_t* bitpointer, ucvector* bitstream, unsigned char bit)
398 /*add a new byte at the end*/
399 if((*bitpointer) % 8 == 0) ucvector_push_back(bitstream, (unsigned char)0);
400 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
401 (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));
402 (*bitpointer)++;
405 static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
407 size_t i;
408 for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
411 static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
413 size_t i;
414 for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
416 #endif /*LODEPNG_COMPILE_ENCODER*/
418 #ifdef LODEPNG_COMPILE_DECODER
420 #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
422 static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream)
424 unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
425 (*bitpointer)++;
426 return result;
429 static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
431 unsigned result = 0, i;
432 for(i = 0; i < nbits; i++)
434 result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
435 (*bitpointer)++;
437 return result;
439 #endif /*LODEPNG_COMPILE_DECODER*/
441 /* ////////////////////////////////////////////////////////////////////////// */
442 /* / Deflate - Huffman / */
443 /* ////////////////////////////////////////////////////////////////////////// */
445 #define FIRST_LENGTH_CODE_INDEX 257
446 #define LAST_LENGTH_CODE_INDEX 285
447 /*256 literals, the end code, some length codes, and 2 unused codes*/
448 #define NUM_DEFLATE_CODE_SYMBOLS 288
449 /*the distance codes have their own symbols, 30 used, 2 unused*/
450 #define NUM_DISTANCE_SYMBOLS 32
451 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
452 #define NUM_CODE_LENGTH_CODES 19
454 /*the base lengths represented by codes 257-285*/
455 static const unsigned LENGTHBASE[29]
456 = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
457 67, 83, 99, 115, 131, 163, 195, 227, 258};
459 /*the extra bits used by codes 257-285 (added to base length)*/
460 static const unsigned LENGTHEXTRA[29]
461 = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
462 4, 4, 4, 4, 5, 5, 5, 5, 0};
464 /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
465 static const unsigned DISTANCEBASE[30]
466 = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
467 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
469 /*the extra bits of backwards distances (added to base)*/
470 static const unsigned DISTANCEEXTRA[30]
471 = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
472 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
474 /*the order in which "code length alphabet code lengths" are stored, out of this
475 the huffman tree of the dynamic huffman tree lengths is generated*/
476 static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
477 = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
479 /* ////////////////////////////////////////////////////////////////////////// */
482 Huffman tree struct, containing multiple representations of the tree
484 typedef struct HuffmanTree
486 unsigned* tree2d;
487 unsigned* tree1d;
488 unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
489 unsigned maxbitlen; /*maximum number of bits a single code can get*/
490 unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
491 } HuffmanTree;
493 /*function used for debug purposes to draw the tree in ascii art with C++*/
494 /*#include <iostream>
495 static void HuffmanTree_draw(HuffmanTree* tree)
497 std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
498 for(size_t i = 0; i < tree->tree1d.size; i++)
500 if(tree->lengths.data[i])
501 std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
503 std::cout << std::endl;
506 static void HuffmanTree_init(HuffmanTree* tree)
508 tree->tree2d = 0;
509 tree->tree1d = 0;
510 tree->lengths = 0;
513 static void HuffmanTree_cleanup(HuffmanTree* tree)
515 myfree(tree->tree2d);
516 myfree(tree->tree1d);
517 myfree(tree->lengths);
520 /*the tree representation used by the decoder. return value is error*/
521 static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
523 unsigned nodefilled = 0; /*up to which node it is filled*/
524 unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
525 unsigned n, i;
527 tree->tree2d = (unsigned*)mymalloc(tree->numcodes * 2 * sizeof(unsigned));
528 if(!tree->tree2d) return 83; /*alloc fail*/
531 convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
532 uninited, a value >= numcodes is an address to another bit, a value < numcodes
533 is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
534 many columns as codes - 1.
535 A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
536 Here, the internal nodes are stored (what their 0 and 1 option point to).
537 There is only memory for such good tree currently, if there are more nodes
538 (due to too long length codes), error 55 will happen
540 for(n = 0; n < tree->numcodes * 2; n++)
542 tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
545 for(n = 0; n < tree->numcodes; n++) /*the codes*/
547 for(i = 0; i < tree->lengths[n]; i++) /*the bits for this code*/
549 unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
550 if(treepos > tree->numcodes - 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/
551 if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
553 if(i + 1 == tree->lengths[n]) /*last bit*/
555 tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
556 treepos = 0;
558 else
560 /*put address of the next step in here, first that address has to be found of course
561 (it's just nodefilled + 1)...*/
562 nodefilled++;
563 /*addresses encoded with numcodes added to it*/
564 tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
565 treepos = nodefilled;
568 else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
572 for(n = 0; n < tree->numcodes * 2; n++)
574 if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
577 return 0;
581 Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
582 numcodes, lengths and maxbitlen must already be filled in correctly. return
583 value is error.
585 static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
587 uivector blcount;
588 uivector nextcode;
589 unsigned bits, n, error = 0;
591 uivector_init(&blcount);
592 uivector_init(&nextcode);
594 tree->tree1d = (unsigned*)mymalloc(tree->numcodes * sizeof(unsigned));
595 if(!tree->tree1d) error = 83; /*alloc fail*/
597 if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
598 || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
599 error = 83; /*alloc fail*/
601 if(!error)
603 /*step 1: count number of instances of each code length*/
604 for(bits = 0; bits < tree->numcodes; bits++) blcount.data[tree->lengths[bits]]++;
605 /*step 2: generate the nextcode values*/
606 for(bits = 1; bits <= tree->maxbitlen; bits++)
608 nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
610 /*step 3: generate all the codes*/
611 for(n = 0; n < tree->numcodes; n++)
613 if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
617 uivector_cleanup(&blcount);
618 uivector_cleanup(&nextcode);
620 if(!error) return HuffmanTree_make2DTree(tree);
621 else return error;
625 given the code lengths (as stored in the PNG file), generate the tree as defined
626 by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
627 return value is error.
629 static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
630 size_t numcodes, unsigned maxbitlen)
632 unsigned i;
633 tree->lengths = (unsigned*)mymalloc(numcodes * sizeof(unsigned));
634 if(!tree->lengths) return 83; /*alloc fail*/
635 for(i = 0; i < numcodes; i++) tree->lengths[i] = bitlen[i];
636 tree->numcodes = (unsigned)numcodes; /*number of symbols*/
637 tree->maxbitlen = maxbitlen;
638 return HuffmanTree_makeFromLengths2(tree);
641 #ifdef LODEPNG_COMPILE_ENCODER
644 A coin, this is the terminology used for the package-merge algorithm and the
645 coin collector's problem. This is used to generate the huffman tree.
646 A coin can be multiple coins (when they're merged)
648 typedef struct Coin
650 uivector symbols;
651 float weight; /*the sum of all weights in this coin*/
652 } Coin;
654 static void coin_init(Coin* c)
656 uivector_init(&c->symbols);
659 /*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/
660 static void coin_cleanup(void* c)
662 uivector_cleanup(&((Coin*)c)->symbols);
665 static void coin_copy(Coin* c1, const Coin* c2)
667 c1->weight = c2->weight;
668 uivector_copy(&c1->symbols, &c2->symbols);
671 static void add_coins(Coin* c1, const Coin* c2)
673 size_t i;
674 for(i = 0; i < c2->symbols.size; i++) uivector_push_back(&c1->symbols, c2->symbols.data[i]);
675 c1->weight += c2->weight;
678 static void init_coins(Coin* coins, size_t num)
680 size_t i;
681 for(i = 0; i < num; i++) coin_init(&coins[i]);
684 static void cleanup_coins(Coin* coins, size_t num)
686 size_t i;
687 for(i = 0; i < num; i++) coin_cleanup(&coins[i]);
691 This uses a simple combsort to sort the data. This function is not critical for
692 overall encoding speed and the data amount isn't that large.
694 static void sort_coins(Coin* data, size_t amount)
696 size_t gap = amount;
697 unsigned char swapped = 0;
698 while((gap > 1) || swapped)
700 size_t i;
701 gap = (gap * 10) / 13; /*shrink factor 1.3*/
702 if(gap == 9 || gap == 10) gap = 11; /*combsort11*/
703 if(gap < 1) gap = 1;
704 swapped = 0;
705 for(i = 0; i < amount - gap; i++)
707 size_t j = i + gap;
708 if(data[j].weight < data[i].weight)
710 float temp = data[j].weight; data[j].weight = data[i].weight; data[i].weight = temp;
711 uivector_swap(&data[i].symbols, &data[j].symbols);
712 swapped = 1;
718 static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum)
720 unsigned i;
721 unsigned j = 0; /*index of present symbols*/
722 for(i = 0; i < numcodes; i++)
724 if(frequencies[i] != 0) /*only include symbols that are present*/
726 coins[j].weight = frequencies[i] / (float)sum;
727 uivector_push_back(&coins[j].symbols, i);
728 j++;
731 return 0;
734 unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
735 size_t numcodes, unsigned maxbitlen)
737 unsigned i, j;
738 size_t sum = 0, numpresent = 0;
739 unsigned error = 0;
740 Coin* coins; /*the coins of the currently calculated row*/
741 Coin* prev_row; /*the previous row of coins*/
742 unsigned numcoins;
743 unsigned coinmem;
745 if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
747 for(i = 0; i < numcodes; i++)
749 if(frequencies[i] > 0)
751 numpresent++;
752 sum += frequencies[i];
756 for(i = 0; i < numcodes; i++) lengths[i] = 0;
758 /*ensure at least two present symbols. There should be at least one symbol
759 according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To
760 make these work as well ensure there are at least two symbols. The
761 Package-Merge code below also doesn't work correctly if there's only one
762 symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
763 if(numpresent == 0)
765 lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
767 else if(numpresent == 1)
769 for(i = 0; i < numcodes; i++)
771 if(frequencies[i])
773 lengths[i] = 1;
774 lengths[i == 0 ? 1 : 0] = 1;
775 break;
779 else
781 /*Package-Merge algorithm represented by coin collector's problem
782 For every symbol, maxbitlen coins will be created*/
784 coinmem = numpresent * 2; /*max amount of coins needed with the current algo*/
785 coins = (Coin*)mymalloc(sizeof(Coin) * coinmem);
786 prev_row = (Coin*)mymalloc(sizeof(Coin) * coinmem);
787 if(!coins || !prev_row) return 83; /*alloc fail*/
788 init_coins(coins, coinmem);
789 init_coins(prev_row, coinmem);
791 /*first row, lowest denominator*/
792 error = append_symbol_coins(coins, frequencies, numcodes, sum);
793 numcoins = numpresent;
794 sort_coins(coins, numcoins);
795 if(!error)
797 unsigned numprev = 0;
798 for(j = 1; j <= maxbitlen && !error; j++) /*each of the remaining rows*/
800 unsigned tempnum;
801 Coin* tempcoins;
802 /*swap prev_row and coins, and their amounts*/
803 tempcoins = prev_row; prev_row = coins; coins = tempcoins;
804 tempnum = numprev; numprev = numcoins; numcoins = tempnum;
806 cleanup_coins(coins, numcoins);
807 init_coins(coins, numcoins);
809 numcoins = 0;
811 /*fill in the merged coins of the previous row*/
812 for(i = 0; i + 1 < numprev; i += 2)
814 /*merge prev_row[i] and prev_row[i + 1] into new coin*/
815 Coin* coin = &coins[numcoins++];
816 coin_copy(coin, &prev_row[i]);
817 add_coins(coin, &prev_row[i + 1]);
819 /*fill in all the original symbols again*/
820 if(j < maxbitlen)
822 error = append_symbol_coins(coins + numcoins, frequencies, numcodes, sum);
823 numcoins += numpresent;
825 sort_coins(coins, numcoins);
829 if(!error)
831 /*calculate the lenghts of each symbol, as the amount of times a coin of each symbol is used*/
832 for(i = 0; i < numpresent - 1; i++)
834 Coin* coin = &coins[i];
835 for(j = 0; j < coin->symbols.size; j++) lengths[coin->symbols.data[j]]++;
839 cleanup_coins(coins, coinmem);
840 myfree(coins);
841 cleanup_coins(prev_row, coinmem);
842 myfree(prev_row);
845 return error;
848 /*Create the Huffman tree given the symbol frequencies*/
849 static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
850 size_t mincodes, size_t numcodes, unsigned maxbitlen)
852 unsigned error = 0;
853 while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
854 tree->maxbitlen = maxbitlen;
855 tree->numcodes = (unsigned)numcodes; /*number of symbols*/
856 tree->lengths = (unsigned*)myrealloc(tree->lengths, numcodes * sizeof(unsigned));
857 if(!tree->lengths) return 83; /*alloc fail*/
858 /*initialize all lengths to 0*/
859 memset(tree->lengths, 0, numcodes * sizeof(unsigned));
861 error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
862 if(!error) error = HuffmanTree_makeFromLengths2(tree);
863 return error;
866 static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
868 return tree->tree1d[index];
871 static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index)
873 return tree->lengths[index];
875 #endif /*LODEPNG_COMPILE_ENCODER*/
877 /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
878 static unsigned generateFixedLitLenTree(HuffmanTree* tree)
880 unsigned i, error = 0;
881 unsigned* bitlen = (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
882 if(!bitlen) return 83; /*alloc fail*/
884 /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
885 for(i = 0; i <= 143; i++) bitlen[i] = 8;
886 for(i = 144; i <= 255; i++) bitlen[i] = 9;
887 for(i = 256; i <= 279; i++) bitlen[i] = 7;
888 for(i = 280; i <= 287; i++) bitlen[i] = 8;
890 error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
892 myfree(bitlen);
893 return error;
896 /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
897 static unsigned generateFixedDistanceTree(HuffmanTree* tree)
899 unsigned i, error = 0;
900 unsigned* bitlen = (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
901 if(!bitlen) return 83; /*alloc fail*/
903 /*there are 32 distance codes, but 30-31 are unused*/
904 for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen[i] = 5;
905 error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
907 myfree(bitlen);
908 return error;
911 #ifdef LODEPNG_COMPILE_DECODER
914 returns the code, or (unsigned)(-1) if error happened
915 inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
917 static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
918 const HuffmanTree* codetree, size_t inbitlength)
920 unsigned treepos = 0, ct;
921 for(;;)
923 if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
925 decode the symbol from the tree. The "readBitFromStream" code is inlined in
926 the expression below because this is the biggest bottleneck while decoding
928 ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
929 (*bp)++;
930 if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
931 else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
933 if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
936 #endif /*LODEPNG_COMPILE_DECODER*/
938 #ifdef LODEPNG_COMPILE_DECODER
940 /* ////////////////////////////////////////////////////////////////////////// */
941 /* / Inflator (Decompressor) / */
942 /* ////////////////////////////////////////////////////////////////////////// */
944 /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
945 static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
947 /*TODO: check for out of memory errors*/
948 generateFixedLitLenTree(tree_ll);
949 generateFixedDistanceTree(tree_d);
952 /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
953 static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
954 const unsigned char* in, size_t* bp, size_t inlength)
956 /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
957 unsigned error = 0;
958 unsigned n, HLIT, HDIST, HCLEN, i;
959 size_t inbitlength = inlength * 8;
961 /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
962 unsigned* bitlen_ll = 0; /*lit,len code lengths*/
963 unsigned* bitlen_d = 0; /*dist code lengths*/
964 /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
965 unsigned* bitlen_cl = 0;
966 HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
968 if((*bp) >> 3 >= inlength - 2) return 49; /*error: the bit pointer is or will go past the memory*/
970 /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
971 HLIT = readBitsFromStream(bp, in, 5) + 257;
972 /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
973 HDIST = readBitsFromStream(bp, in, 5) + 1;
974 /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
975 HCLEN = readBitsFromStream(bp, in, 4) + 4;
977 HuffmanTree_init(&tree_cl);
979 while(!error)
981 /*read the code length codes out of 3 * (amount of code length codes) bits*/
983 bitlen_cl = (unsigned*)mymalloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
984 if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
986 for(i = 0; i < NUM_CODE_LENGTH_CODES; i++)
988 if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
989 else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
992 error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
993 if(error) break;
995 /*now we can use this tree to read the lengths for the tree that this function will return*/
996 bitlen_ll = (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
997 bitlen_d = (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
998 if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
999 for(i = 0; i < NUM_DEFLATE_CODE_SYMBOLS; i++) bitlen_ll[i] = 0;
1000 for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen_d[i] = 0;
1002 /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1003 i = 0;
1004 while(i < HLIT + HDIST)
1006 unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
1007 if(code <= 15) /*a length code*/
1009 if(i < HLIT) bitlen_ll[i] = code;
1010 else bitlen_d[i - HLIT] = code;
1011 i++;
1013 else if(code == 16) /*repeat previous*/
1015 unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1016 unsigned value; /*set value to the previous code*/
1018 if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1019 if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1021 replength += readBitsFromStream(bp, in, 2);
1023 if(i < HLIT + 1) value = bitlen_ll[i - 1];
1024 else value = bitlen_d[i - HLIT - 1];
1025 /*repeat this value in the next lengths*/
1026 for(n = 0; n < replength; n++)
1028 if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1029 if(i < HLIT) bitlen_ll[i] = value;
1030 else bitlen_d[i - HLIT] = value;
1031 i++;
1034 else if(code == 17) /*repeat "0" 3-10 times*/
1036 unsigned replength = 3; /*read in the bits that indicate repeat length*/
1037 if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1039 replength += readBitsFromStream(bp, in, 3);
1041 /*repeat this value in the next lengths*/
1042 for(n = 0; n < replength; n++)
1044 if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1046 if(i < HLIT) bitlen_ll[i] = 0;
1047 else bitlen_d[i - HLIT] = 0;
1048 i++;
1051 else if(code == 18) /*repeat "0" 11-138 times*/
1053 unsigned replength = 11; /*read in the bits that indicate repeat length*/
1054 if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1056 replength += readBitsFromStream(bp, in, 7);
1058 /*repeat this value in the next lengths*/
1059 for(n = 0; n < replength; n++)
1061 if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1063 if(i < HLIT) bitlen_ll[i] = 0;
1064 else bitlen_d[i - HLIT] = 0;
1065 i++;
1068 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1070 if(code == (unsigned)(-1))
1072 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1073 (10=no endcode, 11=wrong jump outside of tree)*/
1074 error = (*bp) > inbitlength ? 10 : 11;
1076 else error = 16; /*unexisting code, this can never happen*/
1077 break;
1080 if(error) break;
1082 if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1084 /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1085 error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
1086 if(error) break;
1087 error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
1089 break; /*end of error-while*/
1092 myfree(bitlen_cl);
1093 myfree(bitlen_ll);
1094 myfree(bitlen_d);
1095 HuffmanTree_cleanup(&tree_cl);
1097 return error;
1100 /*inflate a block with dynamic of fixed Huffman tree*/
1101 static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
1102 size_t* pos, size_t inlength, unsigned btype)
1104 unsigned error = 0;
1105 HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
1106 HuffmanTree tree_d; /*the huffman tree for distance codes*/
1107 size_t inbitlength = inlength * 8;
1109 HuffmanTree_init(&tree_ll);
1110 HuffmanTree_init(&tree_d);
1112 if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
1113 else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
1115 while(!error) /*decode all symbols until end reached, breaks at end code*/
1117 /*code_ll is literal, length or end code*/
1118 unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
1119 if(code_ll <= 255) /*literal symbol*/
1121 if((*pos) >= out->size)
1123 /*reserve more room at once*/
1124 if(!ucvector_resize(out, ((*pos) + 1) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1126 out->data[(*pos)] = (unsigned char)(code_ll);
1127 (*pos)++;
1129 else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
1131 unsigned code_d, distance;
1132 unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
1133 size_t start, forward, backward, length;
1135 /*part 1: get length base*/
1136 length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
1138 /*part 2: get extra bits and add the value of that to length*/
1139 numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
1140 if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1141 length += readBitsFromStream(bp, in, numextrabits_l);
1143 /*part 3: get distance code*/
1144 code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
1145 if(code_d > 29)
1147 if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1149 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1150 (10=no endcode, 11=wrong jump outside of tree)*/
1151 error = (*bp) > inlength * 8 ? 10 : 11;
1153 else error = 18; /*error: invalid distance code (30-31 are never used)*/
1154 break;
1156 distance = DISTANCEBASE[code_d];
1158 /*part 4: get extra bits from distance*/
1159 numextrabits_d = DISTANCEEXTRA[code_d];
1160 if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1162 distance += readBitsFromStream(bp, in, numextrabits_d);
1164 /*part 5: fill in all the out[n] values based on the length and dist*/
1165 start = (*pos);
1166 if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
1167 backward = start - distance;
1168 if((*pos) + length >= out->size)
1170 /*reserve more room at once*/
1171 if(!ucvector_resize(out, ((*pos) + length) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1174 for(forward = 0; forward < length; forward++)
1176 out->data[(*pos)] = out->data[backward];
1177 (*pos)++;
1178 backward++;
1179 if(backward >= start) backward = start - distance;
1182 else if(code_ll == 256)
1184 break; /*end code, break the loop*/
1186 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1188 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1189 (10=no endcode, 11=wrong jump outside of tree)*/
1190 error = (*bp) > inlength * 8 ? 10 : 11;
1191 break;
1195 HuffmanTree_cleanup(&tree_ll);
1196 HuffmanTree_cleanup(&tree_d);
1198 return error;
1201 static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength)
1203 /*go to first boundary of byte*/
1204 size_t p;
1205 unsigned LEN, NLEN, n, error = 0;
1206 while(((*bp) & 0x7) != 0) (*bp)++;
1207 p = (*bp) / 8; /*byte position*/
1209 /*read LEN (2 bytes) and NLEN (2 bytes)*/
1210 if(p >= inlength - 4) return 52; /*error, bit pointer will jump past memory*/
1211 LEN = in[p] + 256 * in[p + 1]; p += 2;
1212 NLEN = in[p] + 256 * in[p + 1]; p += 2;
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*/
1217 if((*pos) + LEN >= out->size)
1219 if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
1222 /*read the literal data: LEN bytes are now stored in the out buffer*/
1223 if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
1224 for(n = 0; n < LEN; n++) out->data[(*pos)++] = in[p++];
1226 (*bp) = p * 8;
1228 return error;
1231 static unsigned lodepng_inflatev(ucvector* out,
1232 const unsigned char* in, size_t insize,
1233 const LodePNGDecompressSettings* settings)
1235 /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1236 size_t bp = 0;
1237 unsigned BFINAL = 0;
1238 size_t pos = 0; /*byte position in the out buffer*/
1240 unsigned error = 0;
1242 (void)settings;
1244 while(!BFINAL)
1246 unsigned BTYPE;
1247 if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
1248 BFINAL = readBitFromStream(&bp, in);
1249 BTYPE = 1 * readBitFromStream(&bp, in);
1250 BTYPE += 2 * readBitFromStream(&bp, in);
1252 if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
1253 else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
1254 else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
1256 if(error) return error;
1259 /*Only now we know the true size of out, resize it to that*/
1260 if(!ucvector_resize(out, pos)) error = 83; /*alloc fail*/
1262 return error;
1265 unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
1266 const unsigned char* in, size_t insize,
1267 const LodePNGDecompressSettings* settings)
1269 unsigned error;
1270 ucvector v;
1271 ucvector_init_buffer(&v, *out, *outsize);
1272 error = lodepng_inflatev(&v, in, insize, settings);
1273 *out = v.data;
1274 *outsize = v.size;
1275 return error;
1278 static unsigned inflate(unsigned char** out, size_t* outsize,
1279 const unsigned char* in, size_t insize,
1280 const LodePNGDecompressSettings* settings)
1282 if(settings->custom_inflate)
1284 return settings->custom_inflate(out, outsize, in, insize, settings);
1286 else
1288 return lodepng_inflate(out, outsize, in, insize, settings);
1292 #endif /*LODEPNG_COMPILE_DECODER*/
1294 #ifdef LODEPNG_COMPILE_ENCODER
1296 /* ////////////////////////////////////////////////////////////////////////// */
1297 /* / Deflator (Compressor) / */
1298 /* ////////////////////////////////////////////////////////////////////////// */
1300 static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
1302 /*bitlen is the size in bits of the code*/
1303 static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen)
1305 addBitsToStreamReversed(bp, compressed, code, bitlen);
1308 /*search the index in the array, that has the largest value smaller than or equal to the given value,
1309 given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1310 static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value)
1312 /*linear search implementation*/
1313 /*for(size_t i = 1; i < array_size; i++) if(array[i] > value) return i - 1;
1314 return array_size - 1;*/
1316 /*binary search implementation (not that much faster) (precondition: array_size > 0)*/
1317 size_t left = 1;
1318 size_t right = array_size - 1;
1319 while(left <= right)
1321 size_t mid = (left + right) / 2;
1322 if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/
1323 else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/
1324 else return mid - 1;
1326 return array_size - 1;
1329 static void addLengthDistance(uivector* values, size_t length, size_t distance)
1331 /*values in encoded vector are those used by deflate:
1332 0-255: literal bytes
1333 256: end
1334 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1335 286-287: invalid*/
1337 unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
1338 unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
1339 unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
1340 unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
1342 uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
1343 uivector_push_back(values, extra_length);
1344 uivector_push_back(values, dist_code);
1345 uivector_push_back(values, extra_distance);
1348 static const unsigned HASH_NUM_VALUES = 65536;
1349 static const unsigned HASH_NUM_CHARACTERS = 3;
1350 static const unsigned HASH_SHIFT = 2;
1352 The HASH_NUM_CHARACTERS value is used to make encoding faster by using longer
1353 sequences to generate a hash value from the stream bytes. Setting it to 3
1354 gives exactly the same compression as the brute force method, since deflate's
1355 run length encoding starts with lengths of 3. Setting it to higher values,
1356 like 6, can make the encoding faster (not always though!), but will cause the
1357 encoding to miss any length between 3 and this value, so that the compression
1358 may be worse (but this can vary too depending on the image, sometimes it is
1359 even a bit better instead).
1360 The HASH_NUM_VALUES is the amount of unique possible hash values that
1361 combinations of bytes can give, the higher it is the more memory is needed, but
1362 if it's too low the advantage of hashing is gone.
1365 typedef struct Hash
1367 int* head; /*hash value to head circular pos*/
1368 int* val; /*circular pos to hash value*/
1369 /*circular pos to prev circular pos*/
1370 unsigned short* chain;
1371 unsigned short* zeros;
1372 } Hash;
1374 static unsigned hash_init(Hash* hash, unsigned windowsize)
1376 unsigned i;
1377 hash->head = (int*)mymalloc(sizeof(int) * HASH_NUM_VALUES);
1378 hash->val = (int*)mymalloc(sizeof(int) * windowsize);
1379 hash->chain = (unsigned short*)mymalloc(sizeof(unsigned short) * windowsize);
1380 hash->zeros = (unsigned short*)mymalloc(sizeof(unsigned short) * windowsize);
1382 if(!hash->head || !hash->val || !hash->chain || !hash->zeros) return 83; /*alloc fail*/
1384 /*initialize hash table*/
1385 for(i = 0; i < HASH_NUM_VALUES; i++) hash->head[i] = -1;
1386 for(i = 0; i < windowsize; i++) hash->val[i] = -1;
1387 for(i = 0; i < windowsize; i++) hash->chain[i] = i; /*same value as index indicates uninitialized*/
1389 return 0;
1392 static void hash_cleanup(Hash* hash)
1394 myfree(hash->head);
1395 myfree(hash->val);
1396 myfree(hash->chain);
1397 myfree(hash->zeros);
1400 static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
1402 unsigned result = 0;
1403 size_t amount, i;
1404 if(pos >= size) return 0;
1405 amount = HASH_NUM_CHARACTERS;
1406 if(pos + amount >= size) amount = size - pos;
1407 for(i = 0; i < amount; i++) result ^= (data[pos + i] << (i * HASH_SHIFT));
1408 return result % HASH_NUM_VALUES;
1411 static unsigned countZeros(const unsigned char* data, size_t size, size_t pos)
1413 const unsigned char* start = data + pos;
1414 const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
1415 if(end > data + size) end = data + size;
1416 data = start;
1417 while (data != end && *data == 0) data++;
1418 /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1419 return (unsigned)(data - start);
1422 static void updateHashChain(Hash* hash, size_t pos, int hashval, unsigned windowsize)
1424 unsigned wpos = pos % windowsize;
1425 hash->val[wpos] = hashval;
1426 if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
1427 hash->head[hashval] = wpos;
1431 LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1432 is in the form of unsigned integers with codes representing for example literal bytes, or
1433 length/distance pairs.
1434 It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1435 sliding window (of windowsize) is used, and all past bytes in that window can be used as
1436 the "dictionary". A brute force search through all possible distances would be slow, and
1437 this hash technique is one out of several ways to speed this up.
1439 static unsigned encodeLZ77(uivector* out, Hash* hash,
1440 const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
1441 unsigned minmatch, unsigned nicematch, unsigned lazymatching)
1443 unsigned short numzeros = 0;
1444 int usezeros = windowsize >= 8192; /*for small window size, the 'max chain length' optimization does a better job*/
1445 unsigned pos, i, error = 0;
1446 /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1447 unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
1448 unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
1450 if(!error)
1452 unsigned offset; /*the offset represents the distance in LZ77 terminology*/
1453 unsigned length;
1454 unsigned lazy = 0;
1455 unsigned lazylength = 0, lazyoffset = 0;
1456 unsigned hashval;
1457 unsigned current_offset, current_length;
1458 const unsigned char *lastptr, *foreptr, *backptr;
1459 unsigned short hashpos, prevpos;
1461 for(pos = inpos; pos < insize; pos++)
1463 size_t wpos = pos % windowsize; /*position for in 'circular' hash buffers*/
1465 hashval = getHash(in, insize, pos);
1466 updateHashChain(hash, pos, hashval, windowsize);
1468 if(usezeros && hashval == 0)
1470 numzeros = countZeros(in, insize, pos);
1471 hash->zeros[wpos] = numzeros;
1474 /*the length and offset found for the current position*/
1475 length = 0;
1476 offset = 0;
1478 prevpos = hash->head[hashval];
1479 hashpos = hash->chain[prevpos];
1481 lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
1483 /*search for the longest string*/
1484 if(hash->val[wpos] == (int)hashval)
1486 unsigned chainlength = 0;
1487 for(;;)
1489 /*stop when went completely around the circular buffer*/
1490 if(prevpos < wpos && hashpos > prevpos && hashpos <= wpos) break;
1491 if(prevpos > wpos && (hashpos <= wpos || hashpos > prevpos)) break;
1492 if(chainlength++ >= maxchainlength) break;
1494 current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize;
1495 if(current_offset > 0)
1497 /*test the next characters*/
1498 foreptr = &in[pos];
1499 backptr = &in[pos - current_offset];
1501 /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1502 if(usezeros && hashval == 0 && hash->val[hashpos] == 0 /*hashval[hashpos] may be out of date*/)
1504 unsigned short skip = hash->zeros[hashpos];
1505 if(skip > numzeros) skip = numzeros;
1506 backptr += skip;
1507 foreptr += skip;
1510 /* multiple checks at once per array bounds check */
1511 while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/
1513 ++backptr;
1514 ++foreptr;
1516 current_length = (unsigned)(foreptr - &in[pos]);
1518 if(current_length > length)
1520 length = current_length; /*the longest length*/
1521 offset = current_offset; /*the offset that is related to this longest length*/
1522 /*jump out once a length of max length is found (speed gain)*/
1523 if(current_length >= nicematch || current_length == MAX_SUPPORTED_DEFLATE_LENGTH) break;
1527 if(hashpos == hash->chain[hashpos]) break;
1529 prevpos = hashpos;
1530 hashpos = hash->chain[hashpos];
1534 if(lazymatching)
1536 if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH)
1538 lazy = 1;
1539 lazylength = length;
1540 lazyoffset = offset;
1541 continue; /*try the next byte*/
1543 if(lazy)
1545 lazy = 0;
1546 if(pos == 0) ERROR_BREAK(81);
1547 if(length > lazylength + 1)
1549 /*push the previous character as literal*/
1550 if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
1552 else
1554 length = lazylength;
1555 offset = lazyoffset;
1556 hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1557 pos--;
1561 if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1563 /**encode it as length/distance pair or literal value**/
1564 if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1566 if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1568 else if(length < minmatch || (length == 3 && offset > 4096))
1570 /*compensate for the fact that longer offsets have more extra bits, a
1571 length of only 3 may be not worth it then*/
1572 if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1574 else
1576 addLengthDistance(out, length, offset);
1577 for(i = 1; i < length; i++)
1579 pos++;
1580 hashval = getHash(in, insize, pos);
1581 updateHashChain(hash, pos, hashval, windowsize);
1582 if(usezeros && hashval == 0)
1584 hash->zeros[pos % windowsize] = countZeros(in, insize, pos);
1589 } /*end of the loop through each character of input*/
1590 } /*end of "if(!error)"*/
1592 return error;
1595 /* /////////////////////////////////////////////////////////////////////////// */
1597 static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize)
1599 /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1600 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1602 size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
1603 unsigned datapos = 0;
1604 for(i = 0; i < numdeflateblocks; i++)
1606 unsigned BFINAL, BTYPE, LEN, NLEN;
1607 unsigned char firstbyte;
1609 BFINAL = (i == numdeflateblocks - 1);
1610 BTYPE = 0;
1612 firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
1613 ucvector_push_back(out, firstbyte);
1615 LEN = 65535;
1616 if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
1617 NLEN = 65535 - LEN;
1619 ucvector_push_back(out, (unsigned char)(LEN % 256));
1620 ucvector_push_back(out, (unsigned char)(LEN / 256));
1621 ucvector_push_back(out, (unsigned char)(NLEN % 256));
1622 ucvector_push_back(out, (unsigned char)(NLEN / 256));
1624 /*Decompressed data*/
1625 for(j = 0; j < 65535 && datapos < datasize; j++)
1627 ucvector_push_back(out, data[datapos++]);
1631 return 0;
1635 write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1636 tree_ll: the tree for lit and len codes.
1637 tree_d: the tree for distance codes.
1639 static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
1640 const HuffmanTree* tree_ll, const HuffmanTree* tree_d)
1642 size_t i = 0;
1643 for(i = 0; i < lz77_encoded->size; i++)
1645 unsigned val = lz77_encoded->data[i];
1646 addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
1647 if(val > 256) /*for a length code, 3 more things have to be added*/
1649 unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
1650 unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
1651 unsigned length_extra_bits = lz77_encoded->data[++i];
1653 unsigned distance_code = lz77_encoded->data[++i];
1655 unsigned distance_index = distance_code;
1656 unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
1657 unsigned distance_extra_bits = lz77_encoded->data[++i];
1659 addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
1660 addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
1661 HuffmanTree_getLength(tree_d, distance_code));
1662 addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
1667 /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1668 static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
1669 const unsigned char* data, size_t datapos, size_t dataend,
1670 const LodePNGCompressSettings* settings, int final)
1672 unsigned error = 0;
1675 A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1676 literal bytes and length/distance pairs. This is then huffman compressed with
1677 two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1678 another huffman tree is used for the dist values ("d"). These two trees are
1679 stored using their code lengths, and to compress even more these code lengths
1680 are also run-length encoded and huffman compressed. This gives a huffman tree
1681 of code lengths "cl". The code lenghts used to describe this third tree are
1682 the code length code lengths ("clcl").
1685 /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1686 uivector lz77_encoded;
1687 HuffmanTree tree_ll; /*tree for lit,len values*/
1688 HuffmanTree tree_d; /*tree for distance codes*/
1689 HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1690 uivector frequencies_ll; /*frequency of lit,len codes*/
1691 uivector frequencies_d; /*frequency of dist codes*/
1692 uivector frequencies_cl; /*frequency of code length codes*/
1693 uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1694 uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1695 /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1696 (these are written as is in the file, it would be crazy to compress these using yet another huffman
1697 tree that needs to be represented by yet another set of code lengths)*/
1698 uivector bitlen_cl;
1699 size_t datasize = dataend - datapos;
1702 Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1703 bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1704 bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1705 bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1708 unsigned BFINAL = final;
1709 size_t numcodes_ll, numcodes_d, i;
1710 unsigned HLIT, HDIST, HCLEN;
1712 uivector_init(&lz77_encoded);
1713 HuffmanTree_init(&tree_ll);
1714 HuffmanTree_init(&tree_d);
1715 HuffmanTree_init(&tree_cl);
1716 uivector_init(&frequencies_ll);
1717 uivector_init(&frequencies_d);
1718 uivector_init(&frequencies_cl);
1719 uivector_init(&bitlen_lld);
1720 uivector_init(&bitlen_lld_e);
1721 uivector_init(&bitlen_cl);
1723 /*This while loop never loops due to a break at the end, it is here to
1724 allow breaking out of it to the cleanup phase on error conditions.*/
1725 while(!error)
1727 if(settings->use_lz77)
1729 error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1730 settings->minmatch, settings->nicematch, settings->lazymatching);
1731 if(error) break;
1733 else
1735 if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
1736 for(i = datapos; i < dataend; i++) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/
1739 if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
1740 if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
1742 /*Count the frequencies of lit, len and dist codes*/
1743 for(i = 0; i < lz77_encoded.size; i++)
1745 unsigned symbol = lz77_encoded.data[i];
1746 frequencies_ll.data[symbol]++;
1747 if(symbol > 256)
1749 unsigned dist = lz77_encoded.data[i + 2];
1750 frequencies_d.data[dist]++;
1751 i += 3;
1754 frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1756 /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1757 error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
1758 if(error) break;
1759 /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1760 error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
1761 if(error) break;
1763 numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
1764 numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
1765 /*store the code lengths of both generated trees in bitlen_lld*/
1766 for(i = 0; i < numcodes_ll; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
1767 for(i = 0; i < numcodes_d; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
1769 /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1770 17 (3-10 zeroes), 18 (11-138 zeroes)*/
1771 for(i = 0; i < (unsigned)bitlen_lld.size; i++)
1773 unsigned j = 0; /*amount of repititions*/
1774 while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) j++;
1776 if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/
1778 j++; /*include the first zero*/
1779 if(j <= 10) /*repeat code 17 supports max 10 zeroes*/
1781 uivector_push_back(&bitlen_lld_e, 17);
1782 uivector_push_back(&bitlen_lld_e, j - 3);
1784 else /*repeat code 18 supports max 138 zeroes*/
1786 if(j > 138) j = 138;
1787 uivector_push_back(&bitlen_lld_e, 18);
1788 uivector_push_back(&bitlen_lld_e, j - 11);
1790 i += (j - 1);
1792 else if(j >= 3) /*repeat code for value other than zero*/
1794 size_t k;
1795 unsigned num = j / 6, rest = j % 6;
1796 uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1797 for(k = 0; k < num; k++)
1799 uivector_push_back(&bitlen_lld_e, 16);
1800 uivector_push_back(&bitlen_lld_e, 6 - 3);
1802 if(rest >= 3)
1804 uivector_push_back(&bitlen_lld_e, 16);
1805 uivector_push_back(&bitlen_lld_e, rest - 3);
1807 else j -= rest;
1808 i += j;
1810 else /*too short to benefit from repeat code*/
1812 uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1816 /*generate tree_cl, the huffmantree of huffmantrees*/
1818 if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
1819 for(i = 0; i < bitlen_lld_e.size; i++)
1821 frequencies_cl.data[bitlen_lld_e.data[i]]++;
1822 /*after a repeat code come the bits that specify the number of repetitions,
1823 those don't need to be in the frequencies_cl calculation*/
1824 if(bitlen_lld_e.data[i] >= 16) i++;
1827 error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
1828 frequencies_cl.size, frequencies_cl.size, 7);
1829 if(error) break;
1831 if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
1832 for(i = 0; i < tree_cl.numcodes; i++)
1834 /*lenghts of code length tree is in the order as specified by deflate*/
1835 bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
1837 while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4)
1839 /*remove zeros at the end, but minimum size must be 4*/
1840 if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
1842 if(error) break;
1845 Write everything into the output
1847 After the BFINAL and BTYPE, the dynamic block consists out of the following:
1848 - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1849 - (HCLEN+4)*3 bits code lengths of code length alphabet
1850 - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
1851 alphabet, + possible repetition codes 16, 17, 18)
1852 - HDIST + 1 code lengths of distance alphabet (encoded using the code length
1853 alphabet, + possible repetition codes 16, 17, 18)
1854 - compressed data
1855 - 256 (end code)
1858 /*Write block type*/
1859 addBitToStream(bp, out, BFINAL);
1860 addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
1861 addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
1863 /*write the HLIT, HDIST and HCLEN values*/
1864 HLIT = (unsigned)(numcodes_ll - 257);
1865 HDIST = (unsigned)(numcodes_d - 1);
1866 HCLEN = (unsigned)bitlen_cl.size - 4;
1867 /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
1868 while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) HCLEN--;
1869 addBitsToStream(bp, out, HLIT, 5);
1870 addBitsToStream(bp, out, HDIST, 5);
1871 addBitsToStream(bp, out, HCLEN, 4);
1873 /*write the code lenghts of the code length alphabet*/
1874 for(i = 0; i < HCLEN + 4; i++) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
1876 /*write the lenghts of the lit/len AND the dist alphabet*/
1877 for(i = 0; i < bitlen_lld_e.size; i++)
1879 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
1880 HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
1881 /*extra bits of repeat codes*/
1882 if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
1883 else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
1884 else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
1887 /*write the compressed data symbols*/
1888 writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1889 /*error: the length of the end code 256 must be larger than 0*/
1890 if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
1892 /*write the end code*/
1893 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1895 break; /*end of error-while*/
1898 /*cleanup*/
1899 uivector_cleanup(&lz77_encoded);
1900 HuffmanTree_cleanup(&tree_ll);
1901 HuffmanTree_cleanup(&tree_d);
1902 HuffmanTree_cleanup(&tree_cl);
1903 uivector_cleanup(&frequencies_ll);
1904 uivector_cleanup(&frequencies_d);
1905 uivector_cleanup(&frequencies_cl);
1906 uivector_cleanup(&bitlen_lld_e);
1907 uivector_cleanup(&bitlen_lld);
1908 uivector_cleanup(&bitlen_cl);
1910 return error;
1913 static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
1914 const unsigned char* data,
1915 size_t datapos, size_t dataend,
1916 const LodePNGCompressSettings* settings, int final)
1918 HuffmanTree tree_ll; /*tree for literal values and length codes*/
1919 HuffmanTree tree_d; /*tree for distance codes*/
1921 unsigned BFINAL = final;
1922 unsigned error = 0;
1923 size_t i;
1925 HuffmanTree_init(&tree_ll);
1926 HuffmanTree_init(&tree_d);
1928 generateFixedLitLenTree(&tree_ll);
1929 generateFixedDistanceTree(&tree_d);
1931 addBitToStream(bp, out, BFINAL);
1932 addBitToStream(bp, out, 1); /*first bit of BTYPE*/
1933 addBitToStream(bp, out, 0); /*second bit of BTYPE*/
1935 if(settings->use_lz77) /*LZ77 encoded*/
1937 uivector lz77_encoded;
1938 uivector_init(&lz77_encoded);
1939 error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1940 settings->minmatch, settings->nicematch, settings->lazymatching);
1941 if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1942 uivector_cleanup(&lz77_encoded);
1944 else /*no LZ77, but still will be Huffman compressed*/
1946 for(i = datapos; i < dataend; i++)
1948 addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
1951 /*add END code*/
1952 if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1954 /*cleanup*/
1955 HuffmanTree_cleanup(&tree_ll);
1956 HuffmanTree_cleanup(&tree_d);
1958 return error;
1961 static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
1962 const LodePNGCompressSettings* settings)
1964 unsigned error = 0;
1965 size_t i, blocksize, numdeflateblocks;
1966 size_t bp = 0; /*the bit pointer*/
1967 Hash hash;
1969 if(settings->btype > 2) return 61;
1970 else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
1971 else if(settings->btype == 1) blocksize = insize;
1972 else /*if(settings->btype == 2)*/
1974 blocksize = insize / 8 + 8;
1975 if(blocksize < 65535) blocksize = 65535;
1978 numdeflateblocks = (insize + blocksize - 1) / blocksize;
1979 if(numdeflateblocks == 0) numdeflateblocks = 1;
1981 error = hash_init(&hash, settings->windowsize);
1982 if(error) return error;
1984 for(i = 0; i < numdeflateblocks && !error; i++)
1986 int final = i == numdeflateblocks - 1;
1987 size_t start = i * blocksize;
1988 size_t end = start + blocksize;
1989 if(end > insize) end = insize;
1991 if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
1992 else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
1995 hash_cleanup(&hash);
1997 return error;
2000 unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
2001 const unsigned char* in, size_t insize,
2002 const LodePNGCompressSettings* settings)
2004 unsigned error;
2005 ucvector v;
2006 ucvector_init_buffer(&v, *out, *outsize);
2007 error = lodepng_deflatev(&v, in, insize, settings);
2008 *out = v.data;
2009 *outsize = v.size;
2010 return error;
2013 static unsigned deflate(unsigned char** out, size_t* outsize,
2014 const unsigned char* in, size_t insize,
2015 const LodePNGCompressSettings* settings)
2017 if(settings->custom_deflate)
2019 return settings->custom_deflate(out, outsize, in, insize, settings);
2021 else
2023 return lodepng_deflate(out, outsize, in, insize, settings);
2027 #endif /*LODEPNG_COMPILE_DECODER*/
2029 /* ////////////////////////////////////////////////////////////////////////// */
2030 /* / Adler32 */
2031 /* ////////////////////////////////////////////////////////////////////////// */
2033 static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
2035 unsigned s1 = adler & 0xffff;
2036 unsigned s2 = (adler >> 16) & 0xffff;
2038 while(len > 0)
2040 /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2041 unsigned amount = len > 5550 ? 5550 : len;
2042 len -= amount;
2043 while(amount > 0)
2045 s1 += (*data++);
2046 s2 += s1;
2047 amount--;
2049 s1 %= 65521;
2050 s2 %= 65521;
2053 return (s2 << 16) | s1;
2056 /*Return the adler32 of the bytes data[0..len-1]*/
2057 static unsigned adler32(const unsigned char* data, unsigned len)
2059 return update_adler32(1L, data, len);
2062 /* ////////////////////////////////////////////////////////////////////////// */
2063 /* / Zlib / */
2064 /* ////////////////////////////////////////////////////////////////////////// */
2066 #ifdef LODEPNG_COMPILE_DECODER
2068 unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2069 size_t insize, const LodePNGDecompressSettings* settings)
2071 unsigned error = 0;
2072 unsigned CM, CINFO, FDICT;
2074 if(insize < 2) return 53; /*error, size of zlib data too small*/
2075 /*read information from zlib header*/
2076 if((in[0] * 256 + in[1]) % 31 != 0)
2078 /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2079 return 24;
2082 CM = in[0] & 15;
2083 CINFO = (in[0] >> 4) & 15;
2084 /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2085 FDICT = (in[1] >> 5) & 1;
2086 /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2088 if(CM != 8 || CINFO > 7)
2090 /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2091 return 25;
2093 if(FDICT != 0)
2095 /*error: the specification of PNG says about the zlib stream:
2096 "The additional flags shall not specify a preset dictionary."*/
2097 return 26;
2100 error = inflate(out, outsize, in + 2, insize - 2, settings);
2101 if(error) return error;
2103 if(!settings->ignore_adler32)
2105 unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
2106 unsigned checksum = adler32(*out, (unsigned)(*outsize));
2107 if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
2110 return 0; /*no error*/
2113 static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2114 size_t insize, const LodePNGDecompressSettings* settings)
2116 if(settings->custom_zlib)
2117 return settings->custom_zlib(out, outsize, in, insize, settings);
2118 else
2119 return lodepng_zlib_decompress(out, outsize, in, insize, settings);
2122 #endif /*LODEPNG_COMPILE_DECODER*/
2124 #ifdef LODEPNG_COMPILE_ENCODER
2126 unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2127 size_t insize, const LodePNGCompressSettings* settings)
2129 /*initially, *out must be NULL and outsize 0, if you just give some random *out
2130 that's pointing to a non allocated buffer, this'll crash*/
2131 ucvector outv;
2132 size_t i;
2133 unsigned error;
2134 unsigned char* deflatedata = 0;
2135 size_t deflatesize = 0;
2137 unsigned ADLER32;
2138 /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2139 unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2140 unsigned FLEVEL = 0;
2141 unsigned FDICT = 0;
2142 unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
2143 unsigned FCHECK = 31 - CMFFLG % 31;
2144 CMFFLG += FCHECK;
2146 /*ucvector-controlled version of the output buffer, for dynamic array*/
2147 ucvector_init_buffer(&outv, *out, *outsize);
2149 ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256));
2150 ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256));
2152 error = deflate(&deflatedata, &deflatesize, in, insize, settings);
2154 if(!error)
2156 ADLER32 = adler32(in, (unsigned)insize);
2157 for(i = 0; i < deflatesize; i++) ucvector_push_back(&outv, deflatedata[i]);
2158 free(deflatedata);
2159 lodepng_add32bitInt(&outv, ADLER32);
2162 *out = outv.data;
2163 *outsize = outv.size;
2165 return error;
2168 /* compress using the default or custom zlib function */
2169 static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2170 size_t insize, const LodePNGCompressSettings* settings)
2172 if(settings->custom_zlib)
2174 return settings->custom_zlib(out, outsize, in, insize, settings);
2176 else
2178 return lodepng_zlib_compress(out, outsize, in, insize, settings);
2182 #endif /*LODEPNG_COMPILE_ENCODER*/
2184 #else /*no LODEPNG_COMPILE_ZLIB*/
2186 #ifdef LODEPNG_COMPILE_DECODER
2187 static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2188 size_t insize, const LodePNGDecompressSettings* settings)
2190 if (!settings->custom_zlib) return 87; /*no custom zlib function provided */
2191 return settings->custom_zlib(out, outsize, in, insize, settings);
2193 #endif /*LODEPNG_COMPILE_DECODER*/
2194 #ifdef LODEPNG_COMPILE_ENCODER
2195 static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2196 size_t insize, const LodePNGCompressSettings* settings)
2198 if (!settings->custom_zlib) return 87; /*no custom zlib function provided */
2199 return settings->custom_zlib(out, outsize, in, insize, settings);
2201 #endif /*LODEPNG_COMPILE_ENCODER*/
2203 #endif /*LODEPNG_COMPILE_ZLIB*/
2205 /* ////////////////////////////////////////////////////////////////////////// */
2207 #ifdef LODEPNG_COMPILE_ENCODER
2209 /*this is a good tradeoff between speed and compression ratio*/
2210 #define DEFAULT_WINDOWSIZE 2048
2212 void lodepng_compress_settings_init(LodePNGCompressSettings* settings)
2214 /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2215 settings->btype = 2;
2216 settings->use_lz77 = 1;
2217 settings->windowsize = DEFAULT_WINDOWSIZE;
2218 settings->minmatch = 3;
2219 settings->nicematch = 128;
2220 settings->lazymatching = 1;
2222 settings->custom_zlib = 0;
2223 settings->custom_deflate = 0;
2224 settings->custom_context = 0;
2227 const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
2230 #endif /*LODEPNG_COMPILE_ENCODER*/
2232 #ifdef LODEPNG_COMPILE_DECODER
2234 void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
2236 settings->ignore_adler32 = 0;
2238 settings->custom_zlib = 0;
2239 settings->custom_inflate = 0;
2240 settings->custom_context = 0;
2243 const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
2245 #endif /*LODEPNG_COMPILE_DECODER*/
2247 /* ////////////////////////////////////////////////////////////////////////// */
2248 /* ////////////////////////////////////////////////////////////////////////// */
2249 /* // End of Zlib related code. Begin of PNG related code. // */
2250 /* ////////////////////////////////////////////////////////////////////////// */
2251 /* ////////////////////////////////////////////////////////////////////////// */
2253 #ifdef LODEPNG_COMPILE_PNG
2255 /* ////////////////////////////////////////////////////////////////////////// */
2256 /* / CRC32 / */
2257 /* ////////////////////////////////////////////////////////////////////////// */
2259 static unsigned Crc32_crc_table_computed = 0;
2260 static unsigned Crc32_crc_table[256];
2262 /*Make the table for a fast CRC.*/
2263 static void Crc32_make_crc_table(void)
2265 unsigned c, k, n;
2266 for(n = 0; n < 256; n++)
2268 c = n;
2269 for(k = 0; k < 8; k++)
2271 if(c & 1) c = 0xedb88320L ^ (c >> 1);
2272 else c = c >> 1;
2274 Crc32_crc_table[n] = c;
2276 Crc32_crc_table_computed = 1;
2279 /*Update a running CRC with the bytes buf[0..len-1]--the CRC should be
2280 initialized to all 1's, and the transmitted value is the 1's complement of the
2281 final running CRC (see the crc() routine below).*/
2282 static unsigned Crc32_update_crc(const unsigned char* buf, unsigned crc, size_t len)
2284 unsigned c = crc;
2285 size_t n;
2287 if(!Crc32_crc_table_computed) Crc32_make_crc_table();
2288 for(n = 0; n < len; n++)
2290 c = Crc32_crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
2292 return c;
2295 /*Return the CRC of the bytes buf[0..len-1].*/
2296 unsigned lodepng_crc32(const unsigned char* buf, size_t len)
2298 return Crc32_update_crc(buf, 0xffffffffL, len) ^ 0xffffffffL;
2301 /* ////////////////////////////////////////////////////////////////////////// */
2302 /* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2303 /* ////////////////////////////////////////////////////////////////////////// */
2305 static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
2307 unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2308 (*bitpointer)++;
2309 return result;
2312 static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
2314 unsigned result = 0;
2315 size_t i;
2316 for(i = nbits - 1; i < nbits; i--)
2318 result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
2320 return result;
2323 #ifdef LODEPNG_COMPILE_DECODER
2324 static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2326 /*the current bit in bitstream must be 0 for this to work*/
2327 if(bit)
2329 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2330 bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
2332 (*bitpointer)++;
2334 #endif /*LODEPNG_COMPILE_DECODER*/
2336 static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2338 /*the current bit in bitstream may be 0 or 1 for this to work*/
2339 if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
2340 else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
2341 (*bitpointer)++;
2344 /* ////////////////////////////////////////////////////////////////////////// */
2345 /* / PNG chunks / */
2346 /* ////////////////////////////////////////////////////////////////////////// */
2348 unsigned lodepng_chunk_length(const unsigned char* chunk)
2350 return lodepng_read32bitInt(&chunk[0]);
2353 void lodepng_chunk_type(char type[5], const unsigned char* chunk)
2355 unsigned i;
2356 for(i = 0; i < 4; i++) type[i] = chunk[4 + i];
2357 type[4] = 0; /*null termination char*/
2360 unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
2362 if(strlen(type) != 4) return 0;
2363 return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2366 unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
2368 return((chunk[4] & 32) != 0);
2371 unsigned char lodepng_chunk_private(const unsigned char* chunk)
2373 return((chunk[6] & 32) != 0);
2376 unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
2378 return((chunk[7] & 32) != 0);
2381 unsigned char* lodepng_chunk_data(unsigned char* chunk)
2383 return &chunk[8];
2386 const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
2388 return &chunk[8];
2391 unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
2393 unsigned length = lodepng_chunk_length(chunk);
2394 unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
2395 /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2396 unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2397 if(CRC != checksum) return 1;
2398 else return 0;
2401 void lodepng_chunk_generate_crc(unsigned char* chunk)
2403 unsigned length = lodepng_chunk_length(chunk);
2404 unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
2405 lodepng_set32bitInt(chunk + 8 + length, CRC);
2408 unsigned char* lodepng_chunk_next(unsigned char* chunk)
2410 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2411 return &chunk[total_chunk_length];
2414 const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
2416 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2417 return &chunk[total_chunk_length];
2420 unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
2422 unsigned i;
2423 unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2424 unsigned char *chunk_start, *new_buffer;
2425 size_t new_length = (*outlength) + total_chunk_length;
2426 if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
2428 new_buffer = (unsigned char*)myrealloc(*out, new_length);
2429 if(!new_buffer) return 83; /*alloc fail*/
2430 (*out) = new_buffer;
2431 (*outlength) = new_length;
2432 chunk_start = &(*out)[new_length - total_chunk_length];
2434 for(i = 0; i < total_chunk_length; i++) chunk_start[i] = chunk[i];
2436 return 0;
2439 unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
2440 const char* type, const unsigned char* data)
2442 unsigned i;
2443 unsigned char *chunk, *new_buffer;
2444 size_t new_length = (*outlength) + length + 12;
2445 if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
2446 new_buffer = (unsigned char*)myrealloc(*out, new_length);
2447 if(!new_buffer) return 83; /*alloc fail*/
2448 (*out) = new_buffer;
2449 (*outlength) = new_length;
2450 chunk = &(*out)[(*outlength) - length - 12];
2452 /*1: length*/
2453 lodepng_set32bitInt(chunk, (unsigned)length);
2455 /*2: chunk name (4 letters)*/
2456 chunk[4] = type[0];
2457 chunk[5] = type[1];
2458 chunk[6] = type[2];
2459 chunk[7] = type[3];
2461 /*3: the data*/
2462 for(i = 0; i < length; i++) chunk[8 + i] = data[i];
2464 /*4: CRC (of the chunkname characters and the data)*/
2465 lodepng_chunk_generate_crc(chunk);
2467 return 0;
2470 /* ////////////////////////////////////////////////////////////////////////// */
2471 /* / Color types and such / */
2472 /* ////////////////////////////////////////////////////////////////////////// */
2474 /*return type is a LodePNG error code*/
2475 static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
2477 switch(colortype)
2479 case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
2480 case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
2481 case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
2482 case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
2483 case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
2484 default: return 31;
2486 return 0; /*allowed color type / bits combination*/
2489 static unsigned getNumColorChannels(LodePNGColorType colortype)
2491 switch(colortype)
2493 case 0: return 1; /*grey*/
2494 case 2: return 3; /*RGB*/
2495 case 3: return 1; /*palette*/
2496 case 4: return 2; /*grey + alpha*/
2497 case 6: return 4; /*RGBA*/
2499 return 0; /*unexisting color type*/
2502 static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
2504 /*bits per pixel is amount of channels * bits per channel*/
2505 return getNumColorChannels(colortype) * bitdepth;
2508 /* ////////////////////////////////////////////////////////////////////////// */
2510 void lodepng_color_mode_init(LodePNGColorMode* info)
2512 info->key_defined = 0;
2513 info->key_r = info->key_g = info->key_b = 0;
2514 info->colortype = LCT_RGBA;
2515 info->bitdepth = 8;
2516 info->palette = 0;
2517 info->palettesize = 0;
2520 void lodepng_color_mode_cleanup(LodePNGColorMode* info)
2522 lodepng_palette_clear(info);
2525 unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
2527 size_t i;
2528 lodepng_color_mode_cleanup(dest);
2529 *dest = *source;
2530 if(source->palette)
2532 dest->palette = (unsigned char*)mymalloc(source->palettesize * 4);
2533 if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2534 for(i = 0; i < source->palettesize * 4; i++) dest->palette[i] = source->palette[i];
2536 return 0;
2539 static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
2541 size_t i;
2542 if(a->colortype != b->colortype) return 0;
2543 if(a->bitdepth != b->bitdepth) return 0;
2544 if(a->key_defined != b->key_defined) return 0;
2545 if(a->key_defined)
2547 if(a->key_r != b->key_r) return 0;
2548 if(a->key_g != b->key_g) return 0;
2549 if(a->key_b != b->key_b) return 0;
2551 if(a->palettesize != b->palettesize) return 0;
2552 for(i = 0; i < a->palettesize * 4; i++)
2554 if(a->palette[i] != b->palette[i]) return 0;
2556 return 1;
2559 void lodepng_palette_clear(LodePNGColorMode* info)
2561 if(info->palette) myfree(info->palette);
2562 info->palettesize = 0;
2565 unsigned lodepng_palette_add(LodePNGColorMode* info,
2566 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2568 unsigned char* data;
2569 /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2570 the max of 256 colors, it'll have the exact alloc size*/
2571 if(!(info->palettesize & (info->palettesize - 1))) /*if palettesize is 0 or a power of two*/
2573 /*allocated data must be at least 4* palettesize (for 4 color bytes)*/
2574 size_t alloc_size = info->palettesize == 0 ? 4 : info->palettesize * 4 * 2;
2575 data = (unsigned char*)myrealloc(info->palette, alloc_size);
2576 if(!data) return 83; /*alloc fail*/
2577 else info->palette = data;
2579 info->palette[4 * info->palettesize + 0] = r;
2580 info->palette[4 * info->palettesize + 1] = g;
2581 info->palette[4 * info->palettesize + 2] = b;
2582 info->palette[4 * info->palettesize + 3] = a;
2583 info->palettesize++;
2584 return 0;
2587 unsigned lodepng_get_bpp(const LodePNGColorMode* info)
2589 /*calculate bits per pixel out of colortype and bitdepth*/
2590 return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
2593 unsigned lodepng_get_channels(const LodePNGColorMode* info)
2595 return getNumColorChannels(info->colortype);
2598 unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
2600 return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
2603 unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
2605 return (info->colortype & 4) != 0; /*4 or 6*/
2608 unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
2610 return info->colortype == LCT_PALETTE;
2613 unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
2615 size_t i;
2616 for(i = 0; i < info->palettesize; i++)
2618 if(info->palette[i * 4 + 3] < 255) return 1;
2620 return 0;
2623 unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
2625 return info->key_defined
2626 || lodepng_is_alpha_type(info)
2627 || lodepng_has_palette_alpha(info);
2630 size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
2632 return (w * h * lodepng_get_bpp(color) + 7) / 8;
2635 size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
2637 return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8;
2640 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2642 static void LodePNGUnknownChunks_init(LodePNGInfo* info)
2644 unsigned i;
2645 for(i = 0; i < 3; i++) info->unknown_chunks_data[i] = 0;
2646 for(i = 0; i < 3; i++) info->unknown_chunks_size[i] = 0;
2649 static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
2651 unsigned i;
2652 for(i = 0; i < 3; i++) myfree(info->unknown_chunks_data[i]);
2655 static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
2657 unsigned i;
2659 LodePNGUnknownChunks_cleanup(dest);
2661 for(i = 0; i < 3; i++)
2663 size_t j;
2664 dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
2665 dest->unknown_chunks_data[i] = (unsigned char*)mymalloc(src->unknown_chunks_size[i]);
2666 if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
2667 for(j = 0; j < src->unknown_chunks_size[i]; j++)
2669 dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
2673 return 0;
2676 /******************************************************************************/
2678 static void LodePNGText_init(LodePNGInfo* info)
2680 info->text_num = 0;
2681 info->text_keys = NULL;
2682 info->text_strings = NULL;
2685 static void LodePNGText_cleanup(LodePNGInfo* info)
2687 size_t i;
2688 for(i = 0; i < info->text_num; i++)
2690 string_cleanup(&info->text_keys[i]);
2691 string_cleanup(&info->text_strings[i]);
2693 myfree(info->text_keys);
2694 myfree(info->text_strings);
2697 static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2699 size_t i = 0;
2700 dest->text_keys = 0;
2701 dest->text_strings = 0;
2702 dest->text_num = 0;
2703 for(i = 0; i < source->text_num; i++)
2705 CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
2707 return 0;
2710 void lodepng_clear_text(LodePNGInfo* info)
2712 LodePNGText_cleanup(info);
2715 unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
2717 char** new_keys = (char**)(myrealloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
2718 char** new_strings = (char**)(myrealloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
2719 if(!new_keys || !new_strings)
2721 myfree(new_keys);
2722 myfree(new_strings);
2723 return 83; /*alloc fail*/
2726 info->text_num++;
2727 info->text_keys = new_keys;
2728 info->text_strings = new_strings;
2730 string_init(&info->text_keys[info->text_num - 1]);
2731 string_set(&info->text_keys[info->text_num - 1], key);
2733 string_init(&info->text_strings[info->text_num - 1]);
2734 string_set(&info->text_strings[info->text_num - 1], str);
2736 return 0;
2739 /******************************************************************************/
2741 static void LodePNGIText_init(LodePNGInfo* info)
2743 info->itext_num = 0;
2744 info->itext_keys = NULL;
2745 info->itext_langtags = NULL;
2746 info->itext_transkeys = NULL;
2747 info->itext_strings = NULL;
2750 static void LodePNGIText_cleanup(LodePNGInfo* info)
2752 size_t i;
2753 for(i = 0; i < info->itext_num; i++)
2755 string_cleanup(&info->itext_keys[i]);
2756 string_cleanup(&info->itext_langtags[i]);
2757 string_cleanup(&info->itext_transkeys[i]);
2758 string_cleanup(&info->itext_strings[i]);
2760 myfree(info->itext_keys);
2761 myfree(info->itext_langtags);
2762 myfree(info->itext_transkeys);
2763 myfree(info->itext_strings);
2766 static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2768 size_t i = 0;
2769 dest->itext_keys = 0;
2770 dest->itext_langtags = 0;
2771 dest->itext_transkeys = 0;
2772 dest->itext_strings = 0;
2773 dest->itext_num = 0;
2774 for(i = 0; i < source->itext_num; i++)
2776 CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
2777 source->itext_transkeys[i], source->itext_strings[i]));
2779 return 0;
2782 void lodepng_clear_itext(LodePNGInfo* info)
2784 LodePNGIText_cleanup(info);
2787 unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
2788 const char* transkey, const char* str)
2790 char** new_keys = (char**)(myrealloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
2791 char** new_langtags = (char**)(myrealloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
2792 char** new_transkeys = (char**)(myrealloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
2793 char** new_strings = (char**)(myrealloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
2794 if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
2796 myfree(new_keys);
2797 myfree(new_langtags);
2798 myfree(new_transkeys);
2799 myfree(new_strings);
2800 return 83; /*alloc fail*/
2803 info->itext_num++;
2804 info->itext_keys = new_keys;
2805 info->itext_langtags = new_langtags;
2806 info->itext_transkeys = new_transkeys;
2807 info->itext_strings = new_strings;
2809 string_init(&info->itext_keys[info->itext_num - 1]);
2810 string_set(&info->itext_keys[info->itext_num - 1], key);
2812 string_init(&info->itext_langtags[info->itext_num - 1]);
2813 string_set(&info->itext_langtags[info->itext_num - 1], langtag);
2815 string_init(&info->itext_transkeys[info->itext_num - 1]);
2816 string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
2818 string_init(&info->itext_strings[info->itext_num - 1]);
2819 string_set(&info->itext_strings[info->itext_num - 1], str);
2821 return 0;
2823 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2825 void lodepng_info_init(LodePNGInfo* info)
2827 lodepng_color_mode_init(&info->color);
2828 info->interlace_method = 0;
2829 info->compression_method = 0;
2830 info->filter_method = 0;
2831 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2832 info->background_defined = 0;
2833 info->background_r = info->background_g = info->background_b = 0;
2835 LodePNGText_init(info);
2836 LodePNGIText_init(info);
2838 info->time_defined = 0;
2839 info->phys_defined = 0;
2841 LodePNGUnknownChunks_init(info);
2842 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2845 void lodepng_info_cleanup(LodePNGInfo* info)
2847 lodepng_color_mode_cleanup(&info->color);
2848 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2849 LodePNGText_cleanup(info);
2850 LodePNGIText_cleanup(info);
2852 LodePNGUnknownChunks_cleanup(info);
2853 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2856 unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2858 lodepng_info_cleanup(dest);
2859 *dest = *source;
2860 lodepng_color_mode_init(&dest->color);
2861 CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
2863 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2864 CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
2865 CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
2867 LodePNGUnknownChunks_init(dest);
2868 CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
2869 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2870 return 0;
2873 void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
2875 LodePNGInfo temp = *a;
2876 *a = *b;
2877 *b = temp;
2880 /* ////////////////////////////////////////////////////////////////////////// */
2882 /*index: bitgroup index, bits: bitgroup size(1, 2 or 4, in: bitgroup value, out: octet array to add bits to*/
2883 static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
2885 /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2886 unsigned p = index % (8 / bits);
2887 in &= (1 << bits) - 1; /*filter out any other bits of the input value*/
2888 in = in << (bits * (8 / bits - p - 1));
2889 if(p == 0) out[index * bits / 8] = in;
2890 else out[index * bits / 8] |= in;
2893 typedef struct ColorTree ColorTree;
2896 One node of a color tree
2897 This is the data structure used to count the number of unique colors and to get a palette
2898 index for a color. It's like an octree, but because the alpha channel is used too, each
2899 node has 16 instead of 8 children.
2901 struct ColorTree
2903 ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
2904 int index; /*the payload. Only has a meaningful value if this is in the last level*/
2907 static void color_tree_init(ColorTree* tree)
2909 int i;
2910 for(i = 0; i < 16; i++) tree->children[i] = 0;
2911 tree->index = -1;
2914 static void color_tree_cleanup(ColorTree* tree)
2916 int i;
2917 for(i = 0; i < 16; i++)
2919 if(tree->children[i])
2921 color_tree_cleanup(tree->children[i]);
2922 myfree(tree->children[i]);
2927 /*returns -1 if color not present, its index otherwise*/
2928 static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2930 int bit = 0;
2931 for(bit = 0; bit < 8; bit++)
2933 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
2934 if(!tree->children[i]) return -1;
2935 else tree = tree->children[i];
2937 return tree ? tree->index : -1;
2940 #ifdef LODEPNG_COMPILE_ENCODER
2941 static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2943 return color_tree_get(tree, r, g, b, a) >= 0;
2945 #endif /*LODEPNG_COMPILE_ENCODER*/
2947 /*color is not allowed to already exist.
2948 Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
2949 static void color_tree_add(ColorTree* tree,
2950 unsigned char r, unsigned char g, unsigned char b, unsigned char a, int index)
2952 int bit;
2953 for(bit = 0; bit < 8; bit++)
2955 int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
2956 if(!tree->children[i])
2958 tree->children[i] = (ColorTree*)mymalloc(sizeof(ColorTree));
2959 color_tree_init(tree->children[i]);
2961 tree = tree->children[i];
2963 tree->index = index;
2966 /*put a pixel, given its RGBA color, into image of any color type*/
2967 static unsigned rgba8ToPixel(unsigned char* out, size_t i,
2968 const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
2969 unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2971 if(mode->colortype == LCT_GREY)
2973 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
2974 if(mode->bitdepth == 8) out[i] = grey;
2975 else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
2976 else
2978 /*take the most significant bits of grey*/
2979 grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
2980 addColorBits(out, i, mode->bitdepth, grey);
2983 else if(mode->colortype == LCT_RGB)
2985 if(mode->bitdepth == 8)
2987 out[i * 3 + 0] = r;
2988 out[i * 3 + 1] = g;
2989 out[i * 3 + 2] = b;
2991 else
2993 out[i * 6 + 0] = out[i * 6 + 1] = r;
2994 out[i * 6 + 2] = out[i * 6 + 3] = g;
2995 out[i * 6 + 4] = out[i * 6 + 5] = b;
2998 else if(mode->colortype == LCT_PALETTE)
3000 int index = color_tree_get(tree, r, g, b, a);
3001 if(index < 0) return 82; /*color not in palette*/
3002 if(mode->bitdepth == 8) out[i] = index;
3003 else addColorBits(out, i, mode->bitdepth, index);
3005 else if(mode->colortype == LCT_GREY_ALPHA)
3007 unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3008 if(mode->bitdepth == 8)
3010 out[i * 2 + 0] = grey;
3011 out[i * 2 + 1] = a;
3013 else if(mode->bitdepth == 16)
3015 out[i * 4 + 0] = out[i * 4 + 1] = grey;
3016 out[i * 4 + 2] = out[i * 4 + 3] = a;
3019 else if(mode->colortype == LCT_RGBA)
3021 if(mode->bitdepth == 8)
3023 out[i * 4 + 0] = r;
3024 out[i * 4 + 1] = g;
3025 out[i * 4 + 2] = b;
3026 out[i * 4 + 3] = a;
3028 else
3030 out[i * 8 + 0] = out[i * 8 + 1] = r;
3031 out[i * 8 + 2] = out[i * 8 + 3] = g;
3032 out[i * 8 + 4] = out[i * 8 + 5] = b;
3033 out[i * 8 + 6] = out[i * 8 + 7] = a;
3037 return 0; /*no error*/
3040 /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3041 static unsigned rgba16ToPixel(unsigned char* out, size_t i,
3042 const LodePNGColorMode* mode,
3043 unsigned short r, unsigned short g, unsigned short b, unsigned short a)
3045 if(mode->bitdepth != 16) return 85; /*must be 16 for this function*/
3046 if(mode->colortype == LCT_GREY)
3048 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3049 out[i * 2 + 0] = (grey >> 8) & 255;
3050 out[i * 2 + 1] = grey & 255;
3052 else if(mode->colortype == LCT_RGB)
3054 out[i * 6 + 0] = (r >> 8) & 255;
3055 out[i * 6 + 1] = r & 255;
3056 out[i * 6 + 2] = (g >> 8) & 255;
3057 out[i * 6 + 3] = g & 255;
3058 out[i * 6 + 4] = (b >> 8) & 255;
3059 out[i * 6 + 5] = b & 255;
3061 else if(mode->colortype == LCT_GREY_ALPHA)
3063 unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3064 out[i * 4 + 0] = (grey >> 8) & 255;
3065 out[i * 4 + 1] = grey & 255;
3066 out[i * 4 + 2] = (a >> 8) & 255;
3067 out[i * 4 + 3] = a & 255;
3069 else if(mode->colortype == LCT_RGBA)
3071 out[i * 8 + 0] = (r >> 8) & 255;
3072 out[i * 8 + 1] = r & 255;
3073 out[i * 8 + 2] = (g >> 8) & 255;
3074 out[i * 8 + 3] = g & 255;
3075 out[i * 8 + 4] = (b >> 8) & 255;
3076 out[i * 8 + 5] = b & 255;
3077 out[i * 8 + 6] = (a >> 8) & 255;
3078 out[i * 8 + 7] = a & 255;
3081 return 0; /*no error*/
3084 /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3085 static unsigned getPixelColorRGBA8(unsigned char* r, unsigned char* g,
3086 unsigned char* b, unsigned char* a,
3087 const unsigned char* in, size_t i,
3088 const LodePNGColorMode* mode)
3090 if(mode->colortype == LCT_GREY)
3092 if(mode->bitdepth == 8)
3094 *r = *g = *b = in[i];
3095 if(mode->key_defined && *r == mode->key_r) *a = 0;
3096 else *a = 255;
3098 else if(mode->bitdepth == 16)
3100 *r = *g = *b = in[i * 2 + 0];
3101 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3102 else *a = 255;
3104 else
3106 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3107 size_t j = i * mode->bitdepth;
3108 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3109 *r = *g = *b = (value * 255) / highest;
3110 if(mode->key_defined && value == mode->key_r) *a = 0;
3111 else *a = 255;
3114 else if(mode->colortype == LCT_RGB)
3116 if(mode->bitdepth == 8)
3118 *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3119 if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3120 else *a = 255;
3122 else
3124 *r = in[i * 6 + 0];
3125 *g = in[i * 6 + 2];
3126 *b = in[i * 6 + 4];
3127 if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3128 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3129 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3130 else *a = 255;
3133 else if(mode->colortype == LCT_PALETTE)
3135 unsigned index;
3136 if(mode->bitdepth == 8) index = in[i];
3137 else
3139 size_t j = i * mode->bitdepth;
3140 index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3142 if(index >= mode->palettesize) return 47; /*index out of palette*/
3143 *r = mode->palette[index * 4 + 0];
3144 *g = mode->palette[index * 4 + 1];
3145 *b = mode->palette[index * 4 + 2];
3146 *a = mode->palette[index * 4 + 3];
3148 else if(mode->colortype == LCT_GREY_ALPHA)
3150 if(mode->bitdepth == 8)
3152 *r = *g = *b = in[i * 2 + 0];
3153 *a = in[i * 2 + 1];
3155 else
3157 *r = *g = *b = in[i * 4 + 0];
3158 *a = in[i * 4 + 2];
3161 else if(mode->colortype == LCT_RGBA)
3163 if(mode->bitdepth == 8)
3165 *r = in[i * 4 + 0];
3166 *g = in[i * 4 + 1];
3167 *b = in[i * 4 + 2];
3168 *a = in[i * 4 + 3];
3170 else
3172 *r = in[i * 8 + 0];
3173 *g = in[i * 8 + 2];
3174 *b = in[i * 8 + 4];
3175 *a = in[i * 8 + 6];
3179 return 0; /*no error*/
3182 /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3183 mode test cases, optimized to convert the colors much faster, when converting
3184 to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3185 enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3186 of the input buffer.*/
3187 static unsigned getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
3188 unsigned has_alpha, const unsigned char* in,
3189 const LodePNGColorMode* mode)
3191 unsigned num_channels = has_alpha ? 4 : 3;
3192 size_t i;
3193 if(mode->colortype == LCT_GREY)
3195 if(mode->bitdepth == 8)
3197 for(i = 0; i < numpixels; i++, buffer += num_channels)
3199 buffer[0] = buffer[1] = buffer[2] = in[i];
3200 if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
3203 else if(mode->bitdepth == 16)
3205 for(i = 0; i < numpixels; i++, buffer += num_channels)
3207 buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3208 if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
3211 else
3213 unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3214 size_t j = 0;
3215 for(i = 0; i < numpixels; i++, buffer += num_channels)
3217 unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3218 buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3219 if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
3223 else if(mode->colortype == LCT_RGB)
3225 if(mode->bitdepth == 8)
3227 for(i = 0; i < numpixels; i++, buffer += num_channels)
3229 buffer[0] = in[i * 3 + 0];
3230 buffer[1] = in[i * 3 + 1];
3231 buffer[2] = in[i * 3 + 2];
3232 if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
3233 && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
3236 else
3238 for(i = 0; i < numpixels; i++, buffer += num_channels)
3240 buffer[0] = in[i * 6 + 0];
3241 buffer[1] = in[i * 6 + 2];
3242 buffer[2] = in[i * 6 + 4];
3243 if(has_alpha) buffer[3] = mode->key_defined
3244 && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3245 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3246 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
3250 else if(mode->colortype == LCT_PALETTE)
3252 unsigned index;
3253 size_t j = 0;
3254 for(i = 0; i < numpixels; i++, buffer += num_channels)
3256 if(mode->bitdepth == 8) index = in[i];
3257 else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3258 if(index >= mode->palettesize) return 47; /*index out of palette*/
3259 buffer[0] = mode->palette[index * 4 + 0];
3260 buffer[1] = mode->palette[index * 4 + 1];
3261 buffer[2] = mode->palette[index * 4 + 2];
3262 if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
3265 else if(mode->colortype == LCT_GREY_ALPHA)
3267 if(mode->bitdepth == 8)
3269 for(i = 0; i < numpixels; i++, buffer += num_channels)
3271 buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3272 if(has_alpha) buffer[3] = in[i * 2 + 1];
3275 else
3277 for(i = 0; i < numpixels; i++, buffer += num_channels)
3279 buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3280 if(has_alpha) buffer[3] = in[i * 4 + 2];
3284 else if(mode->colortype == LCT_RGBA)
3286 if(mode->bitdepth == 8)
3288 for(i = 0; i < numpixels; i++, buffer += num_channels)
3290 buffer[0] = in[i * 4 + 0];
3291 buffer[1] = in[i * 4 + 1];
3292 buffer[2] = in[i * 4 + 2];
3293 if(has_alpha) buffer[3] = in[i * 4 + 3];
3296 else
3298 for(i = 0; i < numpixels; i++, buffer += num_channels)
3300 buffer[0] = in[i * 8 + 0];
3301 buffer[1] = in[i * 8 + 2];
3302 buffer[2] = in[i * 8 + 4];
3303 if(has_alpha) buffer[3] = in[i * 8 + 6];
3308 return 0; /*no error*/
3311 /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3312 given color type, but the given color type must be 16-bit itself.*/
3313 static unsigned getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3314 const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3316 if(mode->bitdepth != 16) return 85; /*error: this function only supports 16-bit input*/
3318 if(mode->colortype == LCT_GREY)
3320 *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3321 if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3322 else *a = 65535;
3324 else if(mode->colortype == LCT_RGB)
3326 *r = 256 * in[i * 6 + 0] + in[i * 6 + 1];
3327 *g = 256 * in[i * 6 + 2] + in[i * 6 + 3];
3328 *b = 256 * in[i * 6 + 4] + in[i * 6 + 5];
3329 if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3330 && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3331 && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3332 else *a = 65535;
3334 else if(mode->colortype == LCT_GREY_ALPHA)
3336 *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1];
3337 *a = 256 * in[i * 4 + 2] + in[i * 4 + 3];
3339 else if(mode->colortype == LCT_RGBA)
3341 *r = 256 * in[i * 8 + 0] + in[i * 8 + 1];
3342 *g = 256 * in[i * 8 + 2] + in[i * 8 + 3];
3343 *b = 256 * in[i * 8 + 4] + in[i * 8 + 5];
3344 *a = 256 * in[i * 8 + 6] + in[i * 8 + 7];
3346 else return 85; /*error: this function only supports 16-bit input, not palettes*/
3348 return 0; /*no error*/
3352 converts from any color type to 24-bit or 32-bit (later maybe more supported). return value = LodePNG error code
3353 the out buffer must have (w * h * bpp + 7) / 8 bytes, where bpp is the bits per pixel of the output color type
3354 (lodepng_get_bpp) for < 8 bpp images, there may _not_ be padding bits at the end of scanlines.
3356 unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3357 LodePNGColorMode* mode_out, LodePNGColorMode* mode_in,
3358 unsigned w, unsigned h)
3360 unsigned error = 0;
3361 size_t i;
3362 ColorTree tree;
3363 size_t numpixels = w * h;
3365 if(lodepng_color_mode_equal(mode_out, mode_in))
3367 size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3368 for(i = 0; i < numbytes; i++) out[i] = in[i];
3369 return error;
3372 if(mode_out->colortype == LCT_PALETTE)
3374 size_t palsize = 1 << mode_out->bitdepth;
3375 if(mode_out->palettesize < palsize) palsize = mode_out->palettesize;
3376 color_tree_init(&tree);
3377 for(i = 0; i < palsize; i++)
3379 unsigned char* p = &mode_out->palette[i * 4];
3380 color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
3384 if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
3386 for(i = 0; i < numpixels; i++)
3388 unsigned short r = 0, g = 0, b = 0, a = 0;
3389 error = getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3390 if(error) break;
3391 error = rgba16ToPixel(out, i, mode_out, r, g, b, a);
3392 if(error) break;
3395 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
3397 error = getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
3399 else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
3401 error = getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
3403 else
3405 unsigned char r = 0, g = 0, b = 0, a = 0;
3406 for(i = 0; i < numpixels; i++)
3408 error = getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3409 if(error) break;
3410 error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
3411 if(error) break;
3415 if(mode_out->colortype == LCT_PALETTE)
3417 color_tree_cleanup(&tree);
3420 return error;
3423 #ifdef LODEPNG_COMPILE_ENCODER
3425 typedef struct ColorProfile
3427 unsigned char sixteenbit; /*needs more than 8 bits per channel*/
3428 unsigned char sixteenbit_done;
3431 unsigned char colored; /*not greyscale*/
3432 unsigned char colored_done;
3434 unsigned char key; /*a color key is required, or more*/
3435 unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/
3436 unsigned short key_g;
3437 unsigned short key_b;
3438 unsigned char alpha; /*alpha channel, or alpha palette, required*/
3439 unsigned char alpha_done;
3441 unsigned numcolors;
3442 ColorTree tree; /*for listing the counted colors, up to 256*/
3443 unsigned char* palette; /*size 1024. Remember up to the first 256 RGBA colors*/
3444 unsigned maxnumcolors; /*if more than that amount counted*/
3445 unsigned char numcolors_done;
3447 unsigned greybits; /*amount of bits required for greyscale (1, 2, 4, 8). Does not take 16 bit into account.*/
3448 unsigned char greybits_done;
3450 } ColorProfile;
3452 static void color_profile_init(ColorProfile* profile, LodePNGColorMode* mode)
3454 profile->sixteenbit = 0;
3455 profile->sixteenbit_done = mode->bitdepth == 16 ? 0 : 1;
3457 profile->colored = 0;
3458 profile->colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
3460 profile->key = 0;
3461 profile->alpha = 0;
3462 profile->alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
3464 profile->numcolors = 0;
3465 color_tree_init(&profile->tree);
3466 profile->palette = (unsigned char*)mymalloc(1024);
3467 profile->maxnumcolors = 257;
3468 if(lodepng_get_bpp(mode) <= 8)
3470 int bpp = lodepng_get_bpp(mode);
3471 profile->maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
3473 profile->numcolors_done = 0;
3475 profile->greybits = 1;
3476 profile->greybits_done = lodepng_get_bpp(mode) == 1 ? 1 : 0;
3479 static void color_profile_cleanup(ColorProfile* profile)
3481 color_tree_cleanup(&profile->tree);
3482 myfree(profile->palette);
3485 /*function used for debug purposes with C++*/
3486 /*void printColorProfile(ColorProfile* p)
3488 std::cout << "sixteenbit: " << (int)p->sixteenbit << std::endl;
3489 std::cout << "sixteenbit_done: " << (int)p->sixteenbit_done << std::endl;
3490 std::cout << "colored: " << (int)p->colored << std::endl;
3491 std::cout << "colored_done: " << (int)p->colored_done << std::endl;
3492 std::cout << "key: " << (int)p->key << std::endl;
3493 std::cout << "key_r: " << (int)p->key_r << std::endl;
3494 std::cout << "key_g: " << (int)p->key_g << std::endl;
3495 std::cout << "key_b: " << (int)p->key_b << std::endl;
3496 std::cout << "alpha: " << (int)p->alpha << std::endl;
3497 std::cout << "alpha_done: " << (int)p->alpha_done << std::endl;
3498 std::cout << "numcolors: " << (int)p->numcolors << std::endl;
3499 std::cout << "maxnumcolors: " << (int)p->maxnumcolors << std::endl;
3500 std::cout << "numcolors_done: " << (int)p->numcolors_done << std::endl;
3501 std::cout << "greybits: " << (int)p->greybits << std::endl;
3502 std::cout << "greybits_done: " << (int)p->greybits_done << std::endl;
3505 /*Returns how many bits needed to represent given value (max 8 bit)*/
3506 unsigned getValueRequiredBits(unsigned short value)
3508 if(value == 0 || value == 255) return 1;
3509 /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3510 if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
3511 return 8;
3514 /*profile must already have been inited with mode.
3515 It's ok to set some parameters of profile to done already.*/
3516 static unsigned get_color_profile(ColorProfile* profile,
3517 const unsigned char* in, size_t numpixels,
3518 LodePNGColorMode* mode)
3520 unsigned error = 0;
3521 size_t i;
3523 if(mode->bitdepth == 16)
3525 for(i = 0; i < numpixels; i++)
3527 unsigned short r, g, b, a;
3528 error = getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3529 if(error) break;
3531 /*a color is considered good for 8-bit if the first byte and the second byte are equal,
3532 (so if it's divisible through 257), NOT necessarily if the second byte is 0*/
3533 if(!profile->sixteenbit_done
3534 && (((r & 255) != ((r >> 8) & 255))
3535 || ((g & 255) != ((g >> 8) & 255))
3536 || ((b & 255) != ((b >> 8) & 255))))
3538 profile->sixteenbit = 1;
3539 profile->sixteenbit_done = 1;
3540 profile->greybits_done = 1; /*greybits is not applicable anymore at 16-bit*/
3541 profile->numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3544 if(!profile->colored_done && (r != g || r != b))
3546 profile->colored = 1;
3547 profile->colored_done = 1;
3548 profile->greybits_done = 1; /*greybits is not applicable anymore*/
3551 if(!profile->alpha_done && a != 255)
3553 if(a == 0 && !(profile->key && (r != profile->key_r || g != profile->key_g || b != profile->key_b)))
3555 if(!profile->key)
3557 profile->key = 1;
3558 profile->key_r = r;
3559 profile->key_g = g;
3560 profile->key_b = b;
3563 else
3565 profile->alpha = 1;
3566 profile->alpha_done = 1;
3567 profile->greybits_done = 1; /*greybits is not applicable anymore*/
3571 if(!profile->greybits_done)
3573 /*assuming 8-bit r, this test does not care about 16-bit*/
3574 unsigned bits = getValueRequiredBits(r);
3575 if(bits > profile->greybits) profile->greybits = bits;
3576 if(profile->greybits >= 8) profile->greybits_done = 1;
3579 if(!profile->numcolors_done)
3581 /*assuming 8-bit rgba, this test does not care about 16-bit*/
3582 if(!color_tree_has(&profile->tree, (unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a))
3584 color_tree_add(&profile->tree, (unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a,
3585 profile->numcolors);
3586 if(profile->numcolors < 256)
3588 unsigned char* p = profile->palette;
3589 unsigned i = profile->numcolors;
3590 p[i * 4 + 0] = (unsigned char)r;
3591 p[i * 4 + 1] = (unsigned char)g;
3592 p[i * 4 + 2] = (unsigned char)b;
3593 p[i * 4 + 3] = (unsigned char)a;
3595 profile->numcolors++;
3596 if(profile->numcolors >= profile->maxnumcolors) profile->numcolors_done = 1;
3600 if(profile->alpha_done && profile->numcolors_done
3601 && profile->colored_done && profile->sixteenbit_done && profile->greybits_done)
3603 break;
3607 else
3609 for(i = 0; i < numpixels; i++)
3611 unsigned char r = 0, g = 0, b = 0, a = 0;
3612 error = getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
3613 if(error) break;
3615 if(!profile->colored_done && (r != g || r != b))
3617 profile->colored = 1;
3618 profile->colored_done = 1;
3619 profile->greybits_done = 1; /*greybits is not applicable anymore*/
3622 if(!profile->alpha_done && a != 255)
3624 if(a == 0 && !(profile->key && (r != profile->key_r || g != profile->key_g || b != profile->key_b)))
3626 if(!profile->key)
3628 profile->key = 1;
3629 profile->key_r = r;
3630 profile->key_g = g;
3631 profile->key_b = b;
3634 else
3636 profile->alpha = 1;
3637 profile->alpha_done = 1;
3638 profile->greybits_done = 1; /*greybits is not applicable anymore*/
3642 if(!profile->greybits_done)
3644 unsigned bits = getValueRequiredBits(r);
3645 if(bits > profile->greybits) profile->greybits = bits;
3646 if(profile->greybits >= 8) profile->greybits_done = 1;
3649 if(!profile->numcolors_done)
3651 if(!color_tree_has(&profile->tree, r, g, b, a))
3654 color_tree_add(&profile->tree, r, g, b, a, profile->numcolors);
3655 if(profile->numcolors < 256)
3657 unsigned char* p = profile->palette;
3658 unsigned i = profile->numcolors;
3659 p[i * 4 + 0] = r;
3660 p[i * 4 + 1] = g;
3661 p[i * 4 + 2] = b;
3662 p[i * 4 + 3] = a;
3664 profile->numcolors++;
3665 if(profile->numcolors >= profile->maxnumcolors) profile->numcolors_done = 1;
3669 if(profile->alpha_done && profile->numcolors_done && profile->colored_done && profile->greybits_done)
3671 break;
3676 /*make the profile's key always 16-bit for consistency*/
3677 if(mode->bitdepth < 16)
3679 /*repeat each byte twice*/
3680 profile->key_r *= 257;
3681 profile->key_g *= 257;
3682 profile->key_b *= 257;
3685 return error;
3688 /*updates values of mode with a potentially smaller color model. mode_out should
3689 contain the user chosen color model, but will be overwritten with the new chosen one.*/
3690 static unsigned doAutoChooseColor(LodePNGColorMode* mode_out,
3691 const unsigned char* image, unsigned w, unsigned h, LodePNGColorMode* mode_in,
3692 LodePNGAutoConvert auto_convert)
3694 ColorProfile profile;
3695 unsigned error = 0;
3696 int no_nibbles = auto_convert == LAC_AUTO_NO_NIBBLES || auto_convert == LAC_AUTO_NO_NIBBLES_NO_PALETTE;
3697 int no_palette = auto_convert == LAC_AUTO_NO_PALETTE || auto_convert == LAC_AUTO_NO_NIBBLES_NO_PALETTE;
3699 if(auto_convert == LAC_ALPHA)
3701 if(mode_out->colortype != LCT_RGBA && mode_out->colortype != LCT_GREY_ALPHA) return 0;
3704 color_profile_init(&profile, mode_in);
3705 if(auto_convert == LAC_ALPHA)
3707 profile.colored_done = 1;
3708 profile.greybits_done = 1;
3709 profile.numcolors_done = 1;
3710 profile.sixteenbit_done = 1;
3712 error = get_color_profile(&profile, image, w * h, mode_in);
3714 if(!error && auto_convert == LAC_ALPHA)
3716 if(!profile.alpha)
3718 mode_out->colortype = (mode_out->colortype == LCT_RGBA ? LCT_RGB : LCT_GREY);
3721 else if(!error && auto_convert != LAC_ALPHA)
3723 mode_out->key_defined = 0;
3725 if(profile.sixteenbit)
3727 mode_out->bitdepth = 16;
3728 if(profile.alpha)
3730 mode_out->colortype = profile.colored ? LCT_RGBA : LCT_GREY_ALPHA;
3732 else
3734 mode_out->colortype = profile.colored ? LCT_RGB : LCT_GREY;
3735 if(profile.key)
3737 mode_out->key_defined = 1;
3738 mode_out->key_r = profile.key_r;
3739 mode_out->key_g = profile.key_g;
3740 mode_out->key_b = profile.key_b;
3744 else /*less than 16 bits per channel*/
3746 /*don't add palette overhead if image hasn't got a lot of pixels*/
3747 unsigned n = profile.numcolors;
3748 int palette_ok = !no_palette && n <= 256 && (n * 2 < w * h);
3749 unsigned palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
3750 int grey_ok = !profile.colored && !profile.alpha; /*grey without alpha, with potentially low bits*/
3751 if(palette_ok || grey_ok)
3753 if(!palette_ok || (grey_ok && profile.greybits <= palettebits))
3755 mode_out->colortype = LCT_GREY;
3756 mode_out->bitdepth = profile.greybits;
3757 if(profile.key)
3759 unsigned keyval = profile.key_r;
3760 keyval &= (profile.greybits - 1); /*same subgroup of bits repeated, so taking right bits is fine*/
3761 mode_out->key_defined = 1;
3762 mode_out->key_r = keyval;
3763 mode_out->key_g = keyval;
3764 mode_out->key_b = keyval;
3767 else
3769 /*fill in the palette*/
3770 unsigned i;
3771 unsigned char* p = profile.palette;
3772 for(i = 0; i < profile.numcolors; i++)
3774 error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
3775 if(error) break;
3778 mode_out->colortype = LCT_PALETTE;
3779 mode_out->bitdepth = palettebits;
3782 else /*8-bit per channel*/
3784 mode_out->bitdepth = 8;
3785 if(profile.alpha)
3787 mode_out->colortype = profile.colored ? LCT_RGBA : LCT_GREY_ALPHA;
3789 else
3791 mode_out->colortype = profile.colored ? LCT_RGB : LCT_GREY /*LCT_GREY normally won't occur, already done earlier*/;
3792 if(profile.key)
3794 mode_out->key_defined = 1;
3795 mode_out->key_r = profile.key_r % 256;
3796 mode_out->key_g = profile.key_g % 256;
3797 mode_out->key_b = profile.key_b % 256;
3804 color_profile_cleanup(&profile);
3806 if(mode_out->colortype == LCT_PALETTE && mode_in->palettesize == mode_out->palettesize)
3808 /*In this case keep the palette order of the input, so that the user can choose an optimal one*/
3809 size_t i;
3810 for(i = 0; i < mode_in->palettesize * 4; i++)
3812 mode_out->palette[i] = mode_in->palette[i];
3816 if(no_nibbles && mode_out->bitdepth < 8)
3818 /*palette can keep its small amount of colors, as long as no indices use it*/
3819 mode_out->bitdepth = 8;
3822 return error;
3825 #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3828 Paeth predicter, used by PNG filter type 4
3829 The parameters are of type short, but should come from unsigned chars, the shorts
3830 are only needed to make the paeth calculation correct.
3832 static unsigned char paethPredictor(short a, short b, short c)
3834 short pa = abs(b - c);
3835 short pb = abs(a - c);
3836 short pc = abs(a + b - c - c);
3838 if(pc < pa && pc < pb) return (unsigned char)c;
3839 else if(pb < pa) return (unsigned char)b;
3840 else return (unsigned char)a;
3843 /*shared values used by multiple Adam7 related functions*/
3845 static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3846 static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3847 static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3848 static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3851 Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3852 passw: output containing the width of the 7 passes
3853 passh: output containing the height of the 7 passes
3854 filter_passstart: output containing the index of the start and end of each
3855 reduced image with filter bytes
3856 padded_passstart output containing the index of the start and end of each
3857 reduced image when without filter bytes but with padded scanlines
3858 passstart: output containing the index of the start and end of each reduced
3859 image without padding between scanlines, but still padding between the images
3860 w, h: width and height of non-interlaced image
3861 bpp: bits per pixel
3862 "padded" is only relevant if bpp is less than 8 and a scanline or image does not
3863 end at a full byte
3865 static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
3866 size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
3868 /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3869 unsigned i;
3871 /*calculate width and height in pixels of each pass*/
3872 for(i = 0; i < 7; i++)
3874 passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
3875 passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
3876 if(passw[i] == 0) passh[i] = 0;
3877 if(passh[i] == 0) passw[i] = 0;
3880 filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
3881 for(i = 0; i < 7; i++)
3883 /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3884 filter_passstart[i + 1] = filter_passstart[i]
3885 + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
3886 /*bits padded if needed to fill full byte at end of each scanline*/
3887 padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
3888 /*only padded at end of reduced image*/
3889 passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
3893 #ifdef LODEPNG_COMPILE_DECODER
3895 /* ////////////////////////////////////////////////////////////////////////// */
3896 /* / PNG Decoder / */
3897 /* ////////////////////////////////////////////////////////////////////////// */
3899 /*read the information from the header and store it in the LodePNGInfo. return value is error*/
3900 unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
3901 const unsigned char* in, size_t insize)
3903 LodePNGInfo* info = &state->info_png;
3904 if(insize == 0 || in == 0)
3906 CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
3908 if(insize < 29)
3910 CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
3913 /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3914 lodepng_info_cleanup(info);
3915 lodepng_info_init(info);
3917 if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
3918 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
3920 CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3922 if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R')
3924 CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
3927 /*read the values given in the header*/
3928 *w = lodepng_read32bitInt(&in[16]);
3929 *h = lodepng_read32bitInt(&in[20]);
3930 info->color.bitdepth = in[24];
3931 info->color.colortype = (LodePNGColorType)in[25];
3932 info->compression_method = in[26];
3933 info->filter_method = in[27];
3934 info->interlace_method = in[28];
3936 if(!state->decoder.ignore_crc)
3938 unsigned CRC = lodepng_read32bitInt(&in[29]);
3939 unsigned checksum = lodepng_crc32(&in[12], 17);
3940 if(CRC != checksum)
3942 CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
3946 /*error: only compression method 0 is allowed in the specification*/
3947 if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
3948 /*error: only filter method 0 is allowed in the specification*/
3949 if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
3950 /*error: only interlace methods 0 and 1 exist in the specification*/
3951 if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
3953 state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
3954 return state->error;
3957 static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
3958 size_t bytewidth, unsigned char filterType, size_t length)
3961 For PNG filter method 0
3962 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
3963 the filter works byte per byte (bytewidth = 1)
3964 precon is the previous unfiltered scanline, recon the result, scanline the current one
3965 the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
3966 recon and scanline MAY be the same memory address! precon must be disjoint.
3969 size_t i;
3970 switch(filterType)
3972 case 0:
3973 for(i = 0; i < length; i++) recon[i] = scanline[i];
3974 break;
3975 case 1:
3976 for(i = 0; i < bytewidth; i++) recon[i] = scanline[i];
3977 for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth];
3978 break;
3979 case 2:
3980 if(precon)
3982 for(i = 0; i < length; i++) recon[i] = scanline[i] + precon[i];
3984 else
3986 for(i = 0; i < length; i++) recon[i] = scanline[i];
3988 break;
3989 case 3:
3990 if(precon)
3992 for(i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2;
3993 for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
3995 else
3997 for(i = 0; i < bytewidth; i++) recon[i] = scanline[i];
3998 for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2;
4000 break;
4001 case 4:
4002 if(precon)
4004 for(i = 0; i < bytewidth; i++)
4006 recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
4008 for(i = bytewidth; i < length; i++)
4010 recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
4013 else
4015 for(i = 0; i < bytewidth; i++)
4017 recon[i] = scanline[i];
4019 for(i = bytewidth; i < length; i++)
4021 /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
4022 recon[i] = (scanline[i] + recon[i - bytewidth]);
4025 break;
4026 default: return 36; /*error: unexisting filter type given*/
4028 return 0;
4031 static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4034 For PNG filter method 0
4035 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
4036 out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
4037 w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
4038 in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
4041 unsigned y;
4042 unsigned char* prevline = 0;
4044 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
4045 size_t bytewidth = (bpp + 7) / 8;
4046 size_t linebytes = (w * bpp + 7) / 8;
4048 for(y = 0; y < h; y++)
4050 size_t outindex = linebytes * y;
4051 size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
4052 unsigned char filterType = in[inindex];
4054 CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
4056 prevline = &out[outindex];
4059 return 0;
4063 in: Adam7 interlaced image, with no padding bits between scanlines, but between
4064 reduced images so that each reduced image starts at a byte.
4065 out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4066 bpp: bits per pixel
4067 out has the following size in bits: w * h * bpp.
4068 in is possibly bigger due to padding bits between reduced images.
4069 out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4070 (because that's likely a little bit faster)
4071 NOTE: comments about padding bits are only relevant if bpp < 8
4073 static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4075 unsigned passw[7], passh[7];
4076 size_t filter_passstart[8], padded_passstart[8], passstart[8];
4077 unsigned i;
4079 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4081 if(bpp >= 8)
4083 for(i = 0; i < 7; i++)
4085 unsigned x, y, b;
4086 size_t bytewidth = bpp / 8;
4087 for(y = 0; y < passh[i]; y++)
4088 for(x = 0; x < passw[i]; x++)
4090 size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4091 size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
4092 for(b = 0; b < bytewidth; b++)
4094 out[pixeloutstart + b] = in[pixelinstart + b];
4099 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4101 for(i = 0; i < 7; i++)
4103 unsigned x, y, b;
4104 unsigned ilinebits = bpp * passw[i];
4105 unsigned olinebits = bpp * w;
4106 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4107 for(y = 0; y < passh[i]; y++)
4108 for(x = 0; x < passw[i]; x++)
4110 ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4111 obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
4112 for(b = 0; b < bpp; b++)
4114 unsigned char bit = readBitFromReversedStream(&ibp, in);
4115 /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4116 setBitOfReversedStream0(&obp, out, bit);
4123 static void removePaddingBits(unsigned char* out, const unsigned char* in,
4124 size_t olinebits, size_t ilinebits, unsigned h)
4127 After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4128 to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4129 for the Adam7 code, the color convert code and the output to the user.
4130 in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4131 have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4132 also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4133 only useful if (ilinebits - olinebits) is a value in the range 1..7
4135 unsigned y;
4136 size_t diff = ilinebits - olinebits;
4137 size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4138 for(y = 0; y < h; y++)
4140 size_t x;
4141 for(x = 0; x < olinebits; x++)
4143 unsigned char bit = readBitFromReversedStream(&ibp, in);
4144 setBitOfReversedStream(&obp, out, bit);
4146 ibp += diff;
4150 /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4151 the IDAT chunks (with filter index bytes and possible padding bits)
4152 return value is error*/
4153 static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4154 unsigned w, unsigned h, const LodePNGInfo* info_png)
4157 This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4158 Steps:
4159 *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4160 *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4161 NOTE: the in buffer will be overwritten with intermediate data!
4163 unsigned bpp = lodepng_get_bpp(&info_png->color);
4164 if(bpp == 0) return 31; /*error: invalid colortype*/
4166 if(info_png->interlace_method == 0)
4168 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
4170 CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4171 removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
4173 /*we can immediatly filter into the out buffer, no other steps needed*/
4174 else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4176 else /*interlace_method is 1 (Adam7)*/
4178 unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4179 unsigned i;
4181 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4183 for(i = 0; i < 7; i++)
4185 CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4186 /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4187 move bytes instead of bits or move not at all*/
4188 if(bpp < 8)
4190 /*remove padding bits in scanlines; after this there still may be padding
4191 bits between the different reduced images: each reduced image still starts nicely at a byte*/
4192 removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4193 ((passw[i] * bpp + 7) / 8) * 8, passh[i]);
4197 Adam7_deinterlace(out, in, w, h, bpp);
4200 return 0;
4203 static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4205 unsigned pos = 0, i;
4206 if(color->palette) myfree(color->palette);
4207 color->palettesize = chunkLength / 3;
4208 color->palette = (unsigned char*)mymalloc(4 * color->palettesize);
4209 if(!color->palette && color->palettesize)
4211 color->palettesize = 0;
4212 return 83; /*alloc fail*/
4214 if(color->palettesize > 256) return 38; /*error: palette too big*/
4216 for(i = 0; i < color->palettesize; i++)
4218 color->palette[4 * i + 0] = data[pos++]; /*R*/
4219 color->palette[4 * i + 1] = data[pos++]; /*G*/
4220 color->palette[4 * i + 2] = data[pos++]; /*B*/
4221 color->palette[4 * i + 3] = 255; /*alpha*/
4224 return 0; /* OK */
4227 static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4229 unsigned i;
4230 if(color->colortype == LCT_PALETTE)
4232 /*error: more alpha values given than there are palette entries*/
4233 if(chunkLength > color->palettesize) return 38;
4235 for(i = 0; i < chunkLength; i++) color->palette[4 * i + 3] = data[i];
4237 else if(color->colortype == LCT_GREY)
4239 /*error: this chunk must be 2 bytes for greyscale image*/
4240 if(chunkLength != 2) return 30;
4242 color->key_defined = 1;
4243 color->key_r = color->key_g = color->key_b = 256 * data[0] + data[1];
4245 else if(color->colortype == LCT_RGB)
4247 /*error: this chunk must be 6 bytes for RGB image*/
4248 if(chunkLength != 6) return 41;
4250 color->key_defined = 1;
4251 color->key_r = 256 * data[0] + data[1];
4252 color->key_g = 256 * data[2] + data[3];
4253 color->key_b = 256 * data[4] + data[5];
4255 else return 42; /*error: tRNS chunk not allowed for other color models*/
4257 return 0; /* OK */
4261 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4262 /*background color chunk (bKGD)*/
4263 static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4265 if(info->color.colortype == LCT_PALETTE)
4267 /*error: this chunk must be 1 byte for indexed color image*/
4268 if(chunkLength != 1) return 43;
4270 info->background_defined = 1;
4271 info->background_r = info->background_g = info->background_b = data[0];
4273 else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
4275 /*error: this chunk must be 2 bytes for greyscale image*/
4276 if(chunkLength != 2) return 44;
4278 info->background_defined = 1;
4279 info->background_r = info->background_g = info->background_b
4280 = 256 * data[0] + data[1];
4282 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
4284 /*error: this chunk must be 6 bytes for greyscale image*/
4285 if(chunkLength != 6) return 45;
4287 info->background_defined = 1;
4288 info->background_r = 256 * data[0] + data[1];
4289 info->background_g = 256 * data[2] + data[3];
4290 info->background_b = 256 * data[4] + data[5];
4293 return 0; /* OK */
4296 /*text chunk (tEXt)*/
4297 static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4299 unsigned error = 0;
4300 char *key = 0, *str = 0;
4301 unsigned i;
4303 while(!error) /*not really a while loop, only used to break on error*/
4305 unsigned length, string2_begin;
4307 length = 0;
4308 while(length < chunkLength && data[length] != 0) length++;
4309 /*even though it's not allowed by the standard, no error is thrown if
4310 there's no null termination char, if the text is empty*/
4311 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4313 key = (char*)mymalloc(length + 1);
4314 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4316 key[length] = 0;
4317 for(i = 0; i < length; i++) key[i] = data[i];
4319 string2_begin = length + 1; /*skip keyword null terminator*/
4321 length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
4322 str = (char*)mymalloc(length + 1);
4323 if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
4325 str[length] = 0;
4326 for(i = 0; i < length; i++) str[i] = data[string2_begin + i];
4328 error = lodepng_add_text(info, key, str);
4330 break;
4333 myfree(key);
4334 myfree(str);
4336 return error;
4339 /*compressed text chunk (zTXt)*/
4340 static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4341 const unsigned char* data, size_t chunkLength)
4343 unsigned error = 0;
4344 unsigned i;
4346 unsigned length, string2_begin;
4347 char *key = 0;
4348 ucvector decoded;
4350 ucvector_init(&decoded);
4352 while(!error) /*not really a while loop, only used to break on error*/
4354 for(length = 0; length < chunkLength && data[length] != 0; length++) ;
4355 if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4356 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4358 key = (char*)mymalloc(length + 1);
4359 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4361 key[length] = 0;
4362 for(i = 0; i < length; i++) key[i] = data[i];
4364 if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4366 string2_begin = length + 2;
4367 if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4369 length = chunkLength - string2_begin;
4370 /*will fail if zlib error, e.g. if length is too small*/
4371 error = zlib_decompress(&decoded.data, &decoded.size,
4372 (unsigned char*)(&data[string2_begin]),
4373 length, zlibsettings);
4374 if(error) break;
4375 ucvector_push_back(&decoded, 0);
4377 error = lodepng_add_text(info, key, (char*)decoded.data);
4379 break;
4382 myfree(key);
4383 ucvector_cleanup(&decoded);
4385 return error;
4388 /*international text chunk (iTXt)*/
4389 static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4390 const unsigned char* data, size_t chunkLength)
4392 unsigned error = 0;
4393 unsigned i;
4395 unsigned length, begin, compressed;
4396 char *key = 0, *langtag = 0, *transkey = 0;
4397 ucvector decoded;
4398 ucvector_init(&decoded);
4400 while(!error) /*not really a while loop, only used to break on error*/
4402 /*Quick check if the chunk length isn't too small. Even without check
4403 it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4404 if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
4406 /*read the key*/
4407 for(length = 0; length < chunkLength && data[length] != 0; length++) ;
4408 if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
4409 if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4411 key = (char*)mymalloc(length + 1);
4412 if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4414 key[length] = 0;
4415 for(i = 0; i < length; i++) key[i] = data[i];
4417 /*read the compression method*/
4418 compressed = data[length + 1];
4419 if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4421 /*even though it's not allowed by the standard, no error is thrown if
4422 there's no null termination char, if the text is empty for the next 3 texts*/
4424 /*read the langtag*/
4425 begin = length + 3;
4426 length = 0;
4427 for(i = begin; i < chunkLength && data[i] != 0; i++) length++;
4429 langtag = (char*)mymalloc(length + 1);
4430 if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
4432 langtag[length] = 0;
4433 for(i = 0; i < length; i++) langtag[i] = data[begin + i];
4435 /*read the transkey*/
4436 begin += length + 1;
4437 length = 0;
4438 for(i = begin; i < chunkLength && data[i] != 0; i++) length++;
4440 transkey = (char*)mymalloc(length + 1);
4441 if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
4443 transkey[length] = 0;
4444 for(i = 0; i < length; i++) transkey[i] = data[begin + i];
4446 /*read the actual text*/
4447 begin += length + 1;
4449 length = chunkLength < begin ? 0 : chunkLength - begin;
4451 if(compressed)
4453 /*will fail if zlib error, e.g. if length is too small*/
4454 error = zlib_decompress(&decoded.data, &decoded.size,
4455 (unsigned char*)(&data[begin]),
4456 length, zlibsettings);
4457 if(error) break;
4458 if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
4459 ucvector_push_back(&decoded, 0);
4461 else
4463 if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
4465 decoded.data[length] = 0;
4466 for(i = 0; i < length; i++) decoded.data[i] = data[begin + i];
4469 error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
4471 break;
4474 myfree(key);
4475 myfree(langtag);
4476 myfree(transkey);
4477 ucvector_cleanup(&decoded);
4479 return error;
4482 static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4484 if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
4486 info->time_defined = 1;
4487 info->time.year = 256 * data[0] + data[+ 1];
4488 info->time.month = data[2];
4489 info->time.day = data[3];
4490 info->time.hour = data[4];
4491 info->time.minute = data[5];
4492 info->time.second = data[6];
4494 return 0; /* OK */
4497 static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4499 if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
4501 info->phys_defined = 1;
4502 info->phys_x = 16777216 * data[0] + 65536 * data[1] + 256 * data[2] + data[3];
4503 info->phys_y = 16777216 * data[4] + 65536 * data[5] + 256 * data[6] + data[7];
4504 info->phys_unit = data[8];
4506 return 0; /* OK */
4508 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4510 /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4511 static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
4512 LodePNGState* state,
4513 const unsigned char* in, size_t insize)
4515 unsigned char IEND = 0;
4516 const unsigned char* chunk;
4517 size_t i;
4518 ucvector idat; /*the data from idat chunks*/
4520 /*for unknown chunk order*/
4521 unsigned unknown = 0;
4522 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4523 unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4524 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4526 /*provide some proper output values if error will happen*/
4527 *out = 0;
4529 state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
4530 if(state->error) return;
4532 ucvector_init(&idat);
4533 chunk = &in[33]; /*first byte of the first chunk after the header*/
4535 /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4536 IDAT data is put at the start of the in buffer*/
4537 while(!IEND && !state->error)
4539 unsigned chunkLength;
4540 const unsigned char* data; /*the data in the chunk*/
4542 /*error: size of the in buffer too small to contain next chunk*/
4543 if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
4545 /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4546 chunkLength = lodepng_chunk_length(chunk);
4547 /*error: chunk length larger than the max PNG chunk size*/
4548 if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
4550 if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
4552 CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
4555 data = lodepng_chunk_data_const(chunk);
4557 /*IDAT chunk, containing compressed image data*/
4558 if(lodepng_chunk_type_equals(chunk, "IDAT"))
4560 size_t oldsize = idat.size;
4561 if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4562 for(i = 0; i < chunkLength; i++) idat.data[oldsize + i] = data[i];
4563 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4564 critical_pos = 3;
4565 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4567 /*IEND chunk*/
4568 else if(lodepng_chunk_type_equals(chunk, "IEND"))
4570 IEND = 1;
4572 /*palette chunk (PLTE)*/
4573 else if(lodepng_chunk_type_equals(chunk, "PLTE"))
4575 state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
4576 if(state->error) break;
4577 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4578 critical_pos = 2;
4579 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4581 /*palette transparency chunk (tRNS)*/
4582 else if(lodepng_chunk_type_equals(chunk, "tRNS"))
4584 state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
4585 if(state->error) break;
4587 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4588 /*background color chunk (bKGD)*/
4589 else if(lodepng_chunk_type_equals(chunk, "bKGD"))
4591 state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
4592 if(state->error) break;
4594 /*text chunk (tEXt)*/
4595 else if(lodepng_chunk_type_equals(chunk, "tEXt"))
4597 if(state->decoder.read_text_chunks)
4599 state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
4600 if(state->error) break;
4603 /*compressed text chunk (zTXt)*/
4604 else if(lodepng_chunk_type_equals(chunk, "zTXt"))
4606 if(state->decoder.read_text_chunks)
4608 state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4609 if(state->error) break;
4612 /*international text chunk (iTXt)*/
4613 else if(lodepng_chunk_type_equals(chunk, "iTXt"))
4615 if(state->decoder.read_text_chunks)
4617 state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4618 if(state->error) break;
4621 else if(lodepng_chunk_type_equals(chunk, "tIME"))
4623 state->error = readChunk_tIME(&state->info_png, data, chunkLength);
4624 if(state->error) break;
4626 else if(lodepng_chunk_type_equals(chunk, "pHYs"))
4628 state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
4629 if(state->error) break;
4631 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4632 else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4634 /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4635 if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
4637 unknown = 1;
4638 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4639 if(state->decoder.remember_unknown_chunks)
4641 state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
4642 &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
4643 if(state->error) break;
4645 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4648 if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
4650 if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
4653 if(!IEND) chunk = lodepng_chunk_next_const(chunk);
4656 if(!state->error)
4658 ucvector scanlines;
4659 ucvector_init(&scanlines);
4661 /*maximum final image length is already reserved in the vector's length - this is not really necessary*/
4662 if(!ucvector_resize(&scanlines, lodepng_get_raw_size(*w, *h, &state->info_png.color) + *h))
4664 state->error = 83; /*alloc fail*/
4666 if(!state->error)
4668 /*decompress with the Zlib decompressor*/
4669 state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
4670 idat.size, &state->decoder.zlibsettings);
4673 if(!state->error)
4675 ucvector outv;
4676 ucvector_init(&outv);
4677 if(!ucvector_resizev(&outv,
4678 lodepng_get_raw_size(*w, *h, &state->info_png.color), 0)) state->error = 83; /*alloc fail*/
4679 if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png);
4680 *out = outv.data;
4682 ucvector_cleanup(&scanlines);
4685 ucvector_cleanup(&idat);
4688 unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
4689 LodePNGState* state,
4690 const unsigned char* in, size_t insize)
4692 *out = 0;
4693 decodeGeneric(out, w, h, state, in, insize);
4694 if(state->error) return state->error;
4695 if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
4697 /*same color type, no copying or converting of data needed*/
4698 /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4699 the raw image has to the end user*/
4700 if(!state->decoder.color_convert)
4702 state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
4703 if(state->error) return state->error;
4706 else
4708 /*color conversion needed; sort of copy of the data*/
4709 unsigned char* data = *out;
4710 size_t outsize;
4712 /*TODO: check if this works according to the statement in the documentation: "The converter can convert
4713 from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4714 if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
4715 && !(state->info_raw.bitdepth == 8))
4717 return 56; /*unsupported color mode conversion*/
4720 outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
4721 *out = (unsigned char*)mymalloc(outsize);
4722 if(!(*out))
4724 state->error = 83; /*alloc fail*/
4726 else state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h);
4727 myfree(data);
4729 return state->error;
4732 unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
4733 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
4735 unsigned error;
4736 LodePNGState state;
4737 lodepng_state_init(&state);
4738 state.info_raw.colortype = colortype;
4739 state.info_raw.bitdepth = bitdepth;
4740 error = lodepng_decode(out, w, h, &state, in, insize);
4741 lodepng_state_cleanup(&state);
4742 return error;
4745 unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4747 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
4750 unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4752 return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
4755 #ifdef LODEPNG_COMPILE_DISK
4756 unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
4757 LodePNGColorType colortype, unsigned bitdepth)
4759 unsigned char* buffer;
4760 size_t buffersize;
4761 unsigned error;
4762 error = lodepng_load_file(&buffer, &buffersize, filename);
4763 if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
4764 myfree(buffer);
4765 return error;
4768 unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4770 return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
4773 unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4775 return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
4777 #endif /*LODEPNG_COMPILE_DISK*/
4779 void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
4781 settings->color_convert = 1;
4782 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4783 settings->read_text_chunks = 1;
4784 settings->remember_unknown_chunks = 0;
4785 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4786 settings->ignore_crc = 0;
4787 lodepng_decompress_settings_init(&settings->zlibsettings);
4790 #endif /*LODEPNG_COMPILE_DECODER*/
4792 #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4794 void lodepng_state_init(LodePNGState* state)
4796 #ifdef LODEPNG_COMPILE_DECODER
4797 lodepng_decoder_settings_init(&state->decoder);
4798 #endif /*LODEPNG_COMPILE_DECODER*/
4799 #ifdef LODEPNG_COMPILE_ENCODER
4800 lodepng_encoder_settings_init(&state->encoder);
4801 #endif /*LODEPNG_COMPILE_ENCODER*/
4802 lodepng_color_mode_init(&state->info_raw);
4803 lodepng_info_init(&state->info_png);
4804 state->error = 1;
4807 void lodepng_state_cleanup(LodePNGState* state)
4809 lodepng_color_mode_cleanup(&state->info_raw);
4810 lodepng_info_cleanup(&state->info_png);
4813 void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
4815 lodepng_state_cleanup(dest);
4816 *dest = *source;
4817 lodepng_color_mode_init(&dest->info_raw);
4818 lodepng_info_init(&dest->info_png);
4819 dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
4820 dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
4823 #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4825 #ifdef LODEPNG_COMPILE_ENCODER
4827 /* ////////////////////////////////////////////////////////////////////////// */
4828 /* / PNG Encoder / */
4829 /* ////////////////////////////////////////////////////////////////////////// */
4831 /*chunkName must be string of 4 characters*/
4832 static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
4834 CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
4835 out->allocsize = out->size; /*fix the allocsize again*/
4836 return 0;
4839 static void writeSignature(ucvector* out)
4841 /*8 bytes PNG signature, aka the magic bytes*/
4842 ucvector_push_back(out, 137);
4843 ucvector_push_back(out, 80);
4844 ucvector_push_back(out, 78);
4845 ucvector_push_back(out, 71);
4846 ucvector_push_back(out, 13);
4847 ucvector_push_back(out, 10);
4848 ucvector_push_back(out, 26);
4849 ucvector_push_back(out, 10);
4852 static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
4853 LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
4855 unsigned error = 0;
4856 ucvector header;
4857 ucvector_init(&header);
4859 lodepng_add32bitInt(&header, w); /*width*/
4860 lodepng_add32bitInt(&header, h); /*height*/
4861 ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
4862 ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
4863 ucvector_push_back(&header, 0); /*compression method*/
4864 ucvector_push_back(&header, 0); /*filter method*/
4865 ucvector_push_back(&header, interlace_method); /*interlace method*/
4867 error = addChunk(out, "IHDR", header.data, header.size);
4868 ucvector_cleanup(&header);
4870 return error;
4873 static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
4875 unsigned error = 0;
4876 size_t i;
4877 ucvector PLTE;
4878 ucvector_init(&PLTE);
4879 for(i = 0; i < info->palettesize * 4; i++)
4881 /*add all channels except alpha channel*/
4882 if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
4884 error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
4885 ucvector_cleanup(&PLTE);
4887 return error;
4890 static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
4892 unsigned error = 0;
4893 size_t i;
4894 ucvector tRNS;
4895 ucvector_init(&tRNS);
4896 if(info->colortype == LCT_PALETTE)
4898 size_t amount = info->palettesize;
4899 /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4900 for(i = info->palettesize; i > 0; i--)
4902 if(info->palette[4 * (i - 1) + 3] == 255) amount--;
4903 else break;
4905 /*add only alpha channel*/
4906 for(i = 0; i < amount; i++) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
4908 else if(info->colortype == LCT_GREY)
4910 if(info->key_defined)
4912 ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4913 ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4916 else if(info->colortype == LCT_RGB)
4918 if(info->key_defined)
4920 ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4921 ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4922 ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256));
4923 ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256));
4924 ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256));
4925 ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256));
4929 error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
4930 ucvector_cleanup(&tRNS);
4932 return error;
4935 static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
4936 LodePNGCompressSettings* zlibsettings)
4938 ucvector zlibdata;
4939 unsigned error = 0;
4941 /*compress with the Zlib compressor*/
4942 ucvector_init(&zlibdata);
4943 error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
4944 if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
4945 ucvector_cleanup(&zlibdata);
4947 return error;
4950 static unsigned addChunk_IEND(ucvector* out)
4952 unsigned error = 0;
4953 error = addChunk(out, "IEND", 0, 0);
4954 return error;
4957 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4959 static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
4961 unsigned error = 0;
4962 size_t i;
4963 ucvector text;
4964 ucvector_init(&text);
4965 for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&text, (unsigned char)keyword[i]);
4966 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4967 ucvector_push_back(&text, 0); /*0 termination char*/
4968 for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&text, (unsigned char)textstring[i]);
4969 error = addChunk(out, "tEXt", text.data, text.size);
4970 ucvector_cleanup(&text);
4972 return error;
4975 static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
4976 LodePNGCompressSettings* zlibsettings)
4978 unsigned error = 0;
4979 ucvector data, compressed;
4980 size_t i, textsize = strlen(textstring);
4982 ucvector_init(&data);
4983 ucvector_init(&compressed);
4984 for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&data, (unsigned char)keyword[i]);
4985 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4986 ucvector_push_back(&data, 0); /*0 termination char*/
4987 ucvector_push_back(&data, 0); /*compression method: 0*/
4989 error = zlib_compress(&compressed.data, &compressed.size,
4990 (unsigned char*)textstring, textsize, zlibsettings);
4991 if(!error)
4993 for(i = 0; i < compressed.size; i++) ucvector_push_back(&data, compressed.data[i]);
4994 error = addChunk(out, "zTXt", data.data, data.size);
4997 ucvector_cleanup(&compressed);
4998 ucvector_cleanup(&data);
4999 return error;
5002 static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
5003 const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
5005 unsigned error = 0;
5006 ucvector data;
5007 size_t i, textsize = strlen(textstring);
5009 ucvector_init(&data);
5011 for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&data, (unsigned char)keyword[i]);
5012 if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
5013 ucvector_push_back(&data, 0); /*null termination char*/
5014 ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
5015 ucvector_push_back(&data, 0); /*compression method*/
5016 for(i = 0; langtag[i] != 0; i++) ucvector_push_back(&data, (unsigned char)langtag[i]);
5017 ucvector_push_back(&data, 0); /*null termination char*/
5018 for(i = 0; transkey[i] != 0; i++) ucvector_push_back(&data, (unsigned char)transkey[i]);
5019 ucvector_push_back(&data, 0); /*null termination char*/
5021 if(compressed)
5023 ucvector compressed_data;
5024 ucvector_init(&compressed_data);
5025 error = zlib_compress(&compressed_data.data, &compressed_data.size,
5026 (unsigned char*)textstring, textsize, zlibsettings);
5027 if(!error)
5029 for(i = 0; i < compressed_data.size; i++) ucvector_push_back(&data, compressed_data.data[i]);
5031 ucvector_cleanup(&compressed_data);
5033 else /*not compressed*/
5035 for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&data, (unsigned char)textstring[i]);
5038 if(!error) error = addChunk(out, "iTXt", data.data, data.size);
5039 ucvector_cleanup(&data);
5040 return error;
5043 static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info)
5045 unsigned error = 0;
5046 ucvector bKGD;
5047 ucvector_init(&bKGD);
5048 if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
5050 ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5051 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5053 else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
5055 ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5056 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5057 ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256));
5058 ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256));
5059 ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256));
5060 ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256));
5062 else if(info->color.colortype == LCT_PALETTE)
5064 ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/
5067 error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
5068 ucvector_cleanup(&bKGD);
5070 return error;
5073 static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time)
5075 unsigned error = 0;
5076 unsigned char* data = (unsigned char*)mymalloc(7);
5077 if(!data) return 83; /*alloc fail*/
5078 data[0] = (unsigned char)(time->year / 256);
5079 data[1] = (unsigned char)(time->year % 256);
5080 data[2] = time->month;
5081 data[3] = time->day;
5082 data[4] = time->hour;
5083 data[5] = time->minute;
5084 data[6] = time->second;
5085 error = addChunk(out, "tIME", data, 7);
5086 myfree(data);
5087 return error;
5090 static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
5092 unsigned error = 0;
5093 ucvector data;
5094 ucvector_init(&data);
5096 lodepng_add32bitInt(&data, info->phys_x);
5097 lodepng_add32bitInt(&data, info->phys_y);
5098 ucvector_push_back(&data, info->phys_unit);
5100 error = addChunk(out, "pHYs", data.data, data.size);
5101 ucvector_cleanup(&data);
5103 return error;
5106 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5108 static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
5109 size_t length, size_t bytewidth, unsigned char filterType)
5111 size_t i;
5112 switch(filterType)
5114 case 0: /*None*/
5115 for(i = 0; i < length; i++) out[i] = scanline[i];
5116 break;
5117 case 1: /*Sub*/
5118 if(prevline)
5120 for(i = 0; i < bytewidth; i++) out[i] = scanline[i];
5121 for(i = bytewidth; i < length; i++) out[i] = scanline[i] - scanline[i - bytewidth];
5123 else
5125 for(i = 0; i < bytewidth; i++) out[i] = scanline[i];
5126 for(i = bytewidth; i < length; i++) out[i] = scanline[i] - scanline[i - bytewidth];
5128 break;
5129 case 2: /*Up*/
5130 if(prevline)
5132 for(i = 0; i < length; i++) out[i] = scanline[i] - prevline[i];
5134 else
5136 for(i = 0; i < length; i++) out[i] = scanline[i];
5138 break;
5139 case 3: /*Average*/
5140 if(prevline)
5142 for(i = 0; i < bytewidth; i++) out[i] = scanline[i] - prevline[i] / 2;
5143 for(i = bytewidth; i < length; i++) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2);
5145 else
5147 for(i = 0; i < bytewidth; i++) out[i] = scanline[i];
5148 for(i = bytewidth; i < length; i++) out[i] = scanline[i] - scanline[i - bytewidth] / 2;
5150 break;
5151 case 4: /*Paeth*/
5152 if(prevline)
5154 /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5155 for(i = 0; i < bytewidth; i++) out[i] = (scanline[i] - prevline[i]);
5156 for(i = bytewidth; i < length; i++)
5158 out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
5161 else
5163 for(i = 0; i < bytewidth; i++) out[i] = scanline[i];
5164 /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5165 for(i = bytewidth; i < length; i++) out[i] = (scanline[i] - scanline[i - bytewidth]);
5167 break;
5168 default: return; /*unexisting filter type given*/
5172 /* log2 approximation. A slight bit faster than std::log. */
5173 static float flog2(float f)
5175 float result = 0;
5176 while(f > 32) { result += 4; f /= 16; }
5177 while(f > 2) { result++; f /= 2; }
5178 return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
5181 static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
5182 const LodePNGColorMode* info, const LodePNGEncoderSettings* settings)
5185 For PNG filter method 0
5186 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5187 the scanlines with 1 extra byte per scanline
5190 unsigned bpp = lodepng_get_bpp(info);
5191 /*the width of a scanline in bytes, not including the filter type*/
5192 size_t linebytes = (w * bpp + 7) / 8;
5193 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5194 size_t bytewidth = (bpp + 7) / 8;
5195 const unsigned char* prevline = 0;
5196 unsigned x, y;
5197 unsigned error = 0;
5198 LodePNGFilterStrategy strategy = settings->filter_strategy;
5201 There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5202 * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5203 use fixed filtering, with the filter None).
5204 * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5205 not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5206 all five filters and select the filter that produces the smallest sum of absolute values per row.
5207 This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5209 If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5210 but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5211 heuristic is used.
5213 if(settings->filter_palette_zero &&
5214 (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
5216 if(bpp == 0) return 31; /*error: invalid color type*/
5218 if(strategy == LFS_ZERO)
5220 for(y = 0; y < h; y++)
5222 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5223 size_t inindex = linebytes * y;
5224 out[outindex] = 0; /*filter type byte*/
5225 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
5226 prevline = &in[inindex];
5229 else if(strategy == LFS_MINSUM)
5231 /*adaptive filtering*/
5232 size_t sum[5];
5233 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5234 size_t smallest = 0;
5235 unsigned type, bestType = 0;
5237 for(type = 0; type < 5; type++)
5239 ucvector_init(&attempt[type]);
5240 if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5243 if(!error)
5245 for(y = 0; y < h; y++)
5247 /*try the 5 filter types*/
5248 for(type = 0; type < 5; type++)
5250 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5252 /*calculate the sum of the result*/
5253 sum[type] = 0;
5254 if(type == 0)
5256 for(x = 0; x < linebytes; x++) sum[type] += (unsigned char)(attempt[type].data[x]);
5258 else
5260 for(x = 0; x < linebytes; x++)
5262 /*For differences, each byte should be treated as signed, values above 127 are negative
5263 (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5264 This means filtertype 0 is almost never chosen, but that is justified.*/
5265 signed char s = (signed char)(attempt[type].data[x]);
5266 sum[type] += s < 0 ? -s : s;
5270 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5271 if(type == 0 || sum[type] < smallest)
5273 bestType = type;
5274 smallest = sum[type];
5278 prevline = &in[y * linebytes];
5280 /*now fill the out values*/
5281 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5282 for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5286 for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]);
5288 else if(strategy == LFS_ENTROPY)
5290 float sum[5];
5291 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5292 float smallest = 0;
5293 unsigned type, bestType = 0;
5294 unsigned count[256];
5296 for(type = 0; type < 5; type++)
5298 ucvector_init(&attempt[type]);
5299 if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5302 for(y = 0; y < h; y++)
5304 /*try the 5 filter types*/
5305 for(type = 0; type < 5; type++)
5307 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5308 for(x = 0; x < 256; x++) count[x] = 0;
5309 for(x = 0; x < linebytes; x++) count[attempt[type].data[x]]++;
5310 count[type]++; /*the filter type itself is part of the scanline*/
5311 sum[type] = 0;
5312 for(x = 0; x < 256; x++)
5314 float p = count[x] / (float)(linebytes + 1);
5315 sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
5317 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5318 if(type == 0 || sum[type] < smallest)
5320 bestType = type;
5321 smallest = sum[type];
5325 prevline = &in[y * linebytes];
5327 /*now fill the out values*/
5328 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5329 for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5332 for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]);
5334 else if(strategy == LFS_PREDEFINED)
5336 for(y = 0; y < h; y++)
5338 size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5339 size_t inindex = linebytes * y;
5340 unsigned type = settings->predefined_filters[y];
5341 out[outindex] = type; /*filter type byte*/
5342 filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
5343 prevline = &in[inindex];
5346 else if(strategy == LFS_BRUTE_FORCE)
5348 /*brute force filter chooser.
5349 deflate the scanline after every filter attempt to see which one deflates best.
5350 This is very slow and gives only slightly smaller, sometimes even larger, result*/
5351 size_t size[5];
5352 ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5353 size_t smallest = 0;
5354 unsigned type = 0, bestType = 0;
5355 unsigned char* dummy;
5356 LodePNGCompressSettings zlibsettings = settings->zlibsettings;
5357 /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5358 to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5359 better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5360 cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5361 zlibsettings.btype = 1;
5362 /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5363 images only, so disable it*/
5364 zlibsettings.custom_zlib = 0;
5365 zlibsettings.custom_deflate = 0;
5366 for(type = 0; type < 5; type++)
5368 ucvector_init(&attempt[type]);
5369 ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/
5371 for(y = 0; y < h; y++) /*try the 5 filter types*/
5373 for(type = 0; type < 5; type++)
5375 unsigned testsize = attempt[type].size;
5376 /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5378 filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5379 size[type] = 0;
5380 dummy = 0;
5381 zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings);
5382 myfree(dummy);
5383 /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5384 if(type == 0 || size[type] < smallest)
5386 bestType = type;
5387 smallest = size[type];
5390 prevline = &in[y * linebytes];
5391 out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5392 for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5394 for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]);
5396 else return 88; /* unknown filter strategy */
5398 return error;
5401 static void addPaddingBits(unsigned char* out, const unsigned char* in,
5402 size_t olinebits, size_t ilinebits, unsigned h)
5404 /*The opposite of the removePaddingBits function
5405 olinebits must be >= ilinebits*/
5406 unsigned y;
5407 size_t diff = olinebits - ilinebits;
5408 size_t obp = 0, ibp = 0; /*bit pointers*/
5409 for(y = 0; y < h; y++)
5411 size_t x;
5412 for(x = 0; x < ilinebits; x++)
5414 unsigned char bit = readBitFromReversedStream(&ibp, in);
5415 setBitOfReversedStream(&obp, out, bit);
5417 /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5418 "Use of uninitialised value of size ###" warning from valgrind*/
5419 for(x = 0; x < diff; x++) setBitOfReversedStream(&obp, out, 0);
5424 in: non-interlaced image with size w*h
5425 out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5426 no padding bits between scanlines, but between reduced images so that each
5427 reduced image starts at a byte.
5428 bpp: bits per pixel
5429 there are no padding bits, not between scanlines, not between reduced images
5430 in has the following size in bits: w * h * bpp.
5431 out is possibly bigger due to padding bits between reduced images
5432 NOTE: comments about padding bits are only relevant if bpp < 8
5434 static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
5436 unsigned passw[7], passh[7];
5437 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5438 unsigned i;
5440 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5442 if(bpp >= 8)
5444 for(i = 0; i < 7; i++)
5446 unsigned x, y, b;
5447 size_t bytewidth = bpp / 8;
5448 for(y = 0; y < passh[i]; y++)
5449 for(x = 0; x < passw[i]; x++)
5451 size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
5452 size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
5453 for(b = 0; b < bytewidth; b++)
5455 out[pixeloutstart + b] = in[pixelinstart + b];
5460 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5462 for(i = 0; i < 7; i++)
5464 unsigned x, y, b;
5465 unsigned ilinebits = bpp * passw[i];
5466 unsigned olinebits = bpp * w;
5467 size_t obp, ibp; /*bit pointers (for out and in buffer)*/
5468 for(y = 0; y < passh[i]; y++)
5469 for(x = 0; x < passw[i]; x++)
5471 ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
5472 obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
5473 for(b = 0; b < bpp; b++)
5475 unsigned char bit = readBitFromReversedStream(&ibp, in);
5476 setBitOfReversedStream(&obp, out, bit);
5483 /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5484 return value is error**/
5485 static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
5486 unsigned w, unsigned h,
5487 const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings)
5490 This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5491 *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5492 *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5494 unsigned bpp = lodepng_get_bpp(&info_png->color);
5495 unsigned error = 0;
5497 if(info_png->interlace_method == 0)
5499 *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5500 *out = (unsigned char*)mymalloc(*outsize);
5501 if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
5503 if(!error)
5505 /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5506 if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
5508 unsigned char* padded = (unsigned char*)mymalloc(h * ((w * bpp + 7) / 8));
5509 if(!padded) error = 83; /*alloc fail*/
5510 if(!error)
5512 addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
5513 error = filter(*out, padded, w, h, &info_png->color, settings);
5515 myfree(padded);
5517 else
5519 /*we can immediatly filter into the out buffer, no other steps needed*/
5520 error = filter(*out, in, w, h, &info_png->color, settings);
5524 else /*interlace_method is 1 (Adam7)*/
5526 unsigned passw[7], passh[7];
5527 size_t filter_passstart[8], padded_passstart[8], passstart[8];
5528 unsigned char* adam7;
5530 Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5532 *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5533 *out = (unsigned char*)mymalloc(*outsize);
5534 if(!(*out)) error = 83; /*alloc fail*/
5536 adam7 = (unsigned char*)mymalloc(passstart[7]);
5537 if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
5539 if(!error)
5541 unsigned i;
5543 Adam7_interlace(adam7, in, w, h, bpp);
5544 for(i = 0; i < 7; i++)
5546 if(bpp < 8)
5548 unsigned char* padded = (unsigned char*)mymalloc(padded_passstart[i + 1] - padded_passstart[i]);
5549 if(!padded) ERROR_BREAK(83); /*alloc fail*/
5550 addPaddingBits(padded, &adam7[passstart[i]],
5551 ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
5552 error = filter(&(*out)[filter_passstart[i]], padded,
5553 passw[i], passh[i], &info_png->color, settings);
5554 myfree(padded);
5556 else
5558 error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
5559 passw[i], passh[i], &info_png->color, settings);
5562 if(error) break;
5566 myfree(adam7);
5569 return error;
5573 palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5574 returns 0 if the palette is opaque,
5575 returns 1 if the palette has a single color with alpha 0 ==> color key
5576 returns 2 if the palette is semi-translucent.
5578 static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize)
5580 size_t i, key = 0;
5581 unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5582 for(i = 0; i < palettesize; i++)
5584 if(!key && palette[4 * i + 3] == 0)
5586 r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
5587 key = 1;
5588 i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5590 else if(palette[4 * i + 3] != 255) return 2;
5591 /*when key, no opaque RGB may have key's RGB*/
5592 else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
5594 return key;
5597 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5598 static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
5600 unsigned char* inchunk = data;
5601 while((size_t)(inchunk - data) < datasize)
5603 CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
5604 out->allocsize = out->size; /*fix the allocsize again*/
5605 inchunk = lodepng_chunk_next(inchunk);
5607 return 0;
5609 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5611 unsigned lodepng_encode(unsigned char** out, size_t* outsize,
5612 const unsigned char* image, unsigned w, unsigned h,
5613 LodePNGState* state)
5615 LodePNGInfo info;
5616 ucvector outv;
5617 unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
5618 size_t datasize = 0;
5620 /*provide some proper output values if error will happen*/
5621 *out = 0;
5622 *outsize = 0;
5623 state->error = 0;
5625 lodepng_info_init(&info);
5626 lodepng_info_copy(&info, &state->info_png);
5628 if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
5629 && (info.color.palettesize == 0 || info.color.palettesize > 256))
5631 state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
5632 return state->error;
5635 if(state->encoder.auto_convert != LAC_NO)
5637 state->error = doAutoChooseColor(&info.color, image, w, h, &state->info_raw,
5638 state->encoder.auto_convert);
5640 if(state->error) return state->error;
5642 if(state->encoder.zlibsettings.windowsize > 32768)
5644 CERROR_RETURN_ERROR(state->error, 60); /*error: windowsize larger than allowed*/
5646 if(state->encoder.zlibsettings.btype > 2)
5648 CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
5650 if(state->info_png.interlace_method > 1)
5652 CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
5655 state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
5656 if(state->error) return state->error; /*error: unexisting color type given*/
5657 state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
5658 if(state->error) return state->error; /*error: unexisting color type given*/
5660 if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
5662 unsigned char* converted;
5663 size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
5665 converted = (unsigned char*)mymalloc(size);
5666 if(!converted && size) state->error = 83; /*alloc fail*/
5667 if(!state->error)
5669 state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
5671 if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
5672 myfree(converted);
5674 else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
5676 ucvector_init(&outv);
5677 while(!state->error) /*while only executed once, to break on error*/
5679 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5680 size_t i;
5681 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5682 /*write signature and chunks*/
5683 writeSignature(&outv);
5684 /*IHDR*/
5685 addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
5686 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5687 /*unknown chunks between IHDR and PLTE*/
5688 if(info.unknown_chunks_data[0])
5690 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
5691 if(state->error) break;
5693 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5694 /*PLTE*/
5695 if(info.color.colortype == LCT_PALETTE)
5697 addChunk_PLTE(&outv, &info.color);
5699 if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA))
5701 addChunk_PLTE(&outv, &info.color);
5703 /*tRNS*/
5704 if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0)
5706 addChunk_tRNS(&outv, &info.color);
5708 if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined)
5710 addChunk_tRNS(&outv, &info.color);
5712 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5713 /*bKGD (must come between PLTE and the IDAt chunks*/
5714 if(info.background_defined) addChunk_bKGD(&outv, &info);
5715 /*pHYs (must come before the IDAT chunks)*/
5716 if(info.phys_defined) addChunk_pHYs(&outv, &info);
5718 /*unknown chunks between PLTE and IDAT*/
5719 if(info.unknown_chunks_data[1])
5721 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
5722 if(state->error) break;
5724 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5725 /*IDAT (multiple IDAT chunks must be consecutive)*/
5726 state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
5727 if(state->error) break;
5728 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5729 /*tIME*/
5730 if(info.time_defined) addChunk_tIME(&outv, &info.time);
5731 /*tEXt and/or zTXt*/
5732 for(i = 0; i < info.text_num; i++)
5734 if(strlen(info.text_keys[i]) > 79)
5736 state->error = 66; /*text chunk too large*/
5737 break;
5739 if(strlen(info.text_keys[i]) < 1)
5741 state->error = 67; /*text chunk too small*/
5742 break;
5744 if(state->encoder.text_compression)
5745 addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
5746 else
5747 addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
5749 /*LodePNG version id in text chunk*/
5750 if(state->encoder.add_id)
5752 unsigned alread_added_id_text = 0;
5753 for(i = 0; i < info.text_num; i++)
5755 if(!strcmp(info.text_keys[i], "LodePNG"))
5757 alread_added_id_text = 1;
5758 break;
5761 if(alread_added_id_text == 0)
5762 addChunk_tEXt(&outv, "LodePNG", VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
5764 /*iTXt*/
5765 for(i = 0; i < info.itext_num; i++)
5767 if(strlen(info.itext_keys[i]) > 79)
5769 state->error = 66; /*text chunk too large*/
5770 break;
5772 if(strlen(info.itext_keys[i]) < 1)
5774 state->error = 67; /*text chunk too small*/
5775 break;
5777 addChunk_iTXt(&outv, state->encoder.text_compression,
5778 info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
5779 &state->encoder.zlibsettings);
5782 /*unknown chunks between IDAT and IEND*/
5783 if(info.unknown_chunks_data[2])
5785 state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
5786 if(state->error) break;
5788 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5789 /*IEND*/
5790 addChunk_IEND(&outv);
5792 break; /*this isn't really a while loop; no error happened so break out now!*/
5795 lodepng_info_cleanup(&info);
5796 myfree(data);
5797 /*instead of cleaning the vector up, give it to the output*/
5798 *out = outv.data;
5799 *outsize = outv.size;
5801 return state->error;
5804 unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
5805 unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
5807 unsigned error;
5808 LodePNGState state;
5809 lodepng_state_init(&state);
5810 state.info_raw.colortype = colortype;
5811 state.info_raw.bitdepth = bitdepth;
5812 state.info_png.color.colortype = colortype;
5813 state.info_png.color.bitdepth = bitdepth;
5814 lodepng_encode(out, outsize, image, w, h, &state);
5815 error = state.error;
5816 lodepng_state_cleanup(&state);
5817 return error;
5820 unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5822 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
5825 unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5827 return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
5830 #ifdef LODEPNG_COMPILE_DISK
5831 unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
5832 LodePNGColorType colortype, unsigned bitdepth)
5834 unsigned char* buffer;
5835 size_t buffersize;
5836 unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
5837 if(!error) error = lodepng_save_file(buffer, buffersize, filename);
5838 myfree(buffer);
5839 return error;
5842 unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5844 return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
5847 unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5849 return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
5851 #endif /*LODEPNG_COMPILE_DISK*/
5853 void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
5855 lodepng_compress_settings_init(&settings->zlibsettings);
5856 settings->filter_palette_zero = 1;
5857 settings->filter_strategy = LFS_MINSUM;
5858 settings->auto_convert = LAC_AUTO;
5859 settings->force_palette = 0;
5860 settings->predefined_filters = 0;
5861 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5862 settings->add_id = 0;
5863 settings->text_compression = 1;
5864 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5867 #endif /*LODEPNG_COMPILE_ENCODER*/
5868 #endif /*LODEPNG_COMPILE_PNG*/
5870 #ifdef LODEPNG_COMPILE_ERROR_TEXT
5872 This returns the description of a numerical error code in English. This is also
5873 the documentation of all the error codes.
5875 const char* lodepng_error_text(unsigned code)
5877 switch(code)
5879 case 0: return "no error, everything went ok";
5880 case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5881 case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
5882 case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5883 case 13: return "problem while processing dynamic deflate block";
5884 case 14: return "problem while processing dynamic deflate block";
5885 case 15: return "problem while processing dynamic deflate block";
5886 case 16: return "unexisting code while processing dynamic deflate block";
5887 case 17: return "end of out buffer memory reached while inflating";
5888 case 18: return "invalid distance code while inflating";
5889 case 19: return "end of out buffer memory reached while inflating";
5890 case 20: return "invalid deflate block BTYPE encountered while decoding";
5891 case 21: return "NLEN is not ones complement of LEN in a deflate block";
5892 /*end of out buffer memory reached while inflating:
5893 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5894 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5895 happen in a normal, well encoded, PNG image.*/
5896 case 22: return "end of out buffer memory reached while inflating";
5897 case 23: return "end of in buffer memory reached while inflating";
5898 case 24: return "invalid FCHECK in zlib header";
5899 case 25: return "invalid compression method in zlib header";
5900 case 26: return "FDICT encountered in zlib header while it's not used for PNG";
5901 case 27: return "PNG file is smaller than a PNG header";
5902 /*Checks the magic file header, the first 8 bytes of the PNG file*/
5903 case 28: return "incorrect PNG signature, it's no PNG or corrupted";
5904 case 29: return "first chunk is not the header chunk";
5905 case 30: return "chunk length too large, chunk broken off at end of file";
5906 case 31: return "illegal PNG color type or bpp";
5907 case 32: return "illegal PNG compression method";
5908 case 33: return "illegal PNG filter method";
5909 case 34: return "illegal PNG interlace method";
5910 case 35: return "chunk length of a chunk is too large or the chunk too small";
5911 case 36: return "illegal PNG filter type encountered";
5912 case 37: return "illegal bit depth for this color type given";
5913 case 38: return "the palette is too big"; /*more than 256 colors*/
5914 case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
5915 case 40: return "tRNS chunk has wrong size for greyscale image";
5916 case 41: return "tRNS chunk has wrong size for RGB image";
5917 case 42: return "tRNS chunk appeared while it was not allowed for this color type";
5918 case 43: return "bKGD chunk has wrong size for palette image";
5919 case 44: return "bKGD chunk has wrong size for greyscale image";
5920 case 45: return "bKGD chunk has wrong size for RGB image";
5921 /*Is the palette too small?*/
5922 case 46: return "a value in indexed image is larger than the palette size (bitdepth = 8)";
5923 /*Is the palette too small?*/
5924 case 47: return "a value in indexed image is larger than the palette size (bitdepth < 8)";
5925 /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/
5926 case 48: return "empty input or file doesn't exist";
5927 case 49: return "jumped past memory while generating dynamic huffman tree";
5928 case 50: return "jumped past memory while generating dynamic huffman tree";
5929 case 51: return "jumped past memory while inflating huffman block";
5930 case 52: return "jumped past memory while inflating";
5931 case 53: return "size of zlib data too small";
5932 case 54: return "repeat symbol in tree while there was no value symbol yet";
5933 /*jumped past tree while generating huffman tree, this could be when the
5934 tree will have more leaves than symbols after generating it out of the
5935 given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
5936 case 55: return "jumped past tree while generating huffman tree";
5937 case 56: return "given output image colortype or bitdepth not supported for color conversion";
5938 case 57: return "invalid CRC encountered (checking CRC can be disabled)";
5939 case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
5940 case 59: return "requested color conversion not supported";
5941 case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
5942 case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
5943 /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
5944 case 62: return "conversion from color to greyscale not supported";
5945 case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
5946 /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
5947 case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
5948 case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
5949 case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
5950 case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
5951 case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
5952 case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
5953 case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
5954 case 73: return "invalid tIME chunk size";
5955 case 74: return "invalid pHYs chunk size";
5956 /*length could be wrong, or data chopped off*/
5957 case 75: return "no null termination char found while decoding text chunk";
5958 case 76: return "iTXt chunk too short to contain required bytes";
5959 case 77: return "integer overflow in buffer size";
5960 case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
5961 case 79: return "failed to open file for writing";
5962 case 80: return "tried creating a tree of 0 symbols";
5963 case 81: return "lazy matching at pos 0 is impossible";
5964 case 82: return "color conversion to palette requested while a color isn't in palette";
5965 case 83: return "memory allocation failed";
5966 case 84: return "given image too small to contain all pixels to be encoded";
5967 case 85: return "internal color conversion bug";
5968 case 86: return "impossible offset in lz77 encoding (internal bug)";
5969 case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
5970 case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
5971 case 89: return "text chunk keyword too short or long: must have size 1-79";
5973 return "unknown error code";
5975 #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
5977 /* ////////////////////////////////////////////////////////////////////////// */
5978 /* ////////////////////////////////////////////////////////////////////////// */
5979 /* // C++ Wrapper // */
5980 /* ////////////////////////////////////////////////////////////////////////// */
5981 /* ////////////////////////////////////////////////////////////////////////// */
5984 #ifdef LODEPNG_COMPILE_CPP
5985 namespace lodepng
5988 #ifdef LODEPNG_COMPILE_DISK
5989 void load_file(std::vector<unsigned char>& buffer, const std::string& filename)
5991 std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
5993 /*get filesize*/
5994 std::streamsize size = 0;
5995 if(file.seekg(0, std::ios::end).good()) size = file.tellg();
5996 if(file.seekg(0, std::ios::beg).good()) size -= file.tellg();
5998 /*read contents of the file into the vector*/
5999 buffer.resize(size_t(size));
6000 if(size > 0) file.read((char*)(&buffer[0]), size);
6003 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
6004 void save_file(const std::vector<unsigned char>& buffer, const std::string& filename)
6006 std::ofstream file(filename.c_str(), std::ios::out|std::ios::binary);
6007 file.write(buffer.empty() ? 0 : (char*)&buffer[0], std::streamsize(buffer.size()));
6009 #endif //LODEPNG_COMPILE_DISK
6011 #ifdef LODEPNG_COMPILE_ZLIB
6012 #ifdef LODEPNG_COMPILE_DECODER
6013 unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
6014 const LodePNGDecompressSettings& settings)
6016 unsigned char* buffer = 0;
6017 size_t buffersize = 0;
6018 unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
6019 if(buffer)
6021 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6022 myfree(buffer);
6024 return error;
6027 unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
6028 const LodePNGDecompressSettings& settings)
6030 return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
6032 #endif //LODEPNG_COMPILE_DECODER
6034 #ifdef LODEPNG_COMPILE_ENCODER
6035 unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
6036 const LodePNGCompressSettings& settings)
6038 unsigned char* buffer = 0;
6039 size_t buffersize = 0;
6040 unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
6041 if(buffer)
6043 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6044 myfree(buffer);
6046 return error;
6049 unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
6050 const LodePNGCompressSettings& settings)
6052 return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
6054 #endif //LODEPNG_COMPILE_ENCODER
6055 #endif //LODEPNG_COMPILE_ZLIB
6058 #ifdef LODEPNG_COMPILE_PNG
6060 State::State()
6062 lodepng_state_init(this);
6065 State::State(const State& other)
6067 lodepng_state_init(this);
6068 lodepng_state_copy(this, &other);
6071 State::~State()
6073 lodepng_state_cleanup(this);
6076 State& State::operator=(const State& other)
6078 lodepng_state_copy(this, &other);
6079 return *this;
6082 #ifdef LODEPNG_COMPILE_DECODER
6084 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
6085 size_t insize, LodePNGColorType colortype, unsigned bitdepth)
6087 unsigned char* buffer;
6088 unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
6089 if(buffer && !error)
6091 State state;
6092 state.info_raw.colortype = colortype;
6093 state.info_raw.bitdepth = bitdepth;
6094 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6095 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6096 myfree(buffer);
6098 return error;
6101 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6102 const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth)
6104 return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
6107 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6108 State& state,
6109 const unsigned char* in, size_t insize)
6111 unsigned char* buffer;
6112 unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
6113 if(buffer && !error)
6115 size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
6116 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6117 myfree(buffer);
6119 return error;
6122 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
6123 State& state,
6124 const std::vector<unsigned char>& in)
6126 return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
6129 #ifdef LODEPNG_COMPILE_DISK
6130 unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
6131 LodePNGColorType colortype, unsigned bitdepth)
6133 std::vector<unsigned char> buffer;
6134 load_file(buffer, filename);
6135 return decode(out, w, h, buffer, colortype, bitdepth);
6137 #endif //LODEPNG_COMPILE_DECODER
6138 #endif //LODEPNG_COMPILE_DISK
6140 #ifdef LODEPNG_COMPILE_ENCODER
6141 unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
6142 LodePNGColorType colortype, unsigned bitdepth)
6144 unsigned char* buffer;
6145 size_t buffersize;
6146 unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
6147 if(buffer)
6149 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6150 myfree(buffer);
6152 return error;
6155 unsigned encode(std::vector<unsigned char>& out,
6156 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6157 LodePNGColorType colortype, unsigned bitdepth)
6159 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6160 return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6163 unsigned encode(std::vector<unsigned char>& out,
6164 const unsigned char* in, unsigned w, unsigned h,
6165 State& state)
6167 unsigned char* buffer;
6168 size_t buffersize;
6169 unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
6170 if(buffer)
6172 out.insert(out.end(), &buffer[0], &buffer[buffersize]);
6173 myfree(buffer);
6175 return error;
6178 unsigned encode(std::vector<unsigned char>& out,
6179 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6180 State& state)
6182 if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
6183 return encode(out, in.empty() ? 0 : &in[0], w, h, state);
6186 #ifdef LODEPNG_COMPILE_DISK
6187 unsigned encode(const std::string& filename,
6188 const unsigned char* in, unsigned w, unsigned h,
6189 LodePNGColorType colortype, unsigned bitdepth)
6191 std::vector<unsigned char> buffer;
6192 unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
6193 if(!error) save_file(buffer, filename);
6194 return error;
6197 unsigned encode(const std::string& filename,
6198 const std::vector<unsigned char>& in, unsigned w, unsigned h,
6199 LodePNGColorType colortype, unsigned bitdepth)
6201 if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
6202 return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
6204 #endif //LODEPNG_COMPILE_DISK
6205 #endif //LODEPNG_COMPILE_ENCODER
6206 #endif //LODEPNG_COMPILE_PNG
6207 } //namespace lodepng
6208 #endif /*LODEPNG_COMPILE_CPP*/