daily pastebin goal
66%
SHARE
TWEET

Untitled

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