remove lodepng from external/
authorOzkan Sezer <sezeroz@gmail.com>
Wed, 06 Nov 2019 20:50:02 +0300
changeset 734e23c797d0a84
parent 733 4f8739f006ad
child 735 e1b2875d74db
remove lodepng from external/
external/lodepng/lodepng.c
external/lodepng/lodepng.h
     1.1 --- a/external/lodepng/lodepng.c	Wed Nov 06 10:01:02 2019 +0300
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,6330 +0,0 @@
     1.4 -/*
     1.5 -LodePNG version 20191020
     1.6 -
     1.7 -Copyright (c) 2005-2019 Lode Vandevenne
     1.8 -
     1.9 -This software is provided 'as-is', without any express or implied
    1.10 -warranty. In no event will the authors be held liable for any damages
    1.11 -arising from the use of this software.
    1.12 -
    1.13 -Permission is granted to anyone to use this software for any purpose,
    1.14 -including commercial applications, and to alter it and redistribute it
    1.15 -freely, subject to the following restrictions:
    1.16 -
    1.17 -    1. The origin of this software must not be misrepresented; you must not
    1.18 -    claim that you wrote the original software. If you use this software
    1.19 -    in a product, an acknowledgment in the product documentation would be
    1.20 -    appreciated but is not required.
    1.21 -
    1.22 -    2. Altered source versions must be plainly marked as such, and must not be
    1.23 -    misrepresented as being the original software.
    1.24 -
    1.25 -    3. This notice may not be removed or altered from any source
    1.26 -    distribution.
    1.27 -*/
    1.28 -
    1.29 -/*
    1.30 -The manual and changelog are in the header file "lodepng.h"
    1.31 -Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
    1.32 -*/
    1.33 -
    1.34 -#include "lodepng.h"
    1.35 -
    1.36 -#ifdef LODEPNG_COMPILE_DISK
    1.37 -#include <limits.h> /* LONG_MAX */
    1.38 -#include <stdio.h> /* file handling */
    1.39 -#endif /* LODEPNG_COMPILE_DISK */
    1.40 -
    1.41 -#ifdef LODEPNG_COMPILE_ALLOCATORS
    1.42 -#include <stdlib.h> /* allocations */
    1.43 -#endif /* LODEPNG_COMPILE_ALLOCATORS */
    1.44 -
    1.45 -#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
    1.46 -#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
    1.47 -#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
    1.48 -#endif /*_MSC_VER */
    1.49 -
    1.50 -const char* LODEPNG_VERSION_STRING = "20191020";
    1.51 -
    1.52 -/*
    1.53 -This source file is built up in the following large parts. The code sections
    1.54 -with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
    1.55 --Tools for C and common code for PNG and Zlib
    1.56 --C Code for Zlib (huffman, deflate, ...)
    1.57 --C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
    1.58 --The C++ wrapper around all of the above
    1.59 -*/
    1.60 -
    1.61 -/* ////////////////////////////////////////////////////////////////////////// */
    1.62 -/* ////////////////////////////////////////////////////////////////////////// */
    1.63 -/* // Tools for C, and common code for PNG and Zlib.                       // */
    1.64 -/* ////////////////////////////////////////////////////////////////////////// */
    1.65 -/* ////////////////////////////////////////////////////////////////////////// */
    1.66 -
    1.67 -/*The malloc, realloc and free functions defined here with "lodepng_" in front
    1.68 -of the name, so that you can easily change them to others related to your
    1.69 -platform if needed. Everything else in the code calls these. Pass
    1.70 --DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
    1.71 -#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
    1.72 -define them in your own project's source files without needing to change
    1.73 -lodepng source code. Don't forget to remove "static" if you copypaste them
    1.74 -from here.*/
    1.75 -
    1.76 -#ifdef LODEPNG_COMPILE_ALLOCATORS
    1.77 -static void* lodepng_malloc(size_t size) {
    1.78 -#ifdef LODEPNG_MAX_ALLOC
    1.79 -  if(size > LODEPNG_MAX_ALLOC) return 0;
    1.80 -#endif
    1.81 -  return malloc(size);
    1.82 -}
    1.83 -
    1.84 -static void* lodepng_realloc(void* ptr, size_t new_size) {
    1.85 -#ifdef LODEPNG_MAX_ALLOC
    1.86 -  if(new_size > LODEPNG_MAX_ALLOC) return 0;
    1.87 -#endif
    1.88 -  return realloc(ptr, new_size);
    1.89 -}
    1.90 -
    1.91 -static void lodepng_free(void* ptr) {
    1.92 -  free(ptr);
    1.93 -}
    1.94 -#else /*LODEPNG_COMPILE_ALLOCATORS*/
    1.95 -/* TODO: support giving additional void* payload to the custom allocators */
    1.96 -void* lodepng_malloc(size_t size);
    1.97 -void* lodepng_realloc(void* ptr, size_t new_size);
    1.98 -void lodepng_free(void* ptr);
    1.99 -#endif /*LODEPNG_COMPILE_ALLOCATORS*/
   1.100 -
   1.101 -/* convince the compiler to inline a function, for use when this measurably improves performance */
   1.102 -/* inline is not available in C90, but use it when supported by the compiler */
   1.103 -#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
   1.104 -#define LODEPNG_INLINE inline
   1.105 -#else
   1.106 -#define LODEPNG_INLINE /* not available */
   1.107 -#endif
   1.108 -
   1.109 -/* restrict is not available in C90, but use it when supported by the compiler */
   1.110 -#if (defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ >= 3) && (__GNUC_MINOR__ >= 1)) ||\
   1.111 -    (defined(_MSC_VER) && (_MSC_VER >= 1400)) || (defined(__WATCOMC__) && (__WATCOMC__ >= 1250))
   1.112 -#define LODEPNG_RESTRICT __restrict
   1.113 -#else
   1.114 -#define LODEPNG_RESTRICT /* not available */
   1.115 -#endif
   1.116 -
   1.117 -/* Replacements for C library functions memcpy and strlen, to support those platforms
   1.118 -where a full C library is not available. The compiler can recognize them and compile
   1.119 -to something as fast. */
   1.120 -
   1.121 -static void lodepng_memcpy(void* LODEPNG_RESTRICT dst,
   1.122 -                           const void* LODEPNG_RESTRICT src, size_t size) {
   1.123 -  size_t i;
   1.124 -  for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i];
   1.125 -}
   1.126 -
   1.127 -/* does not check memory out of bounds, do not use on untrusted data */
   1.128 -static size_t lodepng_strlen(const char* a) {
   1.129 -  const char* orig = a;
   1.130 -  /* avoid warning about unused function in case of disabled COMPILE... macros */
   1.131 -  (void)lodepng_strlen;
   1.132 -  while(*a) a++;
   1.133 -  return (size_t)(a - orig);
   1.134 -}
   1.135 -
   1.136 -#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
   1.137 -#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
   1.138 -#define LODEPNG_ABS(x) ((x) < 0 ? -(x) : (x))
   1.139 -
   1.140 -
   1.141 -#ifdef LODEPNG_COMPILE_DECODER
   1.142 -/* Safely check if multiplying two integers will overflow (no undefined
   1.143 -behavior, compiler removing the code, etc...) and output result. */
   1.144 -static int lodepng_mulofl(size_t a, size_t b, size_t* result) {
   1.145 -  *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
   1.146 -  return (a != 0 && *result / a != b);
   1.147 -}
   1.148 -
   1.149 -/* Safely check if adding two integers will overflow (no undefined
   1.150 -behavior, compiler removing the code, etc...) and output result. */
   1.151 -static int lodepng_addofl(size_t a, size_t b, size_t* result) {
   1.152 -  *result = a + b; /* Unsigned addition is well defined and safe in C90 */
   1.153 -  return *result < a;
   1.154 -}
   1.155 -
   1.156 -#ifdef LODEPNG_COMPILE_ZLIB
   1.157 -/* Safely check if a + b > c, even if overflow could happen. */
   1.158 -static int lodepng_gtofl(size_t a, size_t b, size_t c) {
   1.159 -  size_t d;
   1.160 -  if(lodepng_addofl(a, b, &d)) return 1;
   1.161 -  return d > c;
   1.162 -}
   1.163 -#endif /*LODEPNG_COMPILE_ZLIB*/
   1.164 -#endif /*LODEPNG_COMPILE_DECODER*/
   1.165 -
   1.166 -
   1.167 -/*
   1.168 -Often in case of an error a value is assigned to a variable and then it breaks
   1.169 -out of a loop (to go to the cleanup phase of a function). This macro does that.
   1.170 -It makes the error handling code shorter and more readable.
   1.171 -
   1.172 -Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
   1.173 -*/
   1.174 -#define CERROR_BREAK(errorvar, code){\
   1.175 -  errorvar = code;\
   1.176 -  break;\
   1.177 -}
   1.178 -
   1.179 -/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
   1.180 -#define ERROR_BREAK(code) CERROR_BREAK(error, code)
   1.181 -
   1.182 -/*Set error var to the error code, and return it.*/
   1.183 -#define CERROR_RETURN_ERROR(errorvar, code){\
   1.184 -  errorvar = code;\
   1.185 -  return code;\
   1.186 -}
   1.187 -
   1.188 -/*Try the code, if it returns error, also return the error.*/
   1.189 -#define CERROR_TRY_RETURN(call){\
   1.190 -  unsigned error = call;\
   1.191 -  if(error) return error;\
   1.192 -}
   1.193 -
   1.194 -/*Set error var to the error code, and return from the void function.*/
   1.195 -#define CERROR_RETURN(errorvar, code){\
   1.196 -  errorvar = code;\
   1.197 -  return;\
   1.198 -}
   1.199 -
   1.200 -/*
   1.201 -About uivector, ucvector and string:
   1.202 --All of them wrap dynamic arrays or text strings in a similar way.
   1.203 --LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
   1.204 --The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
   1.205 --They're not used in the interface, only internally in this file as static functions.
   1.206 --As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
   1.207 -*/
   1.208 -
   1.209 -#ifdef LODEPNG_COMPILE_ZLIB
   1.210 -#ifdef LODEPNG_COMPILE_ENCODER
   1.211 -/*dynamic vector of unsigned ints*/
   1.212 -typedef struct uivector {
   1.213 -  unsigned* data;
   1.214 -  size_t size; /*size in number of unsigned longs*/
   1.215 -  size_t allocsize; /*allocated size in bytes*/
   1.216 -} uivector;
   1.217 -
   1.218 -static void uivector_cleanup(void* p) {
   1.219 -  ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
   1.220 -  lodepng_free(((uivector*)p)->data);
   1.221 -  ((uivector*)p)->data = NULL;
   1.222 -}
   1.223 -
   1.224 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.225 -static unsigned uivector_reserve(uivector* p, size_t allocsize) {
   1.226 -  if(allocsize > p->allocsize) {
   1.227 -    size_t newsize = (allocsize > p->allocsize * 2u) ? allocsize : ((allocsize * 3u) >> 1u);
   1.228 -    void* data = lodepng_realloc(p->data, newsize);
   1.229 -    if(data) {
   1.230 -      p->allocsize = newsize;
   1.231 -      p->data = (unsigned*)data;
   1.232 -    }
   1.233 -    else return 0; /*error: not enough memory*/
   1.234 -  }
   1.235 -  return 1;
   1.236 -}
   1.237 -
   1.238 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.239 -static unsigned uivector_resize(uivector* p, size_t size) {
   1.240 -  if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
   1.241 -  p->size = size;
   1.242 -  return 1; /*success*/
   1.243 -}
   1.244 -
   1.245 -/*resize and give all new elements the value*/
   1.246 -static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) {
   1.247 -  size_t oldsize = p->size, i;
   1.248 -  if(!uivector_resize(p, size)) return 0;
   1.249 -  for(i = oldsize; i < size; ++i) p->data[i] = value;
   1.250 -  return 1;
   1.251 -}
   1.252 -
   1.253 -static void uivector_init(uivector* p) {
   1.254 -  p->data = NULL;
   1.255 -  p->size = p->allocsize = 0;
   1.256 -}
   1.257 -
   1.258 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.259 -static unsigned uivector_push_back(uivector* p, unsigned c) {
   1.260 -  if(!uivector_resize(p, p->size + 1)) return 0;
   1.261 -  p->data[p->size - 1] = c;
   1.262 -  return 1;
   1.263 -}
   1.264 -#endif /*LODEPNG_COMPILE_ENCODER*/
   1.265 -#endif /*LODEPNG_COMPILE_ZLIB*/
   1.266 -
   1.267 -/* /////////////////////////////////////////////////////////////////////////// */
   1.268 -
   1.269 -/*dynamic vector of unsigned chars*/
   1.270 -typedef struct ucvector {
   1.271 -  unsigned char* data;
   1.272 -  size_t size; /*used size*/
   1.273 -  size_t allocsize; /*allocated size*/
   1.274 -} ucvector;
   1.275 -
   1.276 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.277 -static unsigned ucvector_reserve(ucvector* p, size_t allocsize) {
   1.278 -  if(allocsize > p->allocsize) {
   1.279 -    size_t newsize = (allocsize > p->allocsize * 2u) ? allocsize : ((allocsize * 3u) >> 1u);
   1.280 -    void* data = lodepng_realloc(p->data, newsize);
   1.281 -    if(data) {
   1.282 -      p->allocsize = newsize;
   1.283 -      p->data = (unsigned char*)data;
   1.284 -    }
   1.285 -    else return 0; /*error: not enough memory*/
   1.286 -  }
   1.287 -  return 1;
   1.288 -}
   1.289 -
   1.290 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.291 -static unsigned ucvector_resize(ucvector* p, size_t size) {
   1.292 -  if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
   1.293 -  p->size = size;
   1.294 -  return 1; /*success*/
   1.295 -}
   1.296 -
   1.297 -#ifdef LODEPNG_COMPILE_PNG
   1.298 -
   1.299 -static void ucvector_cleanup(void* p) {
   1.300 -  ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
   1.301 -  lodepng_free(((ucvector*)p)->data);
   1.302 -  ((ucvector*)p)->data = NULL;
   1.303 -}
   1.304 -
   1.305 -static void ucvector_init(ucvector* p) {
   1.306 -  p->data = NULL;
   1.307 -  p->size = p->allocsize = 0;
   1.308 -}
   1.309 -#endif /*LODEPNG_COMPILE_PNG*/
   1.310 -
   1.311 -#ifdef LODEPNG_COMPILE_ZLIB
   1.312 -/*you can both convert from vector to buffer&size and vice versa. If you use
   1.313 -init_buffer to take over a buffer and size, it is not needed to use cleanup*/
   1.314 -static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) {
   1.315 -  p->data = buffer;
   1.316 -  p->allocsize = p->size = size;
   1.317 -}
   1.318 -#endif /*LODEPNG_COMPILE_ZLIB*/
   1.319 -
   1.320 -#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
   1.321 -/*returns 1 if success, 0 if failure ==> nothing done*/
   1.322 -static unsigned ucvector_push_back(ucvector* p, unsigned char c) {
   1.323 -  if(!ucvector_resize(p, p->size + 1)) return 0;
   1.324 -  p->data[p->size - 1] = c;
   1.325 -  return 1;
   1.326 -}
   1.327 -#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
   1.328 -
   1.329 -
   1.330 -/* ////////////////////////////////////////////////////////////////////////// */
   1.331 -
   1.332 -#ifdef LODEPNG_COMPILE_PNG
   1.333 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   1.334 -
   1.335 -/*free string pointer and set it to NULL*/
   1.336 -static void string_cleanup(char** out) {
   1.337 -  lodepng_free(*out);
   1.338 -  *out = NULL;
   1.339 -}
   1.340 -
   1.341 -/* dynamically allocates a new string with a copy of the null terminated input text */
   1.342 -static char* alloc_string(const char* in) {
   1.343 -  size_t insize = lodepng_strlen(in);
   1.344 -  char* out = (char*)lodepng_malloc(insize + 1);
   1.345 -  if(out) {
   1.346 -    size_t i;
   1.347 -    for(i = 0; i != insize; ++i) {
   1.348 -      out[i] = in[i];
   1.349 -    }
   1.350 -    out[i] = 0;
   1.351 -  }
   1.352 -  return out;
   1.353 -}
   1.354 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   1.355 -#endif /*LODEPNG_COMPILE_PNG*/
   1.356 -
   1.357 -/* ////////////////////////////////////////////////////////////////////////// */
   1.358 -
   1.359 -#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)
   1.360 -static unsigned lodepng_read32bitInt(const unsigned char* buffer) {
   1.361 -  return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) |
   1.362 -         ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);
   1.363 -}
   1.364 -#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/
   1.365 -
   1.366 -#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
   1.367 -/*buffer must have at least 4 allocated bytes available*/
   1.368 -static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {
   1.369 -  buffer[0] = (unsigned char)((value >> 24) & 0xff);
   1.370 -  buffer[1] = (unsigned char)((value >> 16) & 0xff);
   1.371 -  buffer[2] = (unsigned char)((value >>  8) & 0xff);
   1.372 -  buffer[3] = (unsigned char)((value      ) & 0xff);
   1.373 -}
   1.374 -#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
   1.375 -
   1.376 -/* ////////////////////////////////////////////////////////////////////////// */
   1.377 -/* / File IO                                                                / */
   1.378 -/* ////////////////////////////////////////////////////////////////////////// */
   1.379 -
   1.380 -#ifdef LODEPNG_COMPILE_DISK
   1.381 -
   1.382 -/* returns negative value on error. This should be pure C compatible, so no fstat. */
   1.383 -static long lodepng_filesize(const char* filename) {
   1.384 -  FILE* file;
   1.385 -  long size;
   1.386 -  file = fopen(filename, "rb");
   1.387 -  if(!file) return -1;
   1.388 -
   1.389 -  if(fseek(file, 0, SEEK_END) != 0) {
   1.390 -    fclose(file);
   1.391 -    return -1;
   1.392 -  }
   1.393 -
   1.394 -  size = ftell(file);
   1.395 -  /* It may give LONG_MAX as directory size, this is invalid for us. */
   1.396 -  if(size == LONG_MAX) size = -1;
   1.397 -
   1.398 -  fclose(file);
   1.399 -  return size;
   1.400 -}
   1.401 -
   1.402 -/* load file into buffer that already has the correct allocated size. Returns error code.*/
   1.403 -static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) {
   1.404 -  FILE* file;
   1.405 -  size_t readsize;
   1.406 -  file = fopen(filename, "rb");
   1.407 -  if(!file) return 78;
   1.408 -
   1.409 -  readsize = fread(out, 1, size, file);
   1.410 -  fclose(file);
   1.411 -
   1.412 -  if (readsize != size) return 78;
   1.413 -  return 0;
   1.414 -}
   1.415 -
   1.416 -unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {
   1.417 -  long size = lodepng_filesize(filename);
   1.418 -  if (size < 0) return 78;
   1.419 -  *outsize = (size_t)size;
   1.420 -
   1.421 -  *out = (unsigned char*)lodepng_malloc((size_t)size);
   1.422 -  if(!(*out) && size > 0) return 83; /*the above malloc failed*/
   1.423 -
   1.424 -  return lodepng_buffer_file(*out, (size_t)size, filename);
   1.425 -}
   1.426 -
   1.427 -/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
   1.428 -unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {
   1.429 -  FILE* file;
   1.430 -  file = fopen(filename, "wb" );
   1.431 -  if(!file) return 79;
   1.432 -  fwrite(buffer, 1, buffersize, file);
   1.433 -  fclose(file);
   1.434 -  return 0;
   1.435 -}
   1.436 -
   1.437 -#endif /*LODEPNG_COMPILE_DISK*/
   1.438 -
   1.439 -/* ////////////////////////////////////////////////////////////////////////// */
   1.440 -/* ////////////////////////////////////////////////////////////////////////// */
   1.441 -/* // End of common code and tools. Begin of Zlib related code.            // */
   1.442 -/* ////////////////////////////////////////////////////////////////////////// */
   1.443 -/* ////////////////////////////////////////////////////////////////////////// */
   1.444 -
   1.445 -#ifdef LODEPNG_COMPILE_ZLIB
   1.446 -#ifdef LODEPNG_COMPILE_ENCODER
   1.447 -
   1.448 -typedef struct {
   1.449 -  ucvector* data;
   1.450 -  size_t bp;
   1.451 -} LodePNGBitWriter;
   1.452 -
   1.453 -void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) {
   1.454 -  writer->data = data;
   1.455 -  writer->bp = 0;
   1.456 -}
   1.457 -
   1.458 -/*TODO: this ignores potential out of memory errors*/
   1.459 -#define WRITEBIT(/*size_t**/ writer, /*unsigned char*/ bit){\
   1.460 -  /* append new byte */\
   1.461 -  if(((writer->bp) & 7u) == 0) ucvector_push_back(writer->data, (unsigned char)0);\
   1.462 -  (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\
   1.463 -  ++writer->bp;\
   1.464 -}
   1.465 -
   1.466 -/* LSB of value is written first, and LSB of bytes is used first */
   1.467 -static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
   1.468 -  if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */
   1.469 -    WRITEBIT(writer, value);
   1.470 -  } else {
   1.471 -    /* TODO: increase output size nly once here rather than in each WRITEBIT */
   1.472 -    size_t i;
   1.473 -    for(i = 0; i != nbits; ++i) {
   1.474 -      WRITEBIT(writer, (unsigned char)((value >> i) & 1));
   1.475 -    }
   1.476 -  }
   1.477 -}
   1.478 -
   1.479 -/* This one is to use for adding huffman symbol, the value bits are written MSB first */
   1.480 -static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
   1.481 -  size_t i;
   1.482 -  for(i = 0; i != nbits; ++i) {
   1.483 -    /* TODO: increase output size only once here rather than in each WRITEBIT */
   1.484 -    WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u));
   1.485 -  }
   1.486 -}
   1.487 -#endif /*LODEPNG_COMPILE_ENCODER*/
   1.488 -
   1.489 -#ifdef LODEPNG_COMPILE_DECODER
   1.490 -
   1.491 -typedef struct {
   1.492 -  const unsigned char* data;
   1.493 -  size_t size; /*size of data in bytes*/
   1.494 -  size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/
   1.495 -  size_t bp;
   1.496 -  unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/
   1.497 -} LodePNGBitReader;
   1.498 -
   1.499 -/* data size argument is in bytes. Returns error if size too large causing overflow */
   1.500 -static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) {
   1.501 -  size_t temp;
   1.502 -  reader->data = data;
   1.503 -  reader->size = size;
   1.504 -  /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB)  */
   1.505 -  if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;
   1.506 -  /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and
   1.507 -  trying to ensure 32 more bits*/
   1.508 -  if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;
   1.509 -  reader->bp = 0;
   1.510 -  reader->buffer = 0;
   1.511 -  return 0; /*ok*/
   1.512 -}
   1.513 -
   1.514 -/*
   1.515 -ensureBits functions:
   1.516 -Ensures the reader can at least read nbits bits in one or more readBits calls,
   1.517 -safely even if not enough bits are available.
   1.518 -Returns 1 if there are enough bits available, 0 if not.
   1.519 -*/
   1.520 -
   1.521 -/*See ensureBits documentation above. This one ensures exactly 1 bit */
   1.522 -/*static unsigned ensureBits1(LodePNGBitReader* reader) {
   1.523 -  if(reader->bp >= reader->bitsize) return 0;
   1.524 -  reader->buffer = (unsigned)reader->data[reader->bp >> 3u] >> (reader->bp & 7u);
   1.525 -  return 1;
   1.526 -}*/
   1.527 -
   1.528 -/*See ensureBits documentation above. This one ensures up to 9 bits */
   1.529 -static unsigned ensureBits9(LodePNGBitReader* reader, size_t nbits) {
   1.530 -  size_t start = reader->bp >> 3u;
   1.531 -  size_t size = reader->size;
   1.532 -  if(start + 1u < size) {
   1.533 -    reader->buffer = (unsigned)(reader->data[start + 0]) | (unsigned)(reader->data[start + 1] << 8u);
   1.534 -    reader->buffer >>= (reader->bp & 7u);
   1.535 -    return 1;
   1.536 -  } else {
   1.537 -    reader->buffer = 0;
   1.538 -    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
   1.539 -    reader->buffer >>= (reader->bp & 7u);
   1.540 -    return reader->bp + nbits < reader->bitsize;
   1.541 -  }
   1.542 -}
   1.543 -
   1.544 -/*See ensureBits documentation above. This one ensures up to 17 bits */
   1.545 -static unsigned ensureBits17(LodePNGBitReader* reader, size_t nbits) {
   1.546 -  size_t start = reader->bp >> 3u;
   1.547 -  size_t size = reader->size;
   1.548 -  if(start + 2u < size) {
   1.549 -    reader->buffer = (unsigned)(reader->data[start + 0]) | (unsigned)(reader->data[start + 1] << 8u) |
   1.550 -                     (unsigned)(reader->data[start + 2] << 16u);
   1.551 -    reader->buffer >>= (reader->bp & 7u);
   1.552 -    return 1;
   1.553 -  } else {
   1.554 -    reader->buffer = 0;
   1.555 -    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
   1.556 -    if(start + 1u < size) reader->buffer |= (unsigned)(reader->data[start + 1] << 8u);
   1.557 -    reader->buffer >>= (reader->bp & 7u);
   1.558 -    return reader->bp + nbits < reader->bitsize;
   1.559 -  }
   1.560 -}
   1.561 -
   1.562 -/*See ensureBits documentation above. This one ensures up to 25 bits */
   1.563 -static LODEPNG_INLINE unsigned ensureBits25(LodePNGBitReader* reader, size_t nbits) {
   1.564 -  size_t start = reader->bp >> 3u;
   1.565 -  size_t size = reader->size;
   1.566 -  if(start + 3u < size) {
   1.567 -    reader->buffer = (unsigned)(reader->data[start + 0]) | (unsigned)(reader->data[start + 1] << 8u) |
   1.568 -                     (unsigned)(reader->data[start + 2] << 16u) | (unsigned)(reader->data[start + 3] << 24u);
   1.569 -    reader->buffer >>= (reader->bp & 7u);
   1.570 -    return 1;
   1.571 -  } else {
   1.572 -    reader->buffer = 0;
   1.573 -    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
   1.574 -    if(start + 1u < size) reader->buffer |= (unsigned)(reader->data[start + 1] << 8u);
   1.575 -    if(start + 2u < size) reader->buffer |= (unsigned)(reader->data[start + 2] << 16u);
   1.576 -    reader->buffer >>= (reader->bp & 7u);
   1.577 -    return reader->bp + nbits < reader->bitsize;
   1.578 -  }
   1.579 -}
   1.580 -
   1.581 -/*See ensureBits documentation above. This one ensures up to 32 bits */
   1.582 -static LODEPNG_INLINE unsigned ensureBits32(LodePNGBitReader* reader, size_t nbits) {
   1.583 -  size_t start = reader->bp >> 3u;
   1.584 -  size_t size = reader->size;
   1.585 -  if(start + 4u < size) {
   1.586 -    reader->buffer = (unsigned)(reader->data[start + 0]) | (unsigned)(reader->data[start + 1] << 8u) |
   1.587 -                     (unsigned)(reader->data[start + 2] << 16u) | (unsigned)(reader->data[start + 3] << 24u);
   1.588 -    reader->buffer >>= (reader->bp & 7u);
   1.589 -    reader->buffer |= ((unsigned)(reader->data[start + 4] << 24u) << (7u - (reader->bp & 7u)));
   1.590 -    return 1;
   1.591 -  } else {
   1.592 -    reader->buffer = 0;
   1.593 -    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
   1.594 -    if(start + 1u < size) reader->buffer |= (unsigned)(reader->data[start + 1] << 8u);
   1.595 -    if(start + 2u < size) reader->buffer |= (unsigned)(reader->data[start + 2] << 16u);
   1.596 -    if(start + 3u < size) reader->buffer |= (unsigned)(reader->data[start + 3] << 24u);
   1.597 -    reader->buffer >>= (reader->bp & 7u);
   1.598 -    return reader->bp + nbits < reader->bitsize;
   1.599 -  }
   1.600 -}
   1.601 -
   1.602 -/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits */
   1.603 -static unsigned peekBits(LodePNGBitReader* reader, size_t nbits) {
   1.604 -  return reader->buffer & ((1u << nbits) - 1u);
   1.605 -}
   1.606 -
   1.607 -/* Must have enough bits available with ensureBits */
   1.608 -static void advanceBits(LodePNGBitReader* reader, size_t nbits) {
   1.609 -  reader->buffer >>= nbits;
   1.610 -  reader->bp += nbits;
   1.611 -}
   1.612 -
   1.613 -/* Must have enough bits available with ensureBits */
   1.614 -static unsigned readBits(LodePNGBitReader* reader, size_t nbits) {
   1.615 -  unsigned result = peekBits(reader, nbits);
   1.616 -  advanceBits(reader, nbits);
   1.617 -  return result;
   1.618 -}
   1.619 -#endif /*LODEPNG_COMPILE_DECODER*/
   1.620 -
   1.621 -static unsigned reverseBits(unsigned bits, unsigned num) {
   1.622 -  /*TODO: implement faster lookup table based version when needed*/
   1.623 -  unsigned i, result = 0;
   1.624 -  for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;
   1.625 -  return result;
   1.626 -}
   1.627 -
   1.628 -/* ////////////////////////////////////////////////////////////////////////// */
   1.629 -/* / Deflate - Huffman                                                      / */
   1.630 -/* ////////////////////////////////////////////////////////////////////////// */
   1.631 -
   1.632 -#define FIRST_LENGTH_CODE_INDEX 257
   1.633 -#define LAST_LENGTH_CODE_INDEX 285
   1.634 -/*256 literals, the end code, some length codes, and 2 unused codes*/
   1.635 -#define NUM_DEFLATE_CODE_SYMBOLS 288
   1.636 -/*the distance codes have their own symbols, 30 used, 2 unused*/
   1.637 -#define NUM_DISTANCE_SYMBOLS 32
   1.638 -/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
   1.639 -#define NUM_CODE_LENGTH_CODES 19
   1.640 -
   1.641 -/*the base lengths represented by codes 257-285*/
   1.642 -static const unsigned LENGTHBASE[29]
   1.643 -  = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
   1.644 -     67, 83, 99, 115, 131, 163, 195, 227, 258};
   1.645 -
   1.646 -/*the extra bits used by codes 257-285 (added to base length)*/
   1.647 -static const unsigned LENGTHEXTRA[29]
   1.648 -  = {0, 0, 0, 0, 0, 0, 0,  0,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,
   1.649 -      4,  4,  4,   4,   5,   5,   5,   5,   0};
   1.650 -
   1.651 -/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
   1.652 -static const unsigned DISTANCEBASE[30]
   1.653 -  = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
   1.654 -     769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
   1.655 -
   1.656 -/*the extra bits of backwards distances (added to base)*/
   1.657 -static const unsigned DISTANCEEXTRA[30]
   1.658 -  = {0, 0, 0, 0, 1, 1, 2,  2,  3,  3,  4,  4,  5,  5,   6,   6,   7,   7,   8,
   1.659 -       8,    9,    9,   10,   10,   11,   11,   12,    12,    13,    13};
   1.660 -
   1.661 -/*the order in which "code length alphabet code lengths" are stored, out of this
   1.662 -the huffman tree of the dynamic huffman tree lengths is generated*/
   1.663 -static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
   1.664 -  = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
   1.665 -
   1.666 -/* ////////////////////////////////////////////////////////////////////////// */
   1.667 -
   1.668 -/*
   1.669 -Huffman tree struct, containing multiple representations of the tree
   1.670 -*/
   1.671 -typedef struct HuffmanTree {
   1.672 -  unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/
   1.673 -  unsigned* lengths; /*the lengths of the huffman codes*/
   1.674 -  unsigned maxbitlen; /*maximum number of bits a single code can get*/
   1.675 -  unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
   1.676 -  /* for reading only */
   1.677 -  unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/
   1.678 -  unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/
   1.679 -} HuffmanTree;
   1.680 -
   1.681 -static void HuffmanTree_init(HuffmanTree* tree) {
   1.682 -  tree->codes = 0;
   1.683 -  tree->lengths = 0;
   1.684 -  tree->table_len = 0;
   1.685 -  tree->table_value = 0;
   1.686 -}
   1.687 -
   1.688 -static void HuffmanTree_cleanup(HuffmanTree* tree) {
   1.689 -  lodepng_free(tree->codes);
   1.690 -  lodepng_free(tree->lengths);
   1.691 -  lodepng_free(tree->table_len);
   1.692 -  lodepng_free(tree->table_value);
   1.693 -}
   1.694 -
   1.695 -/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/
   1.696 -/* values 8u and 9u work the fastest */
   1.697 -#define FIRSTBITS 9u
   1.698 -
   1.699 -/* make table for huffman decoding */
   1.700 -static unsigned HuffmanTree_makeTable(HuffmanTree* tree) {
   1.701 -  static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/
   1.702 -  static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;
   1.703 -  size_t i, pointer, size; /*total table size*/
   1.704 -  unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned));
   1.705 -  if(!maxlens) return 83; /*alloc fail*/
   1.706 -
   1.707 -  /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/
   1.708 -  for(i = 0; i < headsize; ++i) maxlens[i] = 0;
   1.709 -  for(i = 0; i < tree->numcodes; i++) {
   1.710 -    unsigned symbol = tree->codes[i];
   1.711 -    unsigned l = tree->lengths[i];
   1.712 -    unsigned index;
   1.713 -    if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/
   1.714 -    /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/
   1.715 -    index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);
   1.716 -    maxlens[index] = LODEPNG_MAX(maxlens[index], l);
   1.717 -  }
   1.718 -  /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */
   1.719 -  size = headsize;
   1.720 -  for(i = 0; i < headsize; ++i) {
   1.721 -    unsigned l = maxlens[i];
   1.722 -    if(l > FIRSTBITS) size += (1u << (l - FIRSTBITS));
   1.723 -  }
   1.724 -  tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len));
   1.725 -  tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value));
   1.726 -  if(!tree->table_len || !tree->table_value) {
   1.727 -    lodepng_free(maxlens);
   1.728 -    /* freeing tree->table values is done at a higher scope */
   1.729 -    return 83; /*alloc fail*/
   1.730 -  }
   1.731 -  /*initialize with an invalid length to indicate unused entries*/
   1.732 -  for(i = 0; i < size; ++i) tree->table_len[i] = 16;
   1.733 -
   1.734 -  /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/
   1.735 -  pointer = headsize;
   1.736 -  for(i = 0; i < headsize; ++i) {
   1.737 -    unsigned l = maxlens[i];
   1.738 -    if(l <= FIRSTBITS) continue;
   1.739 -    tree->table_len[i] = l;
   1.740 -    tree->table_value[i] = pointer;
   1.741 -    pointer += (1u << (l - FIRSTBITS));
   1.742 -  }
   1.743 -  lodepng_free(maxlens);
   1.744 -
   1.745 -  /*fill in the first table for short symbols, or secondary table for long symbols*/
   1.746 -  for(i = 0; i < tree->numcodes; ++i) {
   1.747 -    unsigned l = tree->lengths[i];
   1.748 -    unsigned symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/
   1.749 -    /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/
   1.750 -    unsigned reverse = reverseBits(symbol, l);
   1.751 -    if(l == 0) {
   1.752 -      continue;
   1.753 -    } else if(l <= FIRSTBITS) {
   1.754 -      /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/
   1.755 -      unsigned num = 1u << (FIRSTBITS - l);
   1.756 -      unsigned j;
   1.757 -      for(j = 0; j < num; ++j) {
   1.758 -        /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/
   1.759 -        unsigned index = reverse | (j << l);
   1.760 -        if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
   1.761 -        tree->table_len[index] = l;
   1.762 -        tree->table_value[index] = i;
   1.763 -      }
   1.764 -    } else {
   1.765 -      /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/
   1.766 -      /*the FIRSTBITS MSBs of the symbol are the first table index*/
   1.767 -      unsigned index = reverse & mask;
   1.768 -      unsigned maxlen = tree->table_len[index];
   1.769 -      /*log2 of secondary table length, should be >= l - FIRSTBITS*/
   1.770 -      unsigned tablelen = maxlen - FIRSTBITS;
   1.771 -      unsigned start = tree->table_value[index]; /*starting index in secondary table*/
   1.772 -      unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/
   1.773 -      unsigned j;
   1.774 -      if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
   1.775 -      for(j = 0; j < num; ++j) {
   1.776 -        unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */
   1.777 -        unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));
   1.778 -        tree->table_len[index2] = l;
   1.779 -        tree->table_value[index2] = i;
   1.780 -      }
   1.781 -    }
   1.782 -  }
   1.783 -
   1.784 -  /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
   1.785 -  If that is not the case (due to too long length codes), the table will not
   1.786 -  have been fully used, and this is an error (not all bit combinations can be
   1.787 -  decoded): an oversubscribed huffman tree, indicated by error 55. */
   1.788 -  for(i = 0; i < size; ++i) {
   1.789 -    if(tree->table_len[i] == 16) return 55;
   1.790 -  }
   1.791 -
   1.792 -  return 0;
   1.793 -}
   1.794 -
   1.795 -/*
   1.796 -Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
   1.797 -numcodes, lengths and maxbitlen must already be filled in correctly. return
   1.798 -value is error.
   1.799 -*/
   1.800 -static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {
   1.801 -  unsigned* blcount;
   1.802 -  unsigned* nextcode;
   1.803 -  unsigned error = 0;
   1.804 -  unsigned bits, n;
   1.805 -
   1.806 -  tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
   1.807 -  blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
   1.808 -  nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
   1.809 -  if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/
   1.810 -
   1.811 -  if(!error) {
   1.812 -    for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;
   1.813 -    /*step 1: count number of instances of each code length*/
   1.814 -    for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];
   1.815 -    /*step 2: generate the nextcode values*/
   1.816 -    for(bits = 1; bits <= tree->maxbitlen; ++bits) {
   1.817 -      nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1;
   1.818 -    }
   1.819 -    /*step 3: generate all the codes*/
   1.820 -    for(n = 0; n != tree->numcodes; ++n) {
   1.821 -      if(tree->lengths[n] != 0) {
   1.822 -        tree->codes[n] = nextcode[tree->lengths[n]]++;
   1.823 -        /*remove superfluous bits from the code*/
   1.824 -        tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);
   1.825 -      }
   1.826 -    }
   1.827 -  }
   1.828 -
   1.829 -  lodepng_free(blcount);
   1.830 -  lodepng_free(nextcode);
   1.831 -
   1.832 -  if(!error) error = HuffmanTree_makeTable(tree);
   1.833 -  return error;
   1.834 -}
   1.835 -
   1.836 -/*
   1.837 -given the code lengths (as stored in the PNG file), generate the tree as defined
   1.838 -by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
   1.839 -return value is error.
   1.840 -*/
   1.841 -static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
   1.842 -                                            size_t numcodes, unsigned maxbitlen) {
   1.843 -  unsigned i;
   1.844 -  tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
   1.845 -  if(!tree->lengths) return 83; /*alloc fail*/
   1.846 -  for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
   1.847 -  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
   1.848 -  tree->maxbitlen = maxbitlen;
   1.849 -  return HuffmanTree_makeFromLengths2(tree);
   1.850 -}
   1.851 -
   1.852 -#ifdef LODEPNG_COMPILE_ENCODER
   1.853 -
   1.854 -/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
   1.855 -Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
   1.856 -
   1.857 -/*chain node for boundary package merge*/
   1.858 -typedef struct BPMNode {
   1.859 -  int weight; /*the sum of all weights in this chain*/
   1.860 -  unsigned index; /*index of this leaf node (called "count" in the paper)*/
   1.861 -  struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
   1.862 -  int in_use;
   1.863 -} BPMNode;
   1.864 -
   1.865 -/*lists of chains*/
   1.866 -typedef struct BPMLists {
   1.867 -  /*memory pool*/
   1.868 -  unsigned memsize;
   1.869 -  BPMNode* memory;
   1.870 -  unsigned numfree;
   1.871 -  unsigned nextfree;
   1.872 -  BPMNode** freelist;
   1.873 -  /*two heads of lookahead chains per list*/
   1.874 -  unsigned listsize;
   1.875 -  BPMNode** chains0;
   1.876 -  BPMNode** chains1;
   1.877 -} BPMLists;
   1.878 -
   1.879 -/*creates a new chain node with the given parameters, from the memory in the lists */
   1.880 -static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {
   1.881 -  unsigned i;
   1.882 -  BPMNode* result;
   1.883 -
   1.884 -  /*memory full, so garbage collect*/
   1.885 -  if(lists->nextfree >= lists->numfree) {
   1.886 -    /*mark only those that are in use*/
   1.887 -    for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
   1.888 -    for(i = 0; i != lists->listsize; ++i) {
   1.889 -      BPMNode* node;
   1.890 -      for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
   1.891 -      for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
   1.892 -    }
   1.893 -    /*collect those that are free*/
   1.894 -    lists->numfree = 0;
   1.895 -    for(i = 0; i != lists->memsize; ++i) {
   1.896 -      if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
   1.897 -    }
   1.898 -    lists->nextfree = 0;
   1.899 -  }
   1.900 -
   1.901 -  result = lists->freelist[lists->nextfree++];
   1.902 -  result->weight = weight;
   1.903 -  result->index = index;
   1.904 -  result->tail = tail;
   1.905 -  return result;
   1.906 -}
   1.907 -
   1.908 -/*sort the leaves with stable mergesort*/
   1.909 -static void bpmnode_sort(BPMNode* leaves, size_t num) {
   1.910 -  BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
   1.911 -  size_t width, counter = 0;
   1.912 -  for(width = 1; width < num; width *= 2) {
   1.913 -    BPMNode* a = (counter & 1) ? mem : leaves;
   1.914 -    BPMNode* b = (counter & 1) ? leaves : mem;
   1.915 -    size_t p;
   1.916 -    for(p = 0; p < num; p += 2 * width) {
   1.917 -      size_t q = (p + width > num) ? num : (p + width);
   1.918 -      size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
   1.919 -      size_t i = p, j = q, k;
   1.920 -      for(k = p; k < r; k++) {
   1.921 -        if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
   1.922 -        else b[k] = a[j++];
   1.923 -      }
   1.924 -    }
   1.925 -    counter++;
   1.926 -  }
   1.927 -  if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num);
   1.928 -  lodepng_free(mem);
   1.929 -}
   1.930 -
   1.931 -/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
   1.932 -static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {
   1.933 -  unsigned lastindex = lists->chains1[c]->index;
   1.934 -
   1.935 -  if(c == 0) {
   1.936 -    if(lastindex >= numpresent) return;
   1.937 -    lists->chains0[c] = lists->chains1[c];
   1.938 -    lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
   1.939 -  } else {
   1.940 -    /*sum of the weights of the head nodes of the previous lookahead chains.*/
   1.941 -    int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
   1.942 -    lists->chains0[c] = lists->chains1[c];
   1.943 -    if(lastindex < numpresent && sum > leaves[lastindex].weight) {
   1.944 -      lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
   1.945 -      return;
   1.946 -    }
   1.947 -    lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
   1.948 -    /*in the end we are only interested in the chain of the last list, so no
   1.949 -    need to recurse if we're at the last one (this gives measurable speedup)*/
   1.950 -    if(num + 1 < (int)(2 * numpresent - 2)) {
   1.951 -      boundaryPM(lists, leaves, numpresent, c - 1, num);
   1.952 -      boundaryPM(lists, leaves, numpresent, c - 1, num);
   1.953 -    }
   1.954 -  }
   1.955 -}
   1.956 -
   1.957 -unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
   1.958 -                                      size_t numcodes, unsigned maxbitlen) {
   1.959 -  unsigned error = 0;
   1.960 -  unsigned i;
   1.961 -  size_t numpresent = 0; /*number of symbols with non-zero frequency*/
   1.962 -  BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
   1.963 -
   1.964 -  if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
   1.965 -  if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
   1.966 -
   1.967 -  leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
   1.968 -  if(!leaves) return 83; /*alloc fail*/
   1.969 -
   1.970 -  for(i = 0; i != numcodes; ++i) {
   1.971 -    if(frequencies[i] > 0) {
   1.972 -      leaves[numpresent].weight = (int)frequencies[i];
   1.973 -      leaves[numpresent].index = i;
   1.974 -      ++numpresent;
   1.975 -    }
   1.976 -  }
   1.977 -
   1.978 -  for(i = 0; i != numcodes; ++i) lengths[i] = 0;
   1.979 -
   1.980 -  /*ensure at least two present symbols. There should be at least one symbol
   1.981 -  according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
   1.982 -  make these work as well ensure there are at least two symbols. The
   1.983 -  Package-Merge code below also doesn't work correctly if there's only one
   1.984 -  symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/
   1.985 -  if(numpresent == 0) {
   1.986 -    lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
   1.987 -  } else if(numpresent == 1) {
   1.988 -    lengths[leaves[0].index] = 1;
   1.989 -    lengths[leaves[0].index == 0 ? 1 : 0] = 1;
   1.990 -  } else {
   1.991 -    BPMLists lists;
   1.992 -    BPMNode* node;
   1.993 -
   1.994 -    bpmnode_sort(leaves, numpresent);
   1.995 -
   1.996 -    lists.listsize = maxbitlen;
   1.997 -    lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
   1.998 -    lists.nextfree = 0;
   1.999 -    lists.numfree = lists.memsize;
  1.1000 -    lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
  1.1001 -    lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
  1.1002 -    lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
  1.1003 -    lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
  1.1004 -    if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
  1.1005 -
  1.1006 -    if(!error) {
  1.1007 -      for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
  1.1008 -
  1.1009 -      bpmnode_create(&lists, leaves[0].weight, 1, 0);
  1.1010 -      bpmnode_create(&lists, leaves[1].weight, 2, 0);
  1.1011 -
  1.1012 -      for(i = 0; i != lists.listsize; ++i) {
  1.1013 -        lists.chains0[i] = &lists.memory[0];
  1.1014 -        lists.chains1[i] = &lists.memory[1];
  1.1015 -      }
  1.1016 -
  1.1017 -      /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
  1.1018 -      for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
  1.1019 -
  1.1020 -      for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
  1.1021 -        for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
  1.1022 -      }
  1.1023 -    }
  1.1024 -
  1.1025 -    lodepng_free(lists.memory);
  1.1026 -    lodepng_free(lists.freelist);
  1.1027 -    lodepng_free(lists.chains0);
  1.1028 -    lodepng_free(lists.chains1);
  1.1029 -  }
  1.1030 -
  1.1031 -  lodepng_free(leaves);
  1.1032 -  return error;
  1.1033 -}
  1.1034 -
  1.1035 -/*Create the Huffman tree given the symbol frequencies*/
  1.1036 -static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
  1.1037 -                                                size_t mincodes, size_t numcodes, unsigned maxbitlen) {
  1.1038 -  size_t i;
  1.1039 -  unsigned error = 0;
  1.1040 -  while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
  1.1041 -  tree->maxbitlen = maxbitlen;
  1.1042 -  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
  1.1043 -  tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
  1.1044 -  if(!tree->lengths) return 83; /*alloc fail*/
  1.1045 -  /*initialize all lengths to 0*/
  1.1046 -  for(i = 0; i < numcodes; i++) tree->lengths[i] = 0;
  1.1047 -
  1.1048 -  error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
  1.1049 -  if(!error) error = HuffmanTree_makeFromLengths2(tree);
  1.1050 -  return error;
  1.1051 -}
  1.1052 -
  1.1053 -static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) {
  1.1054 -  return tree->codes[index];
  1.1055 -}
  1.1056 -
  1.1057 -static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) {
  1.1058 -  return tree->lengths[index];
  1.1059 -}
  1.1060 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.1061 -
  1.1062 -/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
  1.1063 -static unsigned generateFixedLitLenTree(HuffmanTree* tree) {
  1.1064 -  unsigned i, error = 0;
  1.1065 -  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
  1.1066 -  if(!bitlen) return 83; /*alloc fail*/
  1.1067 -
  1.1068 -  /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
  1.1069 -  for(i =   0; i <= 143; ++i) bitlen[i] = 8;
  1.1070 -  for(i = 144; i <= 255; ++i) bitlen[i] = 9;
  1.1071 -  for(i = 256; i <= 279; ++i) bitlen[i] = 7;
  1.1072 -  for(i = 280; i <= 287; ++i) bitlen[i] = 8;
  1.1073 -
  1.1074 -  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
  1.1075 -
  1.1076 -  lodepng_free(bitlen);
  1.1077 -  return error;
  1.1078 -}
  1.1079 -
  1.1080 -/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
  1.1081 -static unsigned generateFixedDistanceTree(HuffmanTree* tree) {
  1.1082 -  unsigned i, error = 0;
  1.1083 -  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
  1.1084 -  if(!bitlen) return 83; /*alloc fail*/
  1.1085 -
  1.1086 -  /*there are 32 distance codes, but 30-31 are unused*/
  1.1087 -  for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
  1.1088 -  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
  1.1089 -
  1.1090 -  lodepng_free(bitlen);
  1.1091 -  return error;
  1.1092 -}
  1.1093 -
  1.1094 -#ifdef LODEPNG_COMPILE_DECODER
  1.1095 -
  1.1096 -/*
  1.1097 -returns the code. The bit reader must already have been ensured at least 15 bits
  1.1098 -*/
  1.1099 -static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) {
  1.1100 -  unsigned short code = peekBits(reader, FIRSTBITS);
  1.1101 -  unsigned short l = codetree->table_len[code];
  1.1102 -  unsigned short value = codetree->table_value[code];
  1.1103 -  if(l <= FIRSTBITS) {
  1.1104 -    advanceBits(reader, l);
  1.1105 -    return value;
  1.1106 -  } else {
  1.1107 -    unsigned index2;
  1.1108 -    advanceBits(reader, FIRSTBITS);
  1.1109 -    index2 = value + peekBits(reader, l - FIRSTBITS);
  1.1110 -    advanceBits(reader, codetree->table_len[index2] - FIRSTBITS);
  1.1111 -    return codetree->table_value[index2];
  1.1112 -  }
  1.1113 -}
  1.1114 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.1115 -
  1.1116 -#ifdef LODEPNG_COMPILE_DECODER
  1.1117 -
  1.1118 -/* ////////////////////////////////////////////////////////////////////////// */
  1.1119 -/* / Inflator (Decompressor)                                                / */
  1.1120 -/* ////////////////////////////////////////////////////////////////////////// */
  1.1121 -
  1.1122 -/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
  1.1123 -static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {
  1.1124 -  /*TODO: check for out of memory errors*/
  1.1125 -  generateFixedLitLenTree(tree_ll);
  1.1126 -  generateFixedDistanceTree(tree_d);
  1.1127 -}
  1.1128 -
  1.1129 -/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
  1.1130 -static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
  1.1131 -                                      LodePNGBitReader* reader) {
  1.1132 -  /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
  1.1133 -  unsigned error = 0;
  1.1134 -  unsigned n, HLIT, HDIST, HCLEN, i;
  1.1135 -
  1.1136 -  /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
  1.1137 -  unsigned* bitlen_ll = 0; /*lit,len code lengths*/
  1.1138 -  unsigned* bitlen_d = 0; /*dist code lengths*/
  1.1139 -  /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
  1.1140 -  unsigned* bitlen_cl = 0;
  1.1141 -  HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
  1.1142 -
  1.1143 -  if(!ensureBits17(reader, 14)) return 49; /*error: the bit pointer is or will go past the memory*/
  1.1144 -
  1.1145 -  /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
  1.1146 -  HLIT =  readBits(reader, 5) + 257;
  1.1147 -  /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
  1.1148 -  HDIST = readBits(reader, 5) + 1;
  1.1149 -  /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
  1.1150 -  HCLEN = readBits(reader, 4) + 4;
  1.1151 -
  1.1152 -  bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
  1.1153 -  if(!bitlen_cl) return 83 /*alloc fail*/;
  1.1154 -
  1.1155 -  HuffmanTree_init(&tree_cl);
  1.1156 -
  1.1157 -  while(!error) {
  1.1158 -    /*read the code length codes out of 3 * (amount of code length codes) bits*/
  1.1159 -    if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {
  1.1160 -      ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/
  1.1161 -    }
  1.1162 -    for(i = 0; i != HCLEN; ++i) {
  1.1163 -      ensureBits9(reader, 3); /*out of bounds already checked above */
  1.1164 -      bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);
  1.1165 -    }
  1.1166 -    for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {
  1.1167 -      bitlen_cl[CLCL_ORDER[i]] = 0;
  1.1168 -    }
  1.1169 -
  1.1170 -    error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
  1.1171 -    if(error) break;
  1.1172 -
  1.1173 -    /*now we can use this tree to read the lengths for the tree that this function will return*/
  1.1174 -    bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
  1.1175 -    bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
  1.1176 -    if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
  1.1177 -    for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
  1.1178 -    for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
  1.1179 -
  1.1180 -    /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
  1.1181 -    i = 0;
  1.1182 -    while(i < HLIT + HDIST) {
  1.1183 -      unsigned code;
  1.1184 -      ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/
  1.1185 -      code = huffmanDecodeSymbol(reader, &tree_cl);
  1.1186 -      if(code <= 15) /*a length code*/ {
  1.1187 -        if(i < HLIT) bitlen_ll[i] = code;
  1.1188 -        else bitlen_d[i - HLIT] = code;
  1.1189 -        ++i;
  1.1190 -      } else if(code == 16) /*repeat previous*/ {
  1.1191 -        unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
  1.1192 -        unsigned value; /*set value to the previous code*/
  1.1193 -
  1.1194 -        if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
  1.1195 -
  1.1196 -        replength += readBits(reader, 2);
  1.1197 -
  1.1198 -        if(i < HLIT + 1) value = bitlen_ll[i - 1];
  1.1199 -        else value = bitlen_d[i - HLIT - 1];
  1.1200 -        /*repeat this value in the next lengths*/
  1.1201 -        for(n = 0; n < replength; ++n) {
  1.1202 -          if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
  1.1203 -          if(i < HLIT) bitlen_ll[i] = value;
  1.1204 -          else bitlen_d[i - HLIT] = value;
  1.1205 -          ++i;
  1.1206 -        }
  1.1207 -      } else if(code == 17) /*repeat "0" 3-10 times*/ {
  1.1208 -        unsigned replength = 3; /*read in the bits that indicate repeat length*/
  1.1209 -        replength += readBits(reader, 3);
  1.1210 -
  1.1211 -        /*repeat this value in the next lengths*/
  1.1212 -        for(n = 0; n < replength; ++n) {
  1.1213 -          if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
  1.1214 -
  1.1215 -          if(i < HLIT) bitlen_ll[i] = 0;
  1.1216 -          else bitlen_d[i - HLIT] = 0;
  1.1217 -          ++i;
  1.1218 -        }
  1.1219 -      } else if(code == 18) /*repeat "0" 11-138 times*/ {
  1.1220 -        unsigned replength = 11; /*read in the bits that indicate repeat length*/
  1.1221 -        replength += readBits(reader, 7);
  1.1222 -
  1.1223 -        /*repeat this value in the next lengths*/
  1.1224 -        for(n = 0; n < replength; ++n) {
  1.1225 -          if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
  1.1226 -
  1.1227 -          if(i < HLIT) bitlen_ll[i] = 0;
  1.1228 -          else bitlen_d[i - HLIT] = 0;
  1.1229 -          ++i;
  1.1230 -        }
  1.1231 -      } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
  1.1232 -        ERROR_BREAK(16); /*nonexistent code, this can never happen*/
  1.1233 -      }
  1.1234 -      /*check if any of the ensureBits above went out of bounds*/
  1.1235 -      if(reader->bp > reader->bitsize) {
  1.1236 -        /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
  1.1237 -        (10=no endcode, 11=wrong jump outside of tree)*/
  1.1238 -        /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
  1.1239 -        ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
  1.1240 -      }
  1.1241 -    }
  1.1242 -    if(error) break;
  1.1243 -
  1.1244 -    if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
  1.1245 -
  1.1246 -    /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
  1.1247 -    error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
  1.1248 -    if(error) break;
  1.1249 -    error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
  1.1250 -
  1.1251 -    break; /*end of error-while*/
  1.1252 -  }
  1.1253 -
  1.1254 -  lodepng_free(bitlen_cl);
  1.1255 -  lodepng_free(bitlen_ll);
  1.1256 -  lodepng_free(bitlen_d);
  1.1257 -  HuffmanTree_cleanup(&tree_cl);
  1.1258 -
  1.1259 -  return error;
  1.1260 -}
  1.1261 -
  1.1262 -/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/
  1.1263 -static unsigned inflateHuffmanBlock(ucvector* out, size_t* pos, LodePNGBitReader* reader,
  1.1264 -                                    unsigned btype) {
  1.1265 -  unsigned error = 0;
  1.1266 -  HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
  1.1267 -  HuffmanTree tree_d; /*the huffman tree for distance codes*/
  1.1268 -
  1.1269 -  HuffmanTree_init(&tree_ll);
  1.1270 -  HuffmanTree_init(&tree_d);
  1.1271 -
  1.1272 -  if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
  1.1273 -  else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);
  1.1274 -
  1.1275 -  while(!error) /*decode all symbols until end reached, breaks at end code*/ {
  1.1276 -    /*code_ll is literal, length or end code*/
  1.1277 -    unsigned code_ll;
  1.1278 -    ensureBits25(reader, 20); /* up to 15 for the huffman symbol, up to 5 for the length extra bits */
  1.1279 -    code_ll = huffmanDecodeSymbol(reader, &tree_ll);
  1.1280 -    if(code_ll <= 255) /*literal symbol*/ {
  1.1281 -      /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
  1.1282 -      if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
  1.1283 -      out->data[*pos] = (unsigned char)code_ll;
  1.1284 -      ++(*pos);
  1.1285 -    } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {
  1.1286 -      unsigned code_d, distance;
  1.1287 -      unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
  1.1288 -      size_t start, backward, length;
  1.1289 -
  1.1290 -      /*part 1: get length base*/
  1.1291 -      length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
  1.1292 -
  1.1293 -      /*part 2: get extra bits and add the value of that to length*/
  1.1294 -      numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
  1.1295 -      if(numextrabits_l != 0) {
  1.1296 -        /* bits already ensured above */
  1.1297 -        length += readBits(reader, numextrabits_l);
  1.1298 -      }
  1.1299 -
  1.1300 -      /*part 3: get distance code*/
  1.1301 -      ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */
  1.1302 -      code_d = huffmanDecodeSymbol(reader, &tree_d);
  1.1303 -      if(code_d > 29) {
  1.1304 -        if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
  1.1305 -          /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
  1.1306 -          (10=no endcode, 11=wrong jump outside of tree)*/
  1.1307 -          ERROR_BREAK((reader->bp > reader->bitsize) ? 10 : 11);
  1.1308 -        } else {
  1.1309 -          ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/
  1.1310 -        }
  1.1311 -      }
  1.1312 -      distance = DISTANCEBASE[code_d];
  1.1313 -
  1.1314 -      /*part 4: get extra bits from distance*/
  1.1315 -      numextrabits_d = DISTANCEEXTRA[code_d];
  1.1316 -      if(numextrabits_d != 0) {
  1.1317 -        /* bits already ensured above */
  1.1318 -        distance += readBits(reader, numextrabits_d);
  1.1319 -      }
  1.1320 -
  1.1321 -      /*part 5: fill in all the out[n] values based on the length and dist*/
  1.1322 -      start = (*pos);
  1.1323 -      if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
  1.1324 -      backward = start - distance;
  1.1325 -
  1.1326 -      if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
  1.1327 -      if (distance < length) {
  1.1328 -        size_t forward;
  1.1329 -        lodepng_memcpy(out->data + *pos, out->data + backward, distance);
  1.1330 -        *pos += distance;
  1.1331 -        for(forward = distance; forward < length; ++forward) {
  1.1332 -          out->data[(*pos)++] = out->data[backward++];
  1.1333 -        }
  1.1334 -      } else {
  1.1335 -        lodepng_memcpy(out->data + *pos, out->data + backward, length);
  1.1336 -        *pos += length;
  1.1337 -      }
  1.1338 -    } else if(code_ll == 256) {
  1.1339 -      break; /*end code, break the loop*/
  1.1340 -    } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
  1.1341 -      ERROR_BREAK(16) /* impossible */
  1.1342 -    }
  1.1343 -    /*check if any of the ensureBits above went out of bounds*/
  1.1344 -    if(reader->bp > reader->bitsize) {
  1.1345 -      /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
  1.1346 -      (10=no endcode, 11=wrong jump outside of tree)*/
  1.1347 -      /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
  1.1348 -      ERROR_BREAK(51); /*error, bit pointer jumps past memory*/
  1.1349 -    }
  1.1350 -  }
  1.1351 -
  1.1352 -  HuffmanTree_cleanup(&tree_ll);
  1.1353 -  HuffmanTree_cleanup(&tree_d);
  1.1354 -
  1.1355 -  return error;
  1.1356 -}
  1.1357 -
  1.1358 -static unsigned inflateNoCompression(ucvector* out, size_t* pos,
  1.1359 -                                     LodePNGBitReader* reader, const LodePNGDecompressSettings* settings) {
  1.1360 -  size_t bytepos;
  1.1361 -  size_t size = reader->size;
  1.1362 -  unsigned LEN, NLEN, error = 0;
  1.1363 -
  1.1364 -  /*go to first boundary of byte*/
  1.1365 -  bytepos = (reader->bp + 7u) >> 3u;
  1.1366 -
  1.1367 -  /*read LEN (2 bytes) and NLEN (2 bytes)*/
  1.1368 -  if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/
  1.1369 -  LEN = (unsigned)reader->data[bytepos] + (unsigned)(reader->data[bytepos + 1] << 8u); bytepos += 2;
  1.1370 -  NLEN = (unsigned)reader->data[bytepos] + (unsigned)(reader->data[bytepos + 1] << 8u); bytepos += 2;
  1.1371 -
  1.1372 -  /*check if 16-bit NLEN is really the one's complement of LEN*/
  1.1373 -  if(!settings->ignore_nlen && LEN + NLEN != 65535) {
  1.1374 -    return 21; /*error: NLEN is not one's complement of LEN*/
  1.1375 -  }
  1.1376 -
  1.1377 -  if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
  1.1378 -
  1.1379 -  /*read the literal data: LEN bytes are now stored in the out buffer*/
  1.1380 -  if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/
  1.1381 -
  1.1382 -  lodepng_memcpy(out->data + *pos, reader->data + bytepos, LEN);
  1.1383 -  *pos += LEN;
  1.1384 -  bytepos += LEN;
  1.1385 -
  1.1386 -  reader->bp = bytepos << 3u;
  1.1387 -
  1.1388 -  return error;
  1.1389 -}
  1.1390 -
  1.1391 -static unsigned lodepng_inflatev(ucvector* out,
  1.1392 -                                 const unsigned char* in, size_t insize,
  1.1393 -                                 const LodePNGDecompressSettings* settings) {
  1.1394 -  unsigned BFINAL = 0;
  1.1395 -  size_t pos = 0; /*byte position in the out buffer*/
  1.1396 -  LodePNGBitReader reader;
  1.1397 -  unsigned error = LodePNGBitReader_init(&reader, in, insize);
  1.1398 -
  1.1399 -  if(error) return error;
  1.1400 -
  1.1401 -  while(!BFINAL) {
  1.1402 -    unsigned BTYPE;
  1.1403 -    if(!ensureBits9(&reader, 3)) return 52; /*error, bit pointer will jump past memory*/
  1.1404 -    BFINAL = readBits(&reader, 1);
  1.1405 -    BTYPE = readBits(&reader, 2);
  1.1406 -
  1.1407 -    if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
  1.1408 -    else if(BTYPE == 0) error = inflateNoCompression(out, &pos, &reader, settings); /*no compression*/
  1.1409 -    else error = inflateHuffmanBlock(out, &pos, &reader, BTYPE); /*compression, BTYPE 01 or 10*/
  1.1410 -
  1.1411 -    if(error) return error;
  1.1412 -  }
  1.1413 -
  1.1414 -  return error;
  1.1415 -}
  1.1416 -
  1.1417 -unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
  1.1418 -                         const unsigned char* in, size_t insize,
  1.1419 -                         const LodePNGDecompressSettings* settings) {
  1.1420 -  unsigned error;
  1.1421 -  ucvector v;
  1.1422 -  ucvector_init_buffer(&v, *out, *outsize);
  1.1423 -  error = lodepng_inflatev(&v, in, insize, settings);
  1.1424 -  *out = v.data;
  1.1425 -  *outsize = v.size;
  1.1426 -  return error;
  1.1427 -}
  1.1428 -
  1.1429 -static unsigned inflate(unsigned char** out, size_t* outsize,
  1.1430 -                        const unsigned char* in, size_t insize,
  1.1431 -                        const LodePNGDecompressSettings* settings) {
  1.1432 -  if(settings->custom_inflate) {
  1.1433 -    return settings->custom_inflate(out, outsize, in, insize, settings);
  1.1434 -  } else {
  1.1435 -    return lodepng_inflate(out, outsize, in, insize, settings);
  1.1436 -  }
  1.1437 -}
  1.1438 -
  1.1439 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.1440 -
  1.1441 -#ifdef LODEPNG_COMPILE_ENCODER
  1.1442 -
  1.1443 -/* ////////////////////////////////////////////////////////////////////////// */
  1.1444 -/* / Deflator (Compressor)                                                  / */
  1.1445 -/* ////////////////////////////////////////////////////////////////////////// */
  1.1446 -
  1.1447 -static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
  1.1448 -
  1.1449 -/*search the index in the array, that has the largest value smaller than or equal to the given value,
  1.1450 -given array must be sorted (if no value is smaller, it returns the size of the given array)*/
  1.1451 -static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) {
  1.1452 -  /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
  1.1453 -  size_t left = 1;
  1.1454 -  size_t right = array_size - 1;
  1.1455 -
  1.1456 -  while(left <= right) {
  1.1457 -    size_t mid = (left + right) >> 1;
  1.1458 -    if (array[mid] >= value) right = mid - 1;
  1.1459 -    else left = mid + 1;
  1.1460 -  }
  1.1461 -  if(left >= array_size || array[left] > value) left--;
  1.1462 -  return left;
  1.1463 -}
  1.1464 -
  1.1465 -static void addLengthDistance(uivector* values, size_t length, size_t distance) {
  1.1466 -  /*values in encoded vector are those used by deflate:
  1.1467 -  0-255: literal bytes
  1.1468 -  256: end
  1.1469 -  257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
  1.1470 -  286-287: invalid*/
  1.1471 -
  1.1472 -  unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
  1.1473 -  unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
  1.1474 -  unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
  1.1475 -  unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
  1.1476 -
  1.1477 -  uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
  1.1478 -  uivector_push_back(values, extra_length);
  1.1479 -  uivector_push_back(values, dist_code);
  1.1480 -  uivector_push_back(values, extra_distance);
  1.1481 -}
  1.1482 -
  1.1483 -/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
  1.1484 -bytes as input because 3 is the minimum match length for deflate*/
  1.1485 -static const unsigned HASH_NUM_VALUES = 65536;
  1.1486 -static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
  1.1487 -
  1.1488 -typedef struct Hash {
  1.1489 -  int* head; /*hash value to head circular pos - can be outdated if went around window*/
  1.1490 -  /*circular pos to prev circular pos*/
  1.1491 -  unsigned short* chain;
  1.1492 -  int* val; /*circular pos to hash value*/
  1.1493 -
  1.1494 -  /*TODO: do this not only for zeros but for any repeated byte. However for PNG
  1.1495 -  it's always going to be the zeros that dominate, so not important for PNG*/
  1.1496 -  int* headz; /*similar to head, but for chainz*/
  1.1497 -  unsigned short* chainz; /*those with same amount of zeros*/
  1.1498 -  unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
  1.1499 -} Hash;
  1.1500 -
  1.1501 -static unsigned hash_init(Hash* hash, unsigned windowsize) {
  1.1502 -  unsigned i;
  1.1503 -  hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
  1.1504 -  hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
  1.1505 -  hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1.1506 -
  1.1507 -  hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1.1508 -  hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
  1.1509 -  hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1.1510 -
  1.1511 -  if(!hash->head || !hash->chain || !hash->val  || !hash->headz|| !hash->chainz || !hash->zeros) {
  1.1512 -    return 83; /*alloc fail*/
  1.1513 -  }
  1.1514 -
  1.1515 -  /*initialize hash table*/
  1.1516 -  for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
  1.1517 -  for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
  1.1518 -  for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
  1.1519 -
  1.1520 -  for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
  1.1521 -  for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
  1.1522 -
  1.1523 -  return 0;
  1.1524 -}
  1.1525 -
  1.1526 -static void hash_cleanup(Hash* hash) {
  1.1527 -  lodepng_free(hash->head);
  1.1528 -  lodepng_free(hash->val);
  1.1529 -  lodepng_free(hash->chain);
  1.1530 -
  1.1531 -  lodepng_free(hash->zeros);
  1.1532 -  lodepng_free(hash->headz);
  1.1533 -  lodepng_free(hash->chainz);
  1.1534 -}
  1.1535 -
  1.1536 -
  1.1537 -
  1.1538 -static unsigned getHash(const unsigned char* data, size_t size, size_t pos) {
  1.1539 -  unsigned result = 0;
  1.1540 -  if(pos + 2 < size) {
  1.1541 -    /*A simple shift and xor hash is used. Since the data of PNGs is dominated
  1.1542 -    by zeroes due to the filters, a better hash does not have a significant
  1.1543 -    effect on speed in traversing the chain, and causes more time spend on
  1.1544 -    calculating the hash.*/
  1.1545 -    result ^= (unsigned)(data[pos + 0] << 0u);
  1.1546 -    result ^= (unsigned)(data[pos + 1] << 4u);
  1.1547 -    result ^= (unsigned)(data[pos + 2] << 8u);
  1.1548 -  } else {
  1.1549 -    size_t amount, i;
  1.1550 -    if(pos >= size) return 0;
  1.1551 -    amount = size - pos;
  1.1552 -    for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
  1.1553 -  }
  1.1554 -  return result & HASH_BIT_MASK;
  1.1555 -}
  1.1556 -
  1.1557 -static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) {
  1.1558 -  const unsigned char* start = data + pos;
  1.1559 -  const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
  1.1560 -  if(end > data + size) end = data + size;
  1.1561 -  data = start;
  1.1562 -  while(data != end && *data == 0) ++data;
  1.1563 -  /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
  1.1564 -  return (unsigned)(data - start);
  1.1565 -}
  1.1566 -
  1.1567 -/*wpos = pos & (windowsize - 1)*/
  1.1568 -static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) {
  1.1569 -  hash->val[wpos] = (int)hashval;
  1.1570 -  if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
  1.1571 -  hash->head[hashval] = (int)wpos;
  1.1572 -
  1.1573 -  hash->zeros[wpos] = numzeros;
  1.1574 -  if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
  1.1575 -  hash->headz[numzeros] = (int)wpos;
  1.1576 -}
  1.1577 -
  1.1578 -/*
  1.1579 -LZ77-encode the data. Return value is error code. The input are raw bytes, the output
  1.1580 -is in the form of unsigned integers with codes representing for example literal bytes, or
  1.1581 -length/distance pairs.
  1.1582 -It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
  1.1583 -sliding window (of windowsize) is used, and all past bytes in that window can be used as
  1.1584 -the "dictionary". A brute force search through all possible distances would be slow, and
  1.1585 -this hash technique is one out of several ways to speed this up.
  1.1586 -*/
  1.1587 -static unsigned encodeLZ77(uivector* out, Hash* hash,
  1.1588 -                           const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
  1.1589 -                           unsigned minmatch, unsigned nicematch, unsigned lazymatching) {
  1.1590 -  size_t pos;
  1.1591 -  unsigned i, error = 0;
  1.1592 -  /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
  1.1593 -  unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u;
  1.1594 -  unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
  1.1595 -
  1.1596 -  unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
  1.1597 -  unsigned numzeros = 0;
  1.1598 -
  1.1599 -  unsigned offset; /*the offset represents the distance in LZ77 terminology*/
  1.1600 -  unsigned length;
  1.1601 -  unsigned lazy = 0;
  1.1602 -  unsigned lazylength = 0, lazyoffset = 0;
  1.1603 -  unsigned hashval;
  1.1604 -  unsigned current_offset, current_length;
  1.1605 -  unsigned prev_offset;
  1.1606 -  const unsigned char *lastptr, *foreptr, *backptr;
  1.1607 -  unsigned hashpos;
  1.1608 -
  1.1609 -  if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
  1.1610 -  if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
  1.1611 -
  1.1612 -  if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
  1.1613 -
  1.1614 -  for(pos = inpos; pos < insize; ++pos) {
  1.1615 -    size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
  1.1616 -    unsigned chainlength = 0;
  1.1617 -
  1.1618 -    hashval = getHash(in, insize, pos);
  1.1619 -
  1.1620 -    if(usezeros && hashval == 0) {
  1.1621 -      if(numzeros == 0) numzeros = countZeros(in, insize, pos);
  1.1622 -      else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
  1.1623 -    } else {
  1.1624 -      numzeros = 0;
  1.1625 -    }
  1.1626 -
  1.1627 -    updateHashChain(hash, wpos, hashval, numzeros);
  1.1628 -
  1.1629 -    /*the length and offset found for the current position*/
  1.1630 -    length = 0;
  1.1631 -    offset = 0;
  1.1632 -
  1.1633 -    hashpos = hash->chain[wpos];
  1.1634 -
  1.1635 -    lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
  1.1636 -
  1.1637 -    /*search for the longest string*/
  1.1638 -    prev_offset = 0;
  1.1639 -    for(;;) {
  1.1640 -      if(chainlength++ >= maxchainlength) break;
  1.1641 -      current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);
  1.1642 -
  1.1643 -      if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
  1.1644 -      prev_offset = current_offset;
  1.1645 -      if(current_offset > 0) {
  1.1646 -        /*test the next characters*/
  1.1647 -        foreptr = &in[pos];
  1.1648 -        backptr = &in[pos - current_offset];
  1.1649 -
  1.1650 -        /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
  1.1651 -        if(numzeros >= 3) {
  1.1652 -          unsigned skip = hash->zeros[hashpos];
  1.1653 -          if(skip > numzeros) skip = numzeros;
  1.1654 -          backptr += skip;
  1.1655 -          foreptr += skip;
  1.1656 -        }
  1.1657 -
  1.1658 -        while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ {
  1.1659 -          ++backptr;
  1.1660 -          ++foreptr;
  1.1661 -        }
  1.1662 -        current_length = (unsigned)(foreptr - &in[pos]);
  1.1663 -
  1.1664 -        if(current_length > length) {
  1.1665 -          length = current_length; /*the longest length*/
  1.1666 -          offset = current_offset; /*the offset that is related to this longest length*/
  1.1667 -          /*jump out once a length of max length is found (speed gain). This also jumps
  1.1668 -          out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
  1.1669 -          if(current_length >= nicematch) break;
  1.1670 -        }
  1.1671 -      }
  1.1672 -
  1.1673 -      if(hashpos == hash->chain[hashpos]) break;
  1.1674 -
  1.1675 -      if(numzeros >= 3 && length > numzeros) {
  1.1676 -        hashpos = hash->chainz[hashpos];
  1.1677 -        if(hash->zeros[hashpos] != numzeros) break;
  1.1678 -      } else {
  1.1679 -        hashpos = hash->chain[hashpos];
  1.1680 -        /*outdated hash value, happens if particular value was not encountered in whole last window*/
  1.1681 -        if(hash->val[hashpos] != (int)hashval) break;
  1.1682 -      }
  1.1683 -    }
  1.1684 -
  1.1685 -    if(lazymatching) {
  1.1686 -      if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {
  1.1687 -        lazy = 1;
  1.1688 -        lazylength = length;
  1.1689 -        lazyoffset = offset;
  1.1690 -        continue; /*try the next byte*/
  1.1691 -      }
  1.1692 -      if(lazy) {
  1.1693 -        lazy = 0;
  1.1694 -        if(pos == 0) ERROR_BREAK(81);
  1.1695 -        if(length > lazylength + 1) {
  1.1696 -          /*push the previous character as literal*/
  1.1697 -          if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
  1.1698 -        } else {
  1.1699 -          length = lazylength;
  1.1700 -          offset = lazyoffset;
  1.1701 -          hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
  1.1702 -          hash->headz[numzeros] = -1; /*idem*/
  1.1703 -          --pos;
  1.1704 -        }
  1.1705 -      }
  1.1706 -    }
  1.1707 -    if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
  1.1708 -
  1.1709 -    /*encode it as length/distance pair or literal value*/
  1.1710 -    if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ {
  1.1711 -      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
  1.1712 -    } else if(length < minmatch || (length == 3 && offset > 4096)) {
  1.1713 -      /*compensate for the fact that longer offsets have more extra bits, a
  1.1714 -      length of only 3 may be not worth it then*/
  1.1715 -      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
  1.1716 -    } else {
  1.1717 -      addLengthDistance(out, length, offset);
  1.1718 -      for(i = 1; i < length; ++i) {
  1.1719 -        ++pos;
  1.1720 -        wpos = pos & (windowsize - 1);
  1.1721 -        hashval = getHash(in, insize, pos);
  1.1722 -        if(usezeros && hashval == 0) {
  1.1723 -          if(numzeros == 0) numzeros = countZeros(in, insize, pos);
  1.1724 -          else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
  1.1725 -        } else {
  1.1726 -          numzeros = 0;
  1.1727 -        }
  1.1728 -        updateHashChain(hash, wpos, hashval, numzeros);
  1.1729 -      }
  1.1730 -    }
  1.1731 -  } /*end of the loop through each character of input*/
  1.1732 -
  1.1733 -  return error;
  1.1734 -}
  1.1735 -
  1.1736 -/* /////////////////////////////////////////////////////////////////////////// */
  1.1737 -
  1.1738 -static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) {
  1.1739 -  /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
  1.1740 -  2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
  1.1741 -
  1.1742 -  size_t i, j, numdeflateblocks = (datasize + 65534u) / 65535u;
  1.1743 -  unsigned datapos = 0;
  1.1744 -  for(i = 0; i != numdeflateblocks; ++i) {
  1.1745 -    unsigned BFINAL, BTYPE, LEN, NLEN;
  1.1746 -    unsigned char firstbyte;
  1.1747 -
  1.1748 -    BFINAL = (i == numdeflateblocks - 1);
  1.1749 -    BTYPE = 0;
  1.1750 -
  1.1751 -    firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
  1.1752 -    ucvector_push_back(out, firstbyte);
  1.1753 -
  1.1754 -    LEN = 65535;
  1.1755 -    if(datasize - datapos < 65535u) LEN = (unsigned)datasize - datapos;
  1.1756 -    NLEN = 65535 - LEN;
  1.1757 -
  1.1758 -    ucvector_push_back(out, (unsigned char)(LEN & 255));
  1.1759 -    ucvector_push_back(out, (unsigned char)(LEN >> 8u));
  1.1760 -    ucvector_push_back(out, (unsigned char)(NLEN & 255));
  1.1761 -    ucvector_push_back(out, (unsigned char)(NLEN >> 8u));
  1.1762 -
  1.1763 -    /*Decompressed data*/
  1.1764 -    for(j = 0; j < 65535 && datapos < datasize; ++j) {
  1.1765 -      ucvector_push_back(out, data[datapos++]);
  1.1766 -    }
  1.1767 -  }
  1.1768 -
  1.1769 -  return 0;
  1.1770 -}
  1.1771 -
  1.1772 -/*
  1.1773 -write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
  1.1774 -tree_ll: the tree for lit and len codes.
  1.1775 -tree_d: the tree for distance codes.
  1.1776 -*/
  1.1777 -static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded,
  1.1778 -                          const HuffmanTree* tree_ll, const HuffmanTree* tree_d) {
  1.1779 -  size_t i = 0;
  1.1780 -  for(i = 0; i != lz77_encoded->size; ++i) {
  1.1781 -    unsigned val = lz77_encoded->data[i];
  1.1782 -    writeBitsReversed(writer, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
  1.1783 -    if(val > 256) /*for a length code, 3 more things have to be added*/ {
  1.1784 -      unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
  1.1785 -      unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
  1.1786 -      unsigned length_extra_bits = lz77_encoded->data[++i];
  1.1787 -
  1.1788 -      unsigned distance_code = lz77_encoded->data[++i];
  1.1789 -
  1.1790 -      unsigned distance_index = distance_code;
  1.1791 -      unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
  1.1792 -      unsigned distance_extra_bits = lz77_encoded->data[++i];
  1.1793 -
  1.1794 -      writeBits(writer, length_extra_bits, n_length_extra_bits);
  1.1795 -      writeBitsReversed(writer, HuffmanTree_getCode(tree_d, distance_code),
  1.1796 -                       HuffmanTree_getLength(tree_d, distance_code));
  1.1797 -      writeBits(writer, distance_extra_bits, n_distance_extra_bits);
  1.1798 -    }
  1.1799 -  }
  1.1800 -}
  1.1801 -
  1.1802 -/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
  1.1803 -static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash,
  1.1804 -                               const unsigned char* data, size_t datapos, size_t dataend,
  1.1805 -                               const LodePNGCompressSettings* settings, unsigned final) {
  1.1806 -  unsigned error = 0;
  1.1807 -
  1.1808 -  /*
  1.1809 -  A block is compressed as follows: The PNG data is lz77 encoded, resulting in
  1.1810 -  literal bytes and length/distance pairs. This is then huffman compressed with
  1.1811 -  two huffman trees. One huffman tree is used for the lit and len values ("ll"),
  1.1812 -  another huffman tree is used for the dist values ("d"). These two trees are
  1.1813 -  stored using their code lengths, and to compress even more these code lengths
  1.1814 -  are also run-length encoded and huffman compressed. This gives a huffman tree
  1.1815 -  of code lengths "cl". The code lengths used to describe this third tree are
  1.1816 -  the code length code lengths ("clcl").
  1.1817 -  */
  1.1818 -
  1.1819 -  /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
  1.1820 -  uivector lz77_encoded;
  1.1821 -  HuffmanTree tree_ll; /*tree for lit,len values*/
  1.1822 -  HuffmanTree tree_d; /*tree for distance codes*/
  1.1823 -  HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
  1.1824 -  uivector frequencies_ll; /*frequency of lit,len codes*/
  1.1825 -  uivector frequencies_d; /*frequency of dist codes*/
  1.1826 -  uivector frequencies_cl; /*frequency of code length codes*/
  1.1827 -  uivector bitlen_lld; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/
  1.1828 -  uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/
  1.1829 -  /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
  1.1830 -  (these are written as is in the file, it would be crazy to compress these using yet another huffman
  1.1831 -  tree that needs to be represented by yet another set of code lengths)*/
  1.1832 -  uivector bitlen_cl;
  1.1833 -  size_t datasize = dataend - datapos;
  1.1834 -
  1.1835 -  /*
  1.1836 -  Due to the huffman compression of huffman tree representations ("two levels"), there are some analogies:
  1.1837 -  bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
  1.1838 -  bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
  1.1839 -  bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
  1.1840 -  */
  1.1841 -
  1.1842 -  unsigned BFINAL = final;
  1.1843 -  size_t numcodes_ll, numcodes_d, i;
  1.1844 -  unsigned HLIT, HDIST, HCLEN;
  1.1845 -
  1.1846 -  uivector_init(&lz77_encoded);
  1.1847 -  HuffmanTree_init(&tree_ll);
  1.1848 -  HuffmanTree_init(&tree_d);
  1.1849 -  HuffmanTree_init(&tree_cl);
  1.1850 -  uivector_init(&frequencies_ll);
  1.1851 -  uivector_init(&frequencies_d);
  1.1852 -  uivector_init(&frequencies_cl);
  1.1853 -  uivector_init(&bitlen_lld);
  1.1854 -  uivector_init(&bitlen_lld_e);
  1.1855 -  uivector_init(&bitlen_cl);
  1.1856 -
  1.1857 -  /*This while loop never loops due to a break at the end, it is here to
  1.1858 -  allow breaking out of it to the cleanup phase on error conditions.*/
  1.1859 -  while(!error) {
  1.1860 -    if(settings->use_lz77) {
  1.1861 -      error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
  1.1862 -                         settings->minmatch, settings->nicematch, settings->lazymatching);
  1.1863 -      if(error) break;
  1.1864 -    } else {
  1.1865 -      if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
  1.1866 -      for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
  1.1867 -    }
  1.1868 -
  1.1869 -    if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1.1870 -    if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1.1871 -
  1.1872 -    /*Count the frequencies of lit, len and dist codes*/
  1.1873 -    for(i = 0; i != lz77_encoded.size; ++i) {
  1.1874 -      unsigned symbol = lz77_encoded.data[i];
  1.1875 -      ++frequencies_ll.data[symbol];
  1.1876 -      if(symbol > 256) {
  1.1877 -        unsigned dist = lz77_encoded.data[i + 2];
  1.1878 -        ++frequencies_d.data[dist];
  1.1879 -        i += 3;
  1.1880 -      }
  1.1881 -    }
  1.1882 -    frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
  1.1883 -
  1.1884 -    /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
  1.1885 -    error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
  1.1886 -    if(error) break;
  1.1887 -    /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
  1.1888 -    error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
  1.1889 -    if(error) break;
  1.1890 -
  1.1891 -    numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
  1.1892 -    numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
  1.1893 -    /*store the code lengths of both generated trees in bitlen_lld*/
  1.1894 -    for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
  1.1895 -    for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
  1.1896 -
  1.1897 -    /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
  1.1898 -    17 (3-10 zeroes), 18 (11-138 zeroes)*/
  1.1899 -    for(i = 0; i != (unsigned)bitlen_lld.size; ++i) {
  1.1900 -      unsigned j = 0; /*amount of repetitions*/
  1.1901 -      while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
  1.1902 -
  1.1903 -      if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ {
  1.1904 -        ++j; /*include the first zero*/
  1.1905 -        if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ {
  1.1906 -          uivector_push_back(&bitlen_lld_e, 17);
  1.1907 -          uivector_push_back(&bitlen_lld_e, j - 3);
  1.1908 -        } else /*repeat code 18 supports max 138 zeroes*/ {
  1.1909 -          if(j > 138) j = 138;
  1.1910 -          uivector_push_back(&bitlen_lld_e, 18);
  1.1911 -          uivector_push_back(&bitlen_lld_e, j - 11);
  1.1912 -        }
  1.1913 -        i += (j - 1);
  1.1914 -      } else if(j >= 3) /*repeat code for value other than zero*/ {
  1.1915 -        size_t k;
  1.1916 -        unsigned num = j / 6u, rest = j % 6u;
  1.1917 -        uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
  1.1918 -        for(k = 0; k < num; ++k) {
  1.1919 -          uivector_push_back(&bitlen_lld_e, 16);
  1.1920 -          uivector_push_back(&bitlen_lld_e, 6 - 3);
  1.1921 -        }
  1.1922 -        if(rest >= 3) {
  1.1923 -          uivector_push_back(&bitlen_lld_e, 16);
  1.1924 -          uivector_push_back(&bitlen_lld_e, rest - 3);
  1.1925 -        }
  1.1926 -        else j -= rest;
  1.1927 -        i += j;
  1.1928 -      } else /*too short to benefit from repeat code*/ {
  1.1929 -        uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
  1.1930 -      }
  1.1931 -    }
  1.1932 -
  1.1933 -    /*generate tree_cl, the huffmantree of huffmantrees*/
  1.1934 -
  1.1935 -    if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1.1936 -    for(i = 0; i != bitlen_lld_e.size; ++i) {
  1.1937 -      ++frequencies_cl.data[bitlen_lld_e.data[i]];
  1.1938 -      /*after a repeat code come the bits that specify the number of repetitions,
  1.1939 -      those don't need to be in the frequencies_cl calculation*/
  1.1940 -      if(bitlen_lld_e.data[i] >= 16) ++i;
  1.1941 -    }
  1.1942 -
  1.1943 -    error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
  1.1944 -                                            frequencies_cl.size, frequencies_cl.size, 7);
  1.1945 -    if(error) break;
  1.1946 -
  1.1947 -    if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
  1.1948 -    for(i = 0; i != tree_cl.numcodes; ++i) {
  1.1949 -      /*lengths of code length tree is in the order as specified by deflate*/
  1.1950 -      bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
  1.1951 -    }
  1.1952 -    while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) {
  1.1953 -      /*remove zeros at the end, but minimum size must be 4*/
  1.1954 -      if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
  1.1955 -    }
  1.1956 -    if(error) break;
  1.1957 -
  1.1958 -    /*
  1.1959 -    Write everything into the output
  1.1960 -
  1.1961 -    After the BFINAL and BTYPE, the dynamic block consists out of the following:
  1.1962 -    - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
  1.1963 -    - (HCLEN+4)*3 bits code lengths of code length alphabet
  1.1964 -    - HLIT + 257 code lengths of lit/length alphabet (encoded using the code length
  1.1965 -      alphabet, + possible repetition codes 16, 17, 18)
  1.1966 -    - HDIST + 1 code lengths of distance alphabet (encoded using the code length
  1.1967 -      alphabet, + possible repetition codes 16, 17, 18)
  1.1968 -    - compressed data
  1.1969 -    - 256 (end code)
  1.1970 -    */
  1.1971 -
  1.1972 -    /*Write block type*/
  1.1973 -    writeBits(writer, BFINAL, 1);
  1.1974 -    writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/
  1.1975 -    writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/
  1.1976 -
  1.1977 -    /*write the HLIT, HDIST and HCLEN values*/
  1.1978 -    HLIT = (unsigned)(numcodes_ll - 257);
  1.1979 -    HDIST = (unsigned)(numcodes_d - 1);
  1.1980 -    HCLEN = (unsigned)bitlen_cl.size - 4;
  1.1981 -    /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
  1.1982 -    while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
  1.1983 -    writeBits(writer, HLIT, 5);
  1.1984 -    writeBits(writer, HDIST, 5);
  1.1985 -    writeBits(writer, HCLEN, 4);
  1.1986 -
  1.1987 -    /*write the code lengths of the code length alphabet*/
  1.1988 -    for(i = 0; i != HCLEN + 4; ++i) writeBits(writer, bitlen_cl.data[i], 3);
  1.1989 -
  1.1990 -    /*write the lengths of the lit/len AND the dist alphabet*/
  1.1991 -    for(i = 0; i != bitlen_lld_e.size; ++i) {
  1.1992 -      writeBitsReversed(writer, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
  1.1993 -                        HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
  1.1994 -      /*extra bits of repeat codes*/
  1.1995 -      if(bitlen_lld_e.data[i] == 16) writeBits(writer, bitlen_lld_e.data[++i], 2);
  1.1996 -      else if(bitlen_lld_e.data[i] == 17) writeBits(writer, bitlen_lld_e.data[++i], 3);
  1.1997 -      else if(bitlen_lld_e.data[i] == 18) writeBits(writer, bitlen_lld_e.data[++i], 7);
  1.1998 -    }
  1.1999 -
  1.2000 -    /*write the compressed data symbols*/
  1.2001 -    writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
  1.2002 -    /*error: the length of the end code 256 must be larger than 0*/
  1.2003 -    if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
  1.2004 -
  1.2005 -    /*write the end code*/
  1.2006 -    writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
  1.2007 -
  1.2008 -    break; /*end of error-while*/
  1.2009 -  }
  1.2010 -
  1.2011 -  /*cleanup*/
  1.2012 -  uivector_cleanup(&lz77_encoded);
  1.2013 -  HuffmanTree_cleanup(&tree_ll);
  1.2014 -  HuffmanTree_cleanup(&tree_d);
  1.2015 -  HuffmanTree_cleanup(&tree_cl);
  1.2016 -  uivector_cleanup(&frequencies_ll);
  1.2017 -  uivector_cleanup(&frequencies_d);
  1.2018 -  uivector_cleanup(&frequencies_cl);
  1.2019 -  uivector_cleanup(&bitlen_lld_e);
  1.2020 -  uivector_cleanup(&bitlen_lld);
  1.2021 -  uivector_cleanup(&bitlen_cl);
  1.2022 -
  1.2023 -  return error;
  1.2024 -}
  1.2025 -
  1.2026 -static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash,
  1.2027 -                             const unsigned char* data,
  1.2028 -                             size_t datapos, size_t dataend,
  1.2029 -                             const LodePNGCompressSettings* settings, unsigned final) {
  1.2030 -  HuffmanTree tree_ll; /*tree for literal values and length codes*/
  1.2031 -  HuffmanTree tree_d; /*tree for distance codes*/
  1.2032 -
  1.2033 -  unsigned BFINAL = final;
  1.2034 -  unsigned error = 0;
  1.2035 -  size_t i;
  1.2036 -
  1.2037 -  HuffmanTree_init(&tree_ll);
  1.2038 -  HuffmanTree_init(&tree_d);
  1.2039 -
  1.2040 -  generateFixedLitLenTree(&tree_ll);
  1.2041 -  generateFixedDistanceTree(&tree_d);
  1.2042 -
  1.2043 -  writeBits(writer, BFINAL, 1);
  1.2044 -  writeBits(writer, 1, 1); /*first bit of BTYPE*/
  1.2045 -  writeBits(writer, 0, 1); /*second bit of BTYPE*/
  1.2046 -
  1.2047 -  if(settings->use_lz77) /*LZ77 encoded*/ {
  1.2048 -    uivector lz77_encoded;
  1.2049 -    uivector_init(&lz77_encoded);
  1.2050 -    error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
  1.2051 -                       settings->minmatch, settings->nicematch, settings->lazymatching);
  1.2052 -    if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
  1.2053 -    uivector_cleanup(&lz77_encoded);
  1.2054 -  } else /*no LZ77, but still will be Huffman compressed*/ {
  1.2055 -    for(i = datapos; i < dataend; ++i) {
  1.2056 -      writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
  1.2057 -    }
  1.2058 -  }
  1.2059 -  /*add END code*/
  1.2060 -  if(!error) writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
  1.2061 -
  1.2062 -  /*cleanup*/
  1.2063 -  HuffmanTree_cleanup(&tree_ll);
  1.2064 -  HuffmanTree_cleanup(&tree_d);
  1.2065 -
  1.2066 -  return error;
  1.2067 -}
  1.2068 -
  1.2069 -static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
  1.2070 -                                 const LodePNGCompressSettings* settings) {
  1.2071 -  unsigned error = 0;
  1.2072 -  size_t i, blocksize, numdeflateblocks;
  1.2073 -  Hash hash;
  1.2074 -  LodePNGBitWriter writer;
  1.2075 -
  1.2076 -  LodePNGBitWriter_init(&writer, out);
  1.2077 -
  1.2078 -  if(settings->btype > 2) return 61;
  1.2079 -  else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
  1.2080 -  else if(settings->btype == 1) blocksize = insize;
  1.2081 -  else /*if(settings->btype == 2)*/ {
  1.2082 -    /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
  1.2083 -    blocksize = insize / 8u + 8;
  1.2084 -    if(blocksize < 65536) blocksize = 65536;
  1.2085 -    if(blocksize > 262144) blocksize = 262144;
  1.2086 -  }
  1.2087 -
  1.2088 -  numdeflateblocks = (insize + blocksize - 1) / blocksize;
  1.2089 -  if(numdeflateblocks == 0) numdeflateblocks = 1;
  1.2090 -
  1.2091 -  error = hash_init(&hash, settings->windowsize);
  1.2092 -  if(error) return error;
  1.2093 -
  1.2094 -  for(i = 0; i != numdeflateblocks && !error; ++i) {
  1.2095 -    unsigned final = (i == numdeflateblocks - 1);
  1.2096 -    size_t start = i * blocksize;
  1.2097 -    size_t end = start + blocksize;
  1.2098 -    if(end > insize) end = insize;
  1.2099 -
  1.2100 -    if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final);
  1.2101 -    else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final);
  1.2102 -  }
  1.2103 -
  1.2104 -  hash_cleanup(&hash);
  1.2105 -
  1.2106 -  return error;
  1.2107 -}
  1.2108 -
  1.2109 -unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
  1.2110 -                         const unsigned char* in, size_t insize,
  1.2111 -                         const LodePNGCompressSettings* settings) {
  1.2112 -  unsigned error;
  1.2113 -  ucvector v;
  1.2114 -  ucvector_init_buffer(&v, *out, *outsize);
  1.2115 -  error = lodepng_deflatev(&v, in, insize, settings);
  1.2116 -  *out = v.data;
  1.2117 -  *outsize = v.size;
  1.2118 -  return error;
  1.2119 -}
  1.2120 -
  1.2121 -static unsigned deflate(unsigned char** out, size_t* outsize,
  1.2122 -                        const unsigned char* in, size_t insize,
  1.2123 -                        const LodePNGCompressSettings* settings) {
  1.2124 -  if(settings->custom_deflate) {
  1.2125 -    return settings->custom_deflate(out, outsize, in, insize, settings);
  1.2126 -  } else {
  1.2127 -    return lodepng_deflate(out, outsize, in, insize, settings);
  1.2128 -  }
  1.2129 -}
  1.2130 -
  1.2131 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.2132 -
  1.2133 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2134 -/* / Adler32                                                                / */
  1.2135 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2136 -
  1.2137 -static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) {
  1.2138 -  unsigned s1 = adler & 0xffffu;
  1.2139 -  unsigned s2 = (adler >> 16u) & 0xffffu;
  1.2140 -
  1.2141 -  while(len != 0u) {
  1.2142 -    unsigned i;
  1.2143 -    /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
  1.2144 -    unsigned amount = len > 5552u ? 5552u : len;
  1.2145 -    len -= amount;
  1.2146 -    for(i = 0; i != amount; ++i) {
  1.2147 -      s1 += (*data++);
  1.2148 -      s2 += s1;
  1.2149 -    }
  1.2150 -    s1 %= 65521u;
  1.2151 -    s2 %= 65521u;
  1.2152 -  }
  1.2153 -
  1.2154 -  return (s2 << 16u) | s1;
  1.2155 -}
  1.2156 -
  1.2157 -/*Return the adler32 of the bytes data[0..len-1]*/
  1.2158 -static unsigned adler32(const unsigned char* data, unsigned len) {
  1.2159 -  return update_adler32(1u, data, len);
  1.2160 -}
  1.2161 -
  1.2162 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2163 -/* / Zlib                                                                   / */
  1.2164 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2165 -
  1.2166 -#ifdef LODEPNG_COMPILE_DECODER
  1.2167 -
  1.2168 -unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2169 -                                 size_t insize, const LodePNGDecompressSettings* settings) {
  1.2170 -  unsigned error = 0;
  1.2171 -  unsigned CM, CINFO, FDICT;
  1.2172 -
  1.2173 -  if(insize < 2) return 53; /*error, size of zlib data too small*/
  1.2174 -  /*read information from zlib header*/
  1.2175 -  if((in[0] * 256 + in[1]) % 31 != 0) {
  1.2176 -    /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
  1.2177 -    return 24;
  1.2178 -  }
  1.2179 -
  1.2180 -  CM = in[0] & 15;
  1.2181 -  CINFO = (in[0] >> 4) & 15;
  1.2182 -  /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
  1.2183 -  FDICT = (in[1] >> 5) & 1;
  1.2184 -  /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
  1.2185 -
  1.2186 -  if(CM != 8 || CINFO > 7) {
  1.2187 -    /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
  1.2188 -    return 25;
  1.2189 -  }
  1.2190 -  if(FDICT != 0) {
  1.2191 -    /*error: the specification of PNG says about the zlib stream:
  1.2192 -      "The additional flags shall not specify a preset dictionary."*/
  1.2193 -    return 26;
  1.2194 -  }
  1.2195 -
  1.2196 -  error = inflate(out, outsize, in + 2, insize - 2, settings);
  1.2197 -  if(error) return error;
  1.2198 -
  1.2199 -  if(!settings->ignore_adler32) {
  1.2200 -    unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
  1.2201 -    unsigned checksum = adler32(*out, (unsigned)(*outsize));
  1.2202 -    if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
  1.2203 -  }
  1.2204 -
  1.2205 -  return 0; /*no error*/
  1.2206 -}
  1.2207 -
  1.2208 -static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2209 -                                size_t insize, const LodePNGDecompressSettings* settings) {
  1.2210 -  if(settings->custom_zlib) {
  1.2211 -    return settings->custom_zlib(out, outsize, in, insize, settings);
  1.2212 -  } else {
  1.2213 -    return lodepng_zlib_decompress(out, outsize, in, insize, settings);
  1.2214 -  }
  1.2215 -}
  1.2216 -
  1.2217 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.2218 -
  1.2219 -#ifdef LODEPNG_COMPILE_ENCODER
  1.2220 -
  1.2221 -unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2222 -                               size_t insize, const LodePNGCompressSettings* settings) {
  1.2223 -  size_t i;
  1.2224 -  unsigned error;
  1.2225 -  unsigned char* deflatedata = 0;
  1.2226 -  size_t deflatesize = 0;
  1.2227 -
  1.2228 -  error = deflate(&deflatedata, &deflatesize, in, insize, settings);
  1.2229 -
  1.2230 -  *out = NULL;
  1.2231 -  *outsize = 0;
  1.2232 -  if(!error) {
  1.2233 -    *outsize = deflatesize + 6;
  1.2234 -    *out = (unsigned char*)lodepng_malloc(*outsize);
  1.2235 -    if(!out) error = 83; /*alloc fail*/
  1.2236 -  }
  1.2237 -
  1.2238 -  if(!error) {
  1.2239 -    unsigned ADLER32 = adler32(in, (unsigned)insize);
  1.2240 -    /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
  1.2241 -    unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
  1.2242 -    unsigned FLEVEL = 0;
  1.2243 -    unsigned FDICT = 0;
  1.2244 -    unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
  1.2245 -    unsigned FCHECK = 31 - CMFFLG % 31;
  1.2246 -    CMFFLG += FCHECK;
  1.2247 -
  1.2248 -    (*out)[0] = (unsigned char)(CMFFLG >> 8);
  1.2249 -    (*out)[1] = (unsigned char)(CMFFLG & 255);
  1.2250 -    for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i];
  1.2251 -    lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32);
  1.2252 -  }
  1.2253 -
  1.2254 -  lodepng_free(deflatedata);
  1.2255 -  return error;
  1.2256 -}
  1.2257 -
  1.2258 -/* compress using the default or custom zlib function */
  1.2259 -static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2260 -                              size_t insize, const LodePNGCompressSettings* settings) {
  1.2261 -  if(settings->custom_zlib) {
  1.2262 -    return settings->custom_zlib(out, outsize, in, insize, settings);
  1.2263 -  } else {
  1.2264 -    return lodepng_zlib_compress(out, outsize, in, insize, settings);
  1.2265 -  }
  1.2266 -}
  1.2267 -
  1.2268 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.2269 -
  1.2270 -#else /*no LODEPNG_COMPILE_ZLIB*/
  1.2271 -
  1.2272 -#ifdef LODEPNG_COMPILE_DECODER
  1.2273 -static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2274 -                                size_t insize, const LodePNGDecompressSettings* settings) {
  1.2275 -  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
  1.2276 -  return settings->custom_zlib(out, outsize, in, insize, settings);
  1.2277 -}
  1.2278 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.2279 -#ifdef LODEPNG_COMPILE_ENCODER
  1.2280 -static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.2281 -                              size_t insize, const LodePNGCompressSettings* settings) {
  1.2282 -  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
  1.2283 -  return settings->custom_zlib(out, outsize, in, insize, settings);
  1.2284 -}
  1.2285 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.2286 -
  1.2287 -#endif /*LODEPNG_COMPILE_ZLIB*/
  1.2288 -
  1.2289 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2290 -
  1.2291 -#ifdef LODEPNG_COMPILE_ENCODER
  1.2292 -
  1.2293 -/*this is a good tradeoff between speed and compression ratio*/
  1.2294 -#define DEFAULT_WINDOWSIZE 2048
  1.2295 -
  1.2296 -void lodepng_compress_settings_init(LodePNGCompressSettings* settings) {
  1.2297 -  /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
  1.2298 -  settings->btype = 2;
  1.2299 -  settings->use_lz77 = 1;
  1.2300 -  settings->windowsize = DEFAULT_WINDOWSIZE;
  1.2301 -  settings->minmatch = 3;
  1.2302 -  settings->nicematch = 128;
  1.2303 -  settings->lazymatching = 1;
  1.2304 -
  1.2305 -  settings->custom_zlib = 0;
  1.2306 -  settings->custom_deflate = 0;
  1.2307 -  settings->custom_context = 0;
  1.2308 -}
  1.2309 -
  1.2310 -const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
  1.2311 -
  1.2312 -
  1.2313 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.2314 -
  1.2315 -#ifdef LODEPNG_COMPILE_DECODER
  1.2316 -
  1.2317 -void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) {
  1.2318 -  settings->ignore_adler32 = 0;
  1.2319 -  settings->ignore_nlen = 0;
  1.2320 -
  1.2321 -  settings->custom_zlib = 0;
  1.2322 -  settings->custom_inflate = 0;
  1.2323 -  settings->custom_context = 0;
  1.2324 -}
  1.2325 -
  1.2326 -const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0};
  1.2327 -
  1.2328 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.2329 -
  1.2330 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2331 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2332 -/* // End of Zlib related code. Begin of PNG related code.                 // */
  1.2333 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2334 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2335 -
  1.2336 -#ifdef LODEPNG_COMPILE_PNG
  1.2337 -
  1.2338 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2339 -/* / CRC32                                                                  / */
  1.2340 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2341 -
  1.2342 -
  1.2343 -#ifndef LODEPNG_NO_COMPILE_CRC
  1.2344 -/* CRC polynomial: 0xedb88320 */
  1.2345 -static unsigned lodepng_crc32_table[256] = {
  1.2346 -           0u, 1996959894u, 3993919788u, 2567524794u,  124634137u, 1886057615u, 3915621685u, 2657392035u,
  1.2347 -   249268274u, 2044508324u, 3772115230u, 2547177864u,  162941995u, 2125561021u, 3887607047u, 2428444049u,
  1.2348 -   498536548u, 1789927666u, 4089016648u, 2227061214u,  450548861u, 1843258603u, 4107580753u, 2211677639u,
  1.2349 -   325883990u, 1684777152u, 4251122042u, 2321926636u,  335633487u, 1661365465u, 4195302755u, 2366115317u,
  1.2350 -   997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
  1.2351 -   901097722u, 1119000684u, 3686517206u, 2898065728u,  853044451u, 1172266101u, 3705015759u, 2882616665u,
  1.2352 -   651767980u, 1373503546u, 3369554304u, 3218104598u,  565507253u, 1454621731u, 3485111705u, 3099436303u,
  1.2353 -   671266974u, 1594198024u, 3322730930u, 2970347812u,  795835527u, 1483230225u, 3244367275u, 3060149565u,
  1.2354 -  1994146192u,   31158534u, 2563907772u, 4023717930u, 1907459465u,  112637215u, 2680153253u, 3904427059u,
  1.2355 -  2013776290u,  251722036u, 2517215374u, 3775830040u, 2137656763u,  141376813u, 2439277719u, 3865271297u,
  1.2356 -  1802195444u,  476864866u, 2238001368u, 4066508878u, 1812370925u,  453092731u, 2181625025u, 4111451223u,
  1.2357 -  1706088902u,  314042704u, 2344532202u, 4240017532u, 1658658271u,  366619977u, 2362670323u, 4224994405u,
  1.2358 -  1303535960u,  984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
  1.2359 -  1131014506u,  879679996u, 2909243462u, 3663771856u, 1141124467u,  855842277u, 2852801631u, 3708648649u,
  1.2360 -  1342533948u,  654459306u, 3188396048u, 3373015174u, 1466479909u,  544179635u, 3110523913u, 3462522015u,
  1.2361 -  1591671054u,  702138776u, 2966460450u, 3352799412u, 1504918807u,  783551873u, 3082640443u, 3233442989u,
  1.2362 -  3988292384u, 2596254646u,   62317068u, 1957810842u, 3939845945u, 2647816111u,   81470997u, 1943803523u,
  1.2363 -  3814918930u, 2489596804u,  225274430u, 2053790376u, 3826175755u, 2466906013u,  167816743u, 2097651377u,
  1.2364 -  4027552580u, 2265490386u,  503444072u, 1762050814u, 4150417245u, 2154129355u,  426522225u, 1852507879u,
  1.2365 -  4275313526u, 2312317920u,  282753626u, 1742555852u, 4189708143u, 2394877945u,  397917763u, 1622183637u,
  1.2366 -  3604390888u, 2714866558u,  953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
  1.2367 -  3624741850u, 2936675148u,  906185462u, 1090812512u, 3747672003u, 2825379669u,  829329135u, 1181335161u,
  1.2368 -  3412177804u, 3160834842u,  628085408u, 1382605366u, 3423369109u, 3138078467u,  570562233u, 1426400815u,
  1.2369 -  3317316542u, 2998733608u,  733239954u, 1555261956u, 3268935591u, 3050360625u,  752459403u, 1541320221u,
  1.2370 -  2607071920u, 3965973030u, 1969922972u,   40735498u, 2617837225u, 3943577151u, 1913087877u,   83908371u,
  1.2371 -  2512341634u, 3803740692u, 2075208622u,  213261112u, 2463272603u, 3855990285u, 2094854071u,  198958881u,
  1.2372 -  2262029012u, 4057260610u, 1759359992u,  534414190u, 2176718541u, 4139329115u, 1873836001u,  414664567u,
  1.2373 -  2282248934u, 4279200368u, 1711684554u,  285281116u, 2405801727u, 4167216745u, 1634467795u,  376229701u,
  1.2374 -  2685067896u, 3608007406u, 1308918612u,  956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
  1.2375 -  2932959818u, 3654703836u, 1088359270u,  936918000u, 2847714899u, 3736837829u, 1202900863u,  817233897u,
  1.2376 -  3183342108u, 3401237130u, 1404277552u,  615818150u, 3134207493u, 3453421203u, 1423857449u,  601450431u,
  1.2377 -  3009837614u, 3294710456u, 1567103746u,  711928724u, 3020668471u, 3272380065u, 1510334235u,  755167117u
  1.2378 -};
  1.2379 -
  1.2380 -/*Return the CRC of the bytes buf[0..len-1].*/
  1.2381 -unsigned lodepng_crc32(const unsigned char* data, size_t length) {
  1.2382 -  unsigned r = 0xffffffffu;
  1.2383 -  size_t i;
  1.2384 -  for(i = 0; i < length; ++i) {
  1.2385 -    r = lodepng_crc32_table[(r ^ data[i]) & 0xffu] ^ (r >> 8u);
  1.2386 -  }
  1.2387 -  return r ^ 0xffffffffu;
  1.2388 -}
  1.2389 -#else /* !LODEPNG_NO_COMPILE_CRC */
  1.2390 -unsigned lodepng_crc32(const unsigned char* data, size_t length);
  1.2391 -#endif /* !LODEPNG_NO_COMPILE_CRC */
  1.2392 -
  1.2393 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2394 -/* / Reading and writing PNG color channel bits                             / */
  1.2395 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2396 -
  1.2397 -/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,
  1.2398 -so LodePNGBitWriter and LodePNGBitReader can't be used for those. */
  1.2399 -
  1.2400 -static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) {
  1.2401 -  unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
  1.2402 -  ++(*bitpointer);
  1.2403 -  return result;
  1.2404 -}
  1.2405 -
  1.2406 -/* TODO: make this faster */
  1.2407 -static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
  1.2408 -  unsigned result = 0;
  1.2409 -  size_t i;
  1.2410 -  for(i = 0 ; i < nbits; ++i) {
  1.2411 -    result <<= 1;
  1.2412 -    result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
  1.2413 -  }
  1.2414 -  return result;
  1.2415 -}
  1.2416 -
  1.2417 -static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {
  1.2418 -  /*the current bit in bitstream may be 0 or 1 for this to work*/
  1.2419 -  if(bit == 0) bitstream[(*bitpointer) >> 3] &=  (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
  1.2420 -  else         bitstream[(*bitpointer) >> 3] |=  (1 << (7 - ((*bitpointer) & 0x7)));
  1.2421 -  ++(*bitpointer);
  1.2422 -}
  1.2423 -
  1.2424 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2425 -/* / PNG chunks                                                             / */
  1.2426 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2427 -
  1.2428 -unsigned lodepng_chunk_length(const unsigned char* chunk) {
  1.2429 -  return lodepng_read32bitInt(&chunk[0]);
  1.2430 -}
  1.2431 -
  1.2432 -void lodepng_chunk_type(char type[5], const unsigned char* chunk) {
  1.2433 -  unsigned i;
  1.2434 -  for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
  1.2435 -  type[4] = 0; /*null termination char*/
  1.2436 -}
  1.2437 -
  1.2438 -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) {
  1.2439 -  if(lodepng_strlen(type) != 4) return 0;
  1.2440 -  return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
  1.2441 -}
  1.2442 -
  1.2443 -unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) {
  1.2444 -  return((chunk[4] & 32) != 0);
  1.2445 -}
  1.2446 -
  1.2447 -unsigned char lodepng_chunk_private(const unsigned char* chunk) {
  1.2448 -  return((chunk[6] & 32) != 0);
  1.2449 -}
  1.2450 -
  1.2451 -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) {
  1.2452 -  return((chunk[7] & 32) != 0);
  1.2453 -}
  1.2454 -
  1.2455 -unsigned char* lodepng_chunk_data(unsigned char* chunk) {
  1.2456 -  return &chunk[8];
  1.2457 -}
  1.2458 -
  1.2459 -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) {
  1.2460 -  return &chunk[8];
  1.2461 -}
  1.2462 -
  1.2463 -unsigned lodepng_chunk_check_crc(const unsigned char* chunk) {
  1.2464 -  unsigned length = lodepng_chunk_length(chunk);
  1.2465 -  unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
  1.2466 -  /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
  1.2467 -  unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
  1.2468 -  if(CRC != checksum) return 1;
  1.2469 -  else return 0;
  1.2470 -}
  1.2471 -
  1.2472 -void lodepng_chunk_generate_crc(unsigned char* chunk) {
  1.2473 -  unsigned length = lodepng_chunk_length(chunk);
  1.2474 -  unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
  1.2475 -  lodepng_set32bitInt(chunk + 8 + length, CRC);
  1.2476 -}
  1.2477 -
  1.2478 -unsigned char* lodepng_chunk_next(unsigned char* chunk) {
  1.2479 -  if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
  1.2480 -    && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
  1.2481 -    /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
  1.2482 -    return chunk + 8;
  1.2483 -  } else {
  1.2484 -    unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  1.2485 -    return chunk + total_chunk_length;
  1.2486 -  }
  1.2487 -}
  1.2488 -
  1.2489 -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) {
  1.2490 -  if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
  1.2491 -    && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
  1.2492 -    /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
  1.2493 -    return chunk + 8;
  1.2494 -  } else {
  1.2495 -    unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  1.2496 -    return chunk + total_chunk_length;
  1.2497 -  }
  1.2498 -}
  1.2499 -
  1.2500 -unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]) {
  1.2501 -  for(;;) {
  1.2502 -    if(chunk + 12 >= end) return 0;
  1.2503 -    if(lodepng_chunk_type_equals(chunk, type)) return chunk;
  1.2504 -    chunk = lodepng_chunk_next(chunk);
  1.2505 -  }
  1.2506 -}
  1.2507 -
  1.2508 -const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) {
  1.2509 -  for(;;) {
  1.2510 -    if(chunk + 12 >= end) return 0;
  1.2511 -    if(lodepng_chunk_type_equals(chunk, type)) return chunk;
  1.2512 -    chunk = lodepng_chunk_next_const(chunk);
  1.2513 -  }
  1.2514 -}
  1.2515 -
  1.2516 -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) {
  1.2517 -  unsigned i;
  1.2518 -  unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  1.2519 -  unsigned char *chunk_start, *new_buffer;
  1.2520 -  size_t new_length = (*outlength) + total_chunk_length;
  1.2521 -  if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
  1.2522 -
  1.2523 -  new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
  1.2524 -  if(!new_buffer) return 83; /*alloc fail*/
  1.2525 -  (*out) = new_buffer;
  1.2526 -  (*outlength) = new_length;
  1.2527 -  chunk_start = &(*out)[new_length - total_chunk_length];
  1.2528 -
  1.2529 -  for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
  1.2530 -
  1.2531 -  return 0;
  1.2532 -}
  1.2533 -
  1.2534 -unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
  1.2535 -                              const char* type, const unsigned char* data) {
  1.2536 -  unsigned i;
  1.2537 -  unsigned char *chunk, *new_buffer;
  1.2538 -  size_t new_length = (*outlength) + length + 12;
  1.2539 -  if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
  1.2540 -  new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
  1.2541 -  if(!new_buffer) return 83; /*alloc fail*/
  1.2542 -  (*out) = new_buffer;
  1.2543 -  (*outlength) = new_length;
  1.2544 -  chunk = &(*out)[(*outlength) - length - 12];
  1.2545 -
  1.2546 -  /*1: length*/
  1.2547 -  lodepng_set32bitInt(chunk, (unsigned)length);
  1.2548 -
  1.2549 -  /*2: chunk name (4 letters)*/
  1.2550 -  chunk[4] = (unsigned char)type[0];
  1.2551 -  chunk[5] = (unsigned char)type[1];
  1.2552 -  chunk[6] = (unsigned char)type[2];
  1.2553 -  chunk[7] = (unsigned char)type[3];
  1.2554 -
  1.2555 -  /*3: the data*/
  1.2556 -  for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
  1.2557 -
  1.2558 -  /*4: CRC (of the chunkname characters and the data)*/
  1.2559 -  lodepng_chunk_generate_crc(chunk);
  1.2560 -
  1.2561 -  return 0;
  1.2562 -}
  1.2563 -
  1.2564 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2565 -/* / Color types, channels, bits                                            / */
  1.2566 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2567 -
  1.2568 -/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.
  1.2569 -Return value is a LodePNG error code.*/
  1.2570 -static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) {
  1.2571 -  switch(colortype) {
  1.2572 -    case LCT_GREY:       if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break;
  1.2573 -    case LCT_RGB:        if(!(                                 bd == 8 || bd == 16)) return 37; break;
  1.2574 -    case LCT_PALETTE:    if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8            )) return 37; break;
  1.2575 -    case LCT_GREY_ALPHA: if(!(                                 bd == 8 || bd == 16)) return 37; break;
  1.2576 -    case LCT_RGBA:       if(!(                                 bd == 8 || bd == 16)) return 37; break;
  1.2577 -    default: return 31; /* invalid color type */
  1.2578 -  }
  1.2579 -  return 0; /*allowed color type / bits combination*/
  1.2580 -}
  1.2581 -
  1.2582 -static unsigned getNumColorChannels(LodePNGColorType colortype) {
  1.2583 -  switch(colortype) {
  1.2584 -    case LCT_GREY: return 1;
  1.2585 -    case LCT_RGB: return 3;
  1.2586 -    case LCT_PALETTE: return 1;
  1.2587 -    case LCT_GREY_ALPHA: return 2;
  1.2588 -    case LCT_RGBA: return 4;
  1.2589 -    default: return 0; /*invalid color type*/
  1.2590 -  }
  1.2591 -}
  1.2592 -
  1.2593 -static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) {
  1.2594 -  /*bits per pixel is amount of channels * bits per channel*/
  1.2595 -  return getNumColorChannels(colortype) * bitdepth;
  1.2596 -}
  1.2597 -
  1.2598 -/* ////////////////////////////////////////////////////////////////////////// */
  1.2599 -
  1.2600 -void lodepng_color_mode_init(LodePNGColorMode* info) {
  1.2601 -  info->key_defined = 0;
  1.2602 -  info->key_r = info->key_g = info->key_b = 0;
  1.2603 -  info->colortype = LCT_RGBA;
  1.2604 -  info->bitdepth = 8;
  1.2605 -  info->palette = 0;
  1.2606 -  info->palettesize = 0;
  1.2607 -}
  1.2608 -
  1.2609 -void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) {
  1.2610 -  size_t i;
  1.2611 -  /*room for 256 colors with 4 bytes each. Using realloc to avoid leak if it is being overwritten*/
  1.2612 -  info->palette = (unsigned char*)lodepng_realloc(info->palette, 1024);
  1.2613 -  if(!info->palette) return; /*alloc fail*/
  1.2614 -  for(i = 0; i != 256; ++i) {
  1.2615 -    /*Initialize all unused colors with black, the value used for invalid palette indices.
  1.2616 -    This is an error according to the PNG spec, but common PNG decoders make it black instead.
  1.2617 -    That makes color conversion slightly faster due to no error handling needed.*/
  1.2618 -    info->palette[i * 4 + 0] = 0;
  1.2619 -    info->palette[i * 4 + 1] = 0;
  1.2620 -    info->palette[i * 4 + 2] = 0;
  1.2621 -    info->palette[i * 4 + 3] = 255;
  1.2622 -  }
  1.2623 -}
  1.2624 -
  1.2625 -void lodepng_color_mode_cleanup(LodePNGColorMode* info) {
  1.2626 -  lodepng_palette_clear(info);
  1.2627 -}
  1.2628 -
  1.2629 -unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) {
  1.2630 -  size_t i;
  1.2631 -  lodepng_color_mode_cleanup(dest);
  1.2632 -  *dest = *source;
  1.2633 -  if(source->palette) {
  1.2634 -    dest->palette = (unsigned char*)lodepng_malloc(1024);
  1.2635 -    if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
  1.2636 -    for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
  1.2637 -  }
  1.2638 -  return 0;
  1.2639 -}
  1.2640 -
  1.2641 -LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) {
  1.2642 -  LodePNGColorMode result;
  1.2643 -  lodepng_color_mode_init(&result);
  1.2644 -  result.colortype = colortype;
  1.2645 -  result.bitdepth = bitdepth;
  1.2646 -  return result;
  1.2647 -}
  1.2648 -
  1.2649 -static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) {
  1.2650 -  size_t i;
  1.2651 -  if(a->colortype != b->colortype) return 0;
  1.2652 -  if(a->bitdepth != b->bitdepth) return 0;
  1.2653 -  if(a->key_defined != b->key_defined) return 0;
  1.2654 -  if(a->key_defined) {
  1.2655 -    if(a->key_r != b->key_r) return 0;
  1.2656 -    if(a->key_g != b->key_g) return 0;
  1.2657 -    if(a->key_b != b->key_b) return 0;
  1.2658 -  }
  1.2659 -  if(a->palettesize != b->palettesize) return 0;
  1.2660 -  for(i = 0; i != a->palettesize * 4; ++i) {
  1.2661 -    if(a->palette[i] != b->palette[i]) return 0;
  1.2662 -  }
  1.2663 -  return 1;
  1.2664 -}
  1.2665 -
  1.2666 -void lodepng_palette_clear(LodePNGColorMode* info) {
  1.2667 -  if(info->palette) lodepng_free(info->palette);
  1.2668 -  info->palette = 0;
  1.2669 -  info->palettesize = 0;
  1.2670 -}
  1.2671 -
  1.2672 -unsigned lodepng_palette_add(LodePNGColorMode* info,
  1.2673 -                             unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  1.2674 -  if(!info->palette) /*allocate palette if empty*/ {
  1.2675 -    lodepng_color_mode_alloc_palette(info);
  1.2676 -    if(!info->palette) return 83; /*alloc fail*/
  1.2677 -  }
  1.2678 -  if(info->palettesize >= 256) {
  1.2679 -    return 108; /*too many palette values*/
  1.2680 -  }
  1.2681 -  info->palette[4 * info->palettesize + 0] = r;
  1.2682 -  info->palette[4 * info->palettesize + 1] = g;
  1.2683 -  info->palette[4 * info->palettesize + 2] = b;
  1.2684 -  info->palette[4 * info->palettesize + 3] = a;
  1.2685 -  ++info->palettesize;
  1.2686 -  return 0;
  1.2687 -}
  1.2688 -
  1.2689 -/*calculate bits per pixel out of colortype and bitdepth*/
  1.2690 -unsigned lodepng_get_bpp(const LodePNGColorMode* info) {
  1.2691 -  return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
  1.2692 -}
  1.2693 -
  1.2694 -unsigned lodepng_get_channels(const LodePNGColorMode* info) {
  1.2695 -  return getNumColorChannels(info->colortype);
  1.2696 -}
  1.2697 -
  1.2698 -unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) {
  1.2699 -  return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
  1.2700 -}
  1.2701 -
  1.2702 -unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) {
  1.2703 -  return (info->colortype & 4) != 0; /*4 or 6*/
  1.2704 -}
  1.2705 -
  1.2706 -unsigned lodepng_is_palette_type(const LodePNGColorMode* info) {
  1.2707 -  return info->colortype == LCT_PALETTE;
  1.2708 -}
  1.2709 -
  1.2710 -unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) {
  1.2711 -  size_t i;
  1.2712 -  for(i = 0; i != info->palettesize; ++i) {
  1.2713 -    if(info->palette[i * 4 + 3] < 255) return 1;
  1.2714 -  }
  1.2715 -  return 0;
  1.2716 -}
  1.2717 -
  1.2718 -unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) {
  1.2719 -  return info->key_defined
  1.2720 -      || lodepng_is_alpha_type(info)
  1.2721 -      || lodepng_has_palette_alpha(info);
  1.2722 -}
  1.2723 -
  1.2724 -static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
  1.2725 -  size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
  1.2726 -  size_t n = (size_t)w * (size_t)h;
  1.2727 -  return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;
  1.2728 -}
  1.2729 -
  1.2730 -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) {
  1.2731 -  return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
  1.2732 -}
  1.2733 -
  1.2734 -
  1.2735 -#ifdef LODEPNG_COMPILE_PNG
  1.2736 -#ifdef LODEPNG_COMPILE_DECODER
  1.2737 -
  1.2738 -/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
  1.2739 -and in addition has one extra byte per line: the filter byte. So this gives a larger
  1.2740 -result than lodepng_get_raw_size. */
  1.2741 -static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) {
  1.2742 -  size_t bpp = lodepng_get_bpp(color);
  1.2743 -  /* + 1 for the filter byte, and possibly plus padding bits per line */
  1.2744 -  size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;
  1.2745 -  return (size_t)h * line;
  1.2746 -}
  1.2747 -
  1.2748 -/*Safely checks whether size_t overflow can be caused due to amount of pixels.
  1.2749 -This check is overcautious rather than precise. If this check indicates no overflow,
  1.2750 -you can safely compute in a size_t (but not an unsigned):
  1.2751 --(size_t)w * (size_t)h * 8
  1.2752 --amount of bytes in IDAT (including filter, padding and Adam7 bytes)
  1.2753 --amount of bytes in raw color model
  1.2754 -Returns 1 if overflow possible, 0 if not.
  1.2755 -*/
  1.2756 -static int lodepng_pixel_overflow(unsigned w, unsigned h,
  1.2757 -                                  const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) {
  1.2758 -  size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));
  1.2759 -  size_t numpixels, total;
  1.2760 -  size_t line; /* bytes per line in worst case */
  1.2761 -
  1.2762 -  if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
  1.2763 -  if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
  1.2764 -
  1.2765 -  /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */
  1.2766 -  if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;
  1.2767 -  if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;
  1.2768 -
  1.2769 -  if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
  1.2770 -  if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
  1.2771 -
  1.2772 -  return 0; /* no overflow */
  1.2773 -}
  1.2774 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.2775 -#endif /*LODEPNG_COMPILE_PNG*/
  1.2776 -
  1.2777 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.2778 -
  1.2779 -static void LodePNGUnknownChunks_init(LodePNGInfo* info) {
  1.2780 -  unsigned i;
  1.2781 -  for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
  1.2782 -  for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
  1.2783 -}
  1.2784 -
  1.2785 -static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) {
  1.2786 -  unsigned i;
  1.2787 -  for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
  1.2788 -}
  1.2789 -
  1.2790 -static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) {
  1.2791 -  unsigned i;
  1.2792 -
  1.2793 -  LodePNGUnknownChunks_cleanup(dest);
  1.2794 -
  1.2795 -  for(i = 0; i != 3; ++i) {
  1.2796 -    size_t j;
  1.2797 -    dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
  1.2798 -    dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
  1.2799 -    if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
  1.2800 -    for(j = 0; j < src->unknown_chunks_size[i]; ++j) {
  1.2801 -      dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
  1.2802 -    }
  1.2803 -  }
  1.2804 -
  1.2805 -  return 0;
  1.2806 -}
  1.2807 -
  1.2808 -/******************************************************************************/
  1.2809 -
  1.2810 -static void LodePNGText_init(LodePNGInfo* info) {
  1.2811 -  info->text_num = 0;
  1.2812 -  info->text_keys = NULL;
  1.2813 -  info->text_strings = NULL;
  1.2814 -}
  1.2815 -
  1.2816 -static void LodePNGText_cleanup(LodePNGInfo* info) {
  1.2817 -  size_t i;
  1.2818 -  for(i = 0; i != info->text_num; ++i) {
  1.2819 -    string_cleanup(&info->text_keys[i]);
  1.2820 -    string_cleanup(&info->text_strings[i]);
  1.2821 -  }
  1.2822 -  lodepng_free(info->text_keys);
  1.2823 -  lodepng_free(info->text_strings);
  1.2824 -}
  1.2825 -
  1.2826 -static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  1.2827 -  size_t i = 0;
  1.2828 -  dest->text_keys = 0;
  1.2829 -  dest->text_strings = 0;
  1.2830 -  dest->text_num = 0;
  1.2831 -  for(i = 0; i != source->text_num; ++i) {
  1.2832 -    CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
  1.2833 -  }
  1.2834 -  return 0;
  1.2835 -}
  1.2836 -
  1.2837 -void lodepng_clear_text(LodePNGInfo* info) {
  1.2838 -  LodePNGText_cleanup(info);
  1.2839 -}
  1.2840 -
  1.2841 -unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) {
  1.2842 -  char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
  1.2843 -  char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
  1.2844 -  if(!new_keys || !new_strings) {
  1.2845 -    lodepng_free(new_keys);
  1.2846 -    lodepng_free(new_strings);
  1.2847 -    return 83; /*alloc fail*/
  1.2848 -  }
  1.2849 -
  1.2850 -  ++info->text_num;
  1.2851 -  info->text_keys = new_keys;
  1.2852 -  info->text_strings = new_strings;
  1.2853 -
  1.2854 -  info->text_keys[info->text_num - 1] = alloc_string(key);
  1.2855 -  info->text_strings[info->text_num - 1] = alloc_string(str);
  1.2856 -
  1.2857 -  return 0;
  1.2858 -}
  1.2859 -
  1.2860 -/******************************************************************************/
  1.2861 -
  1.2862 -static void LodePNGIText_init(LodePNGInfo* info) {
  1.2863 -  info->itext_num = 0;
  1.2864 -  info->itext_keys = NULL;
  1.2865 -  info->itext_langtags = NULL;
  1.2866 -  info->itext_transkeys = NULL;
  1.2867 -  info->itext_strings = NULL;
  1.2868 -}
  1.2869 -
  1.2870 -static void LodePNGIText_cleanup(LodePNGInfo* info) {
  1.2871 -  size_t i;
  1.2872 -  for(i = 0; i != info->itext_num; ++i) {
  1.2873 -    string_cleanup(&info->itext_keys[i]);
  1.2874 -    string_cleanup(&info->itext_langtags[i]);
  1.2875 -    string_cleanup(&info->itext_transkeys[i]);
  1.2876 -    string_cleanup(&info->itext_strings[i]);
  1.2877 -  }
  1.2878 -  lodepng_free(info->itext_keys);
  1.2879 -  lodepng_free(info->itext_langtags);
  1.2880 -  lodepng_free(info->itext_transkeys);
  1.2881 -  lodepng_free(info->itext_strings);
  1.2882 -}
  1.2883 -
  1.2884 -static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  1.2885 -  size_t i = 0;
  1.2886 -  dest->itext_keys = 0;
  1.2887 -  dest->itext_langtags = 0;
  1.2888 -  dest->itext_transkeys = 0;
  1.2889 -  dest->itext_strings = 0;
  1.2890 -  dest->itext_num = 0;
  1.2891 -  for(i = 0; i != source->itext_num; ++i) {
  1.2892 -    CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
  1.2893 -                                        source->itext_transkeys[i], source->itext_strings[i]));
  1.2894 -  }
  1.2895 -  return 0;
  1.2896 -}
  1.2897 -
  1.2898 -void lodepng_clear_itext(LodePNGInfo* info) {
  1.2899 -  LodePNGIText_cleanup(info);
  1.2900 -}
  1.2901 -
  1.2902 -unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
  1.2903 -                           const char* transkey, const char* str) {
  1.2904 -  char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
  1.2905 -  char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
  1.2906 -  char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
  1.2907 -  char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
  1.2908 -  if(!new_keys || !new_langtags || !new_transkeys || !new_strings) {
  1.2909 -    lodepng_free(new_keys);
  1.2910 -    lodepng_free(new_langtags);
  1.2911 -    lodepng_free(new_transkeys);
  1.2912 -    lodepng_free(new_strings);
  1.2913 -    return 83; /*alloc fail*/
  1.2914 -  }
  1.2915 -
  1.2916 -  ++info->itext_num;
  1.2917 -  info->itext_keys = new_keys;
  1.2918 -  info->itext_langtags = new_langtags;
  1.2919 -  info->itext_transkeys = new_transkeys;
  1.2920 -  info->itext_strings = new_strings;
  1.2921 -
  1.2922 -  info->itext_keys[info->itext_num - 1] = alloc_string(key);
  1.2923 -  info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);
  1.2924 -  info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);
  1.2925 -  info->itext_strings[info->itext_num - 1] = alloc_string(str);
  1.2926 -
  1.2927 -  return 0;
  1.2928 -}
  1.2929 -
  1.2930 -/* same as set but does not delete */
  1.2931 -static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
  1.2932 -  if(profile_size == 0) return 100; /*invalid ICC profile size*/
  1.2933 -
  1.2934 -  info->iccp_name = alloc_string(name);
  1.2935 -  info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size);
  1.2936 -
  1.2937 -  if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/
  1.2938 -
  1.2939 -  lodepng_memcpy(info->iccp_profile, profile, profile_size);
  1.2940 -  info->iccp_profile_size = profile_size;
  1.2941 -
  1.2942 -  return 0; /*ok*/
  1.2943 -}
  1.2944 -
  1.2945 -unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
  1.2946 -  if(info->iccp_name) lodepng_clear_icc(info);
  1.2947 -  info->iccp_defined = 1;
  1.2948 -
  1.2949 -  return lodepng_assign_icc(info, name, profile, profile_size);
  1.2950 -}
  1.2951 -
  1.2952 -void lodepng_clear_icc(LodePNGInfo* info) {
  1.2953 -  string_cleanup(&info->iccp_name);
  1.2954 -  lodepng_free(info->iccp_profile);
  1.2955 -  info->iccp_profile = NULL;
  1.2956 -  info->iccp_profile_size = 0;
  1.2957 -  info->iccp_defined = 0;
  1.2958 -}
  1.2959 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.2960 -
  1.2961 -void lodepng_info_init(LodePNGInfo* info) {
  1.2962 -  lodepng_color_mode_init(&info->color);
  1.2963 -  info->interlace_method = 0;
  1.2964 -  info->compression_method = 0;
  1.2965 -  info->filter_method = 0;
  1.2966 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.2967 -  info->background_defined = 0;
  1.2968 -  info->background_r = info->background_g = info->background_b = 0;
  1.2969 -
  1.2970 -  LodePNGText_init(info);
  1.2971 -  LodePNGIText_init(info);
  1.2972 -
  1.2973 -  info->time_defined = 0;
  1.2974 -  info->phys_defined = 0;
  1.2975 -
  1.2976 -  info->gama_defined = 0;
  1.2977 -  info->chrm_defined = 0;
  1.2978 -  info->srgb_defined = 0;
  1.2979 -  info->iccp_defined = 0;
  1.2980 -  info->iccp_name = NULL;
  1.2981 -  info->iccp_profile = NULL;
  1.2982 -
  1.2983 -  LodePNGUnknownChunks_init(info);
  1.2984 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.2985 -}
  1.2986 -
  1.2987 -void lodepng_info_cleanup(LodePNGInfo* info) {
  1.2988 -  lodepng_color_mode_cleanup(&info->color);
  1.2989 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.2990 -  LodePNGText_cleanup(info);
  1.2991 -  LodePNGIText_cleanup(info);
  1.2992 -
  1.2993 -  lodepng_clear_icc(info);
  1.2994 -
  1.2995 -  LodePNGUnknownChunks_cleanup(info);
  1.2996 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.2997 -}
  1.2998 -
  1.2999 -unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  1.3000 -  lodepng_info_cleanup(dest);
  1.3001 -  *dest = *source;
  1.3002 -  lodepng_color_mode_init(&dest->color);
  1.3003 -  CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
  1.3004 -
  1.3005 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.3006 -  CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
  1.3007 -  CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
  1.3008 -  if(source->iccp_defined) {
  1.3009 -    CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));
  1.3010 -  }
  1.3011 -
  1.3012 -  LodePNGUnknownChunks_init(dest);
  1.3013 -  CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
  1.3014 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.3015 -  return 0;
  1.3016 -}
  1.3017 -
  1.3018 -/* ////////////////////////////////////////////////////////////////////////// */
  1.3019 -
  1.3020 -/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
  1.3021 -static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) {
  1.3022 -  unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
  1.3023 -  /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
  1.3024 -  unsigned p = index & m;
  1.3025 -  in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
  1.3026 -  in = in << (bits * (m - p));
  1.3027 -  if(p == 0) out[index * bits / 8u] = in;
  1.3028 -  else out[index * bits / 8u] |= in;
  1.3029 -}
  1.3030 -
  1.3031 -typedef struct ColorTree ColorTree;
  1.3032 -
  1.3033 -/*
  1.3034 -One node of a color tree
  1.3035 -This is the data structure used to count the number of unique colors and to get a palette
  1.3036 -index for a color. It's like an octree, but because the alpha channel is used too, each
  1.3037 -node has 16 instead of 8 children.
  1.3038 -*/
  1.3039 -struct ColorTree {
  1.3040 -  ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
  1.3041 -  int index; /*the payload. Only has a meaningful value if this is in the last level*/
  1.3042 -};
  1.3043 -
  1.3044 -static void color_tree_init(ColorTree* tree) {
  1.3045 -  int i;
  1.3046 -  for(i = 0; i != 16; ++i) tree->children[i] = 0;
  1.3047 -  tree->index = -1;
  1.3048 -}
  1.3049 -
  1.3050 -static void color_tree_cleanup(ColorTree* tree) {
  1.3051 -  int i;
  1.3052 -  for(i = 0; i != 16; ++i) {
  1.3053 -    if(tree->children[i]) {
  1.3054 -      color_tree_cleanup(tree->children[i]);
  1.3055 -      lodepng_free(tree->children[i]);
  1.3056 -    }
  1.3057 -  }
  1.3058 -}
  1.3059 -
  1.3060 -/*returns -1 if color not present, its index otherwise*/
  1.3061 -static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  1.3062 -  int bit = 0;
  1.3063 -  for(bit = 0; bit < 8; ++bit) {
  1.3064 -    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
  1.3065 -    if(!tree->children[i]) return -1;
  1.3066 -    else tree = tree->children[i];
  1.3067 -  }
  1.3068 -  return tree ? tree->index : -1;
  1.3069 -}
  1.3070 -
  1.3071 -#ifdef LODEPNG_COMPILE_ENCODER
  1.3072 -static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  1.3073 -  return color_tree_get(tree, r, g, b, a) >= 0;
  1.3074 -}
  1.3075 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.3076 -
  1.3077 -/*color is not allowed to already exist.
  1.3078 -Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
  1.3079 -static void color_tree_add(ColorTree* tree,
  1.3080 -                           unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) {
  1.3081 -  int bit;
  1.3082 -  for(bit = 0; bit < 8; ++bit) {
  1.3083 -    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
  1.3084 -    if(!tree->children[i]) {
  1.3085 -      tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
  1.3086 -      color_tree_init(tree->children[i]);
  1.3087 -    }
  1.3088 -    tree = tree->children[i];
  1.3089 -  }
  1.3090 -  tree->index = (int)index;
  1.3091 -}
  1.3092 -
  1.3093 -/*put a pixel, given its RGBA color, into image of any color type*/
  1.3094 -static unsigned rgba8ToPixel(unsigned char* out, size_t i,
  1.3095 -                             const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
  1.3096 -                             unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  1.3097 -  if(mode->colortype == LCT_GREY) {
  1.3098 -    unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
  1.3099 -    if(mode->bitdepth == 8) out[i] = gray;
  1.3100 -    else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
  1.3101 -    else {
  1.3102 -      /*take the most significant bits of gray*/
  1.3103 -      gray = (gray >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
  1.3104 -      addColorBits(out, i, mode->bitdepth, gray);
  1.3105 -    }
  1.3106 -  } else if(mode->colortype == LCT_RGB) {
  1.3107 -    if(mode->bitdepth == 8) {
  1.3108 -      out[i * 3 + 0] = r;
  1.3109 -      out[i * 3 + 1] = g;
  1.3110 -      out[i * 3 + 2] = b;
  1.3111 -    } else {
  1.3112 -      out[i * 6 + 0] = out[i * 6 + 1] = r;
  1.3113 -      out[i * 6 + 2] = out[i * 6 + 3] = g;
  1.3114 -      out[i * 6 + 4] = out[i * 6 + 5] = b;
  1.3115 -    }
  1.3116 -  } else if(mode->colortype == LCT_PALETTE) {
  1.3117 -    int index = color_tree_get(tree, r, g, b, a);
  1.3118 -    if(index < 0) return 82; /*color not in palette*/
  1.3119 -    if(mode->bitdepth == 8) out[i] = index;
  1.3120 -    else addColorBits(out, i, mode->bitdepth, (unsigned)index);
  1.3121 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3122 -    unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
  1.3123 -    if(mode->bitdepth == 8) {
  1.3124 -      out[i * 2 + 0] = gray;
  1.3125 -      out[i * 2 + 1] = a;
  1.3126 -    } else if(mode->bitdepth == 16) {
  1.3127 -      out[i * 4 + 0] = out[i * 4 + 1] = gray;
  1.3128 -      out[i * 4 + 2] = out[i * 4 + 3] = a;
  1.3129 -    }
  1.3130 -  } else if(mode->colortype == LCT_RGBA) {
  1.3131 -    if(mode->bitdepth == 8) {
  1.3132 -      out[i * 4 + 0] = r;
  1.3133 -      out[i * 4 + 1] = g;
  1.3134 -      out[i * 4 + 2] = b;
  1.3135 -      out[i * 4 + 3] = a;
  1.3136 -    } else {
  1.3137 -      out[i * 8 + 0] = out[i * 8 + 1] = r;
  1.3138 -      out[i * 8 + 2] = out[i * 8 + 3] = g;
  1.3139 -      out[i * 8 + 4] = out[i * 8 + 5] = b;
  1.3140 -      out[i * 8 + 6] = out[i * 8 + 7] = a;
  1.3141 -    }
  1.3142 -  }
  1.3143 -
  1.3144 -  return 0; /*no error*/
  1.3145 -}
  1.3146 -
  1.3147 -/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
  1.3148 -static void rgba16ToPixel(unsigned char* out, size_t i,
  1.3149 -                         const LodePNGColorMode* mode,
  1.3150 -                         unsigned short r, unsigned short g, unsigned short b, unsigned short a) {
  1.3151 -  if(mode->colortype == LCT_GREY) {
  1.3152 -    unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
  1.3153 -    out[i * 2 + 0] = (gray >> 8) & 255;
  1.3154 -    out[i * 2 + 1] = gray & 255;
  1.3155 -  } else if(mode->colortype == LCT_RGB) {
  1.3156 -    out[i * 6 + 0] = (r >> 8) & 255;
  1.3157 -    out[i * 6 + 1] = r & 255;
  1.3158 -    out[i * 6 + 2] = (g >> 8) & 255;
  1.3159 -    out[i * 6 + 3] = g & 255;
  1.3160 -    out[i * 6 + 4] = (b >> 8) & 255;
  1.3161 -    out[i * 6 + 5] = b & 255;
  1.3162 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3163 -    unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
  1.3164 -    out[i * 4 + 0] = (gray >> 8) & 255;
  1.3165 -    out[i * 4 + 1] = gray & 255;
  1.3166 -    out[i * 4 + 2] = (a >> 8) & 255;
  1.3167 -    out[i * 4 + 3] = a & 255;
  1.3168 -  } else if(mode->colortype == LCT_RGBA) {
  1.3169 -    out[i * 8 + 0] = (r >> 8) & 255;
  1.3170 -    out[i * 8 + 1] = r & 255;
  1.3171 -    out[i * 8 + 2] = (g >> 8) & 255;
  1.3172 -    out[i * 8 + 3] = g & 255;
  1.3173 -    out[i * 8 + 4] = (b >> 8) & 255;
  1.3174 -    out[i * 8 + 5] = b & 255;
  1.3175 -    out[i * 8 + 6] = (a >> 8) & 255;
  1.3176 -    out[i * 8 + 7] = a & 255;
  1.3177 -  }
  1.3178 -}
  1.3179 -
  1.3180 -/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
  1.3181 -static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
  1.3182 -                               unsigned char* b, unsigned char* a,
  1.3183 -                               const unsigned char* in, size_t i,
  1.3184 -                               const LodePNGColorMode* mode) {
  1.3185 -  if(mode->colortype == LCT_GREY) {
  1.3186 -    if(mode->bitdepth == 8) {
  1.3187 -      *r = *g = *b = in[i];
  1.3188 -      if(mode->key_defined && *r == mode->key_r) *a = 0;
  1.3189 -      else *a = 255;
  1.3190 -    } else if(mode->bitdepth == 16) {
  1.3191 -      *r = *g = *b = in[i * 2 + 0];
  1.3192 -      if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
  1.3193 -      else *a = 255;
  1.3194 -    } else {
  1.3195 -      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  1.3196 -      size_t j = i * mode->bitdepth;
  1.3197 -      unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3198 -      *r = *g = *b = (value * 255) / highest;
  1.3199 -      if(mode->key_defined && value == mode->key_r) *a = 0;
  1.3200 -      else *a = 255;
  1.3201 -    }
  1.3202 -  } else if(mode->colortype == LCT_RGB) {
  1.3203 -    if(mode->bitdepth == 8) {
  1.3204 -      *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
  1.3205 -      if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
  1.3206 -      else *a = 255;
  1.3207 -    } else {
  1.3208 -      *r = in[i * 6 + 0];
  1.3209 -      *g = in[i * 6 + 2];
  1.3210 -      *b = in[i * 6 + 4];
  1.3211 -      if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  1.3212 -         && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  1.3213 -         && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
  1.3214 -      else *a = 255;
  1.3215 -    }
  1.3216 -  } else if(mode->colortype == LCT_PALETTE) {
  1.3217 -    unsigned index;
  1.3218 -    if(mode->bitdepth == 8) index = in[i];
  1.3219 -    else {
  1.3220 -      size_t j = i * mode->bitdepth;
  1.3221 -      index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3222 -    }
  1.3223 -    /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  1.3224 -    *r = mode->palette[index * 4 + 0];
  1.3225 -    *g = mode->palette[index * 4 + 1];
  1.3226 -    *b = mode->palette[index * 4 + 2];
  1.3227 -    *a = mode->palette[index * 4 + 3];
  1.3228 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3229 -    if(mode->bitdepth == 8) {
  1.3230 -      *r = *g = *b = in[i * 2 + 0];
  1.3231 -      *a = in[i * 2 + 1];
  1.3232 -    } else {
  1.3233 -      *r = *g = *b = in[i * 4 + 0];
  1.3234 -      *a = in[i * 4 + 2];
  1.3235 -    }
  1.3236 -  } else if(mode->colortype == LCT_RGBA) {
  1.3237 -    if(mode->bitdepth == 8) {
  1.3238 -      *r = in[i * 4 + 0];
  1.3239 -      *g = in[i * 4 + 1];
  1.3240 -      *b = in[i * 4 + 2];
  1.3241 -      *a = in[i * 4 + 3];
  1.3242 -    } else {
  1.3243 -      *r = in[i * 8 + 0];
  1.3244 -      *g = in[i * 8 + 2];
  1.3245 -      *b = in[i * 8 + 4];
  1.3246 -      *a = in[i * 8 + 6];
  1.3247 -    }
  1.3248 -  }
  1.3249 -}
  1.3250 -
  1.3251 -/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
  1.3252 -mode test cases, optimized to convert the colors much faster, when converting
  1.3253 -to the common case of RGBA with 8 bit per channel. buffer must be RGBA with
  1.3254 -enough memory.*/
  1.3255 -static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
  1.3256 -                                const unsigned char* LODEPNG_RESTRICT in,
  1.3257 -                                const LodePNGColorMode* mode) {
  1.3258 -  unsigned num_channels = 4;
  1.3259 -  size_t i;
  1.3260 -  if(mode->colortype == LCT_GREY) {
  1.3261 -    if(mode->bitdepth == 8) {
  1.3262 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3263 -        buffer[0] = buffer[1] = buffer[2] = in[i];
  1.3264 -        buffer[3] = 255;
  1.3265 -      }
  1.3266 -      if(mode->key_defined) {
  1.3267 -        buffer -= numpixels * num_channels;
  1.3268 -        for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3269 -          if(buffer[0] == mode->key_r) buffer[3] = 0;
  1.3270 -        }
  1.3271 -      }
  1.3272 -    } else if(mode->bitdepth == 16) {
  1.3273 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3274 -        buffer[0] = buffer[1] = buffer[2] = in[i * 2];
  1.3275 -        buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
  1.3276 -      }
  1.3277 -    } else {
  1.3278 -      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  1.3279 -      size_t j = 0;
  1.3280 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3281 -        unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3282 -        buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
  1.3283 -        buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
  1.3284 -      }
  1.3285 -    }
  1.3286 -  } else if(mode->colortype == LCT_RGB) {
  1.3287 -    if(mode->bitdepth == 8) {
  1.3288 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3289 -        lodepng_memcpy(buffer, &in[i * 3], 3);
  1.3290 -        buffer[3] = 255;
  1.3291 -      }
  1.3292 -      if(mode->key_defined) {
  1.3293 -        buffer -= numpixels * num_channels;
  1.3294 -        for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3295 -          if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;
  1.3296 -        }
  1.3297 -      }
  1.3298 -    } else {
  1.3299 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3300 -        buffer[0] = in[i * 6 + 0];
  1.3301 -        buffer[1] = in[i * 6 + 2];
  1.3302 -        buffer[2] = in[i * 6 + 4];
  1.3303 -        buffer[3] = mode->key_defined
  1.3304 -           && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  1.3305 -           && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  1.3306 -           && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
  1.3307 -      }
  1.3308 -    }
  1.3309 -  } else if(mode->colortype == LCT_PALETTE) {
  1.3310 -    if(mode->bitdepth == 8) {
  1.3311 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3312 -        unsigned index = in[i];
  1.3313 -        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  1.3314 -        lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
  1.3315 -      }
  1.3316 -    } else {
  1.3317 -      size_t j = 0;
  1.3318 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3319 -        unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3320 -        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  1.3321 -        lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
  1.3322 -      }
  1.3323 -    }
  1.3324 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3325 -    if(mode->bitdepth == 8) {
  1.3326 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3327 -        buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
  1.3328 -        buffer[3] = in[i * 2 + 1];
  1.3329 -      }
  1.3330 -    } else {
  1.3331 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3332 -        buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
  1.3333 -        buffer[3] = in[i * 4 + 2];
  1.3334 -      }
  1.3335 -    }
  1.3336 -  } else if(mode->colortype == LCT_RGBA) {
  1.3337 -    if(mode->bitdepth == 8) {
  1.3338 -      lodepng_memcpy(buffer, in, numpixels * 4);
  1.3339 -    } else {
  1.3340 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3341 -        buffer[0] = in[i * 8 + 0];
  1.3342 -        buffer[1] = in[i * 8 + 2];
  1.3343 -        buffer[2] = in[i * 8 + 4];
  1.3344 -        buffer[3] = in[i * 8 + 6];
  1.3345 -      }
  1.3346 -    }
  1.3347 -  }
  1.3348 -}
  1.3349 -
  1.3350 -/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/
  1.3351 -static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
  1.3352 -                               const unsigned char* LODEPNG_RESTRICT in,
  1.3353 -                               const LodePNGColorMode* mode) {
  1.3354 -  const unsigned num_channels = 3;
  1.3355 -  size_t i;
  1.3356 -  if(mode->colortype == LCT_GREY) {
  1.3357 -    if(mode->bitdepth == 8) {
  1.3358 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3359 -        buffer[0] = buffer[1] = buffer[2] = in[i];
  1.3360 -      }
  1.3361 -    } else if(mode->bitdepth == 16) {
  1.3362 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3363 -        buffer[0] = buffer[1] = buffer[2] = in[i * 2];
  1.3364 -      }
  1.3365 -    } else {
  1.3366 -      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  1.3367 -      size_t j = 0;
  1.3368 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3369 -        unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3370 -        buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
  1.3371 -      }
  1.3372 -    }
  1.3373 -  } else if(mode->colortype == LCT_RGB) {
  1.3374 -    if(mode->bitdepth == 8) {
  1.3375 -      lodepng_memcpy(buffer, in, numpixels * 3);
  1.3376 -    } else {
  1.3377 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3378 -        buffer[0] = in[i * 6 + 0];
  1.3379 -        buffer[1] = in[i * 6 + 2];
  1.3380 -        buffer[2] = in[i * 6 + 4];
  1.3381 -      }
  1.3382 -    }
  1.3383 -  } else if(mode->colortype == LCT_PALETTE) {
  1.3384 -    if(mode->bitdepth == 8) {
  1.3385 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3386 -        unsigned index = in[i];
  1.3387 -        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  1.3388 -        lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
  1.3389 -      }
  1.3390 -    } else {
  1.3391 -      size_t j = 0;
  1.3392 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3393 -        unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  1.3394 -        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  1.3395 -        lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
  1.3396 -      }
  1.3397 -    }
  1.3398 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3399 -    if(mode->bitdepth == 8) {
  1.3400 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3401 -        buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
  1.3402 -      }
  1.3403 -    } else {
  1.3404 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3405 -        buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
  1.3406 -      }
  1.3407 -    }
  1.3408 -  } else if(mode->colortype == LCT_RGBA) {
  1.3409 -    if(mode->bitdepth == 8) {
  1.3410 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3411 -        lodepng_memcpy(buffer, &in[i * 4], 3);
  1.3412 -      }
  1.3413 -    } else {
  1.3414 -      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  1.3415 -        buffer[0] = in[i * 8 + 0];
  1.3416 -        buffer[1] = in[i * 8 + 2];
  1.3417 -        buffer[2] = in[i * 8 + 4];
  1.3418 -      }
  1.3419 -    }
  1.3420 -  }
  1.3421 -}
  1.3422 -
  1.3423 -/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
  1.3424 -given color type, but the given color type must be 16-bit itself.*/
  1.3425 -static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
  1.3426 -                                const unsigned char* in, size_t i, const LodePNGColorMode* mode) {
  1.3427 -  if(mode->colortype == LCT_GREY) {
  1.3428 -    *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
  1.3429 -    if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
  1.3430 -    else *a = 65535;
  1.3431 -  } else if(mode->colortype == LCT_RGB) {
  1.3432 -    *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
  1.3433 -    *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
  1.3434 -    *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
  1.3435 -    if(mode->key_defined
  1.3436 -       && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  1.3437 -       && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  1.3438 -       && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
  1.3439 -    else *a = 65535;
  1.3440 -  } else if(mode->colortype == LCT_GREY_ALPHA) {
  1.3441 -    *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
  1.3442 -    *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
  1.3443 -  } else if(mode->colortype == LCT_RGBA) {
  1.3444 -    *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
  1.3445 -    *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
  1.3446 -    *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
  1.3447 -    *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
  1.3448 -  }
  1.3449 -}
  1.3450 -
  1.3451 -unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
  1.3452 -                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
  1.3453 -                         unsigned w, unsigned h) {
  1.3454 -  size_t i;
  1.3455 -  ColorTree tree;
  1.3456 -  size_t numpixels = (size_t)w * (size_t)h;
  1.3457 -  unsigned error = 0;
  1.3458 -
  1.3459 -  if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) {
  1.3460 -    return 107; /* error: must provide palette if input mode is palette */
  1.3461 -  }
  1.3462 -
  1.3463 -  if(lodepng_color_mode_equal(mode_out, mode_in)) {
  1.3464 -    size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
  1.3465 -    for(i = 0; i != numbytes; ++i) out[i] = in[i];
  1.3466 -    return 0;
  1.3467 -  }
  1.3468 -
  1.3469 -  if(mode_out->colortype == LCT_PALETTE) {
  1.3470 -    size_t palettesize = mode_out->palettesize;
  1.3471 -    const unsigned char* palette = mode_out->palette;
  1.3472 -    size_t palsize = (size_t)1u << mode_out->bitdepth;
  1.3473 -    /*if the user specified output palette but did not give the values, assume
  1.3474 -    they want the values of the input color type (assuming that one is palette).
  1.3475 -    Note that we never create a new palette ourselves.*/
  1.3476 -    if(palettesize == 0) {
  1.3477 -      palettesize = mode_in->palettesize;
  1.3478 -      palette = mode_in->palette;
  1.3479 -      /*if the input was also palette with same bitdepth, then the color types are also
  1.3480 -      equal, so copy literally. This to preserve the exact indices that were in the PNG
  1.3481 -      even in case there are duplicate colors in the palette.*/
  1.3482 -      if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
  1.3483 -        size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
  1.3484 -        for(i = 0; i != numbytes; ++i) out[i] = in[i];
  1.3485 -        return 0;
  1.3486 -      }
  1.3487 -    }
  1.3488 -    if(palettesize < palsize) palsize = palettesize;
  1.3489 -    color_tree_init(&tree);
  1.3490 -    for(i = 0; i != palsize; ++i) {
  1.3491 -      const unsigned char* p = &palette[i * 4];
  1.3492 -      color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
  1.3493 -    }
  1.3494 -  }
  1.3495 -
  1.3496 -  if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
  1.3497 -    for(i = 0; i != numpixels; ++i) {
  1.3498 -      unsigned short r = 0, g = 0, b = 0, a = 0;
  1.3499 -      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  1.3500 -      rgba16ToPixel(out, i, mode_out, r, g, b, a);
  1.3501 -    }
  1.3502 -  } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
  1.3503 -    getPixelColorsRGBA8(out, numpixels, in, mode_in);
  1.3504 -  } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
  1.3505 -    getPixelColorsRGB8(out, numpixels, in, mode_in);
  1.3506 -  } else {
  1.3507 -    unsigned char r = 0, g = 0, b = 0, a = 0;
  1.3508 -    for(i = 0; i != numpixels; ++i) {
  1.3509 -      getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  1.3510 -      error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
  1.3511 -      if (error) break;
  1.3512 -    }
  1.3513 -  }
  1.3514 -
  1.3515 -  if(mode_out->colortype == LCT_PALETTE) {
  1.3516 -    color_tree_cleanup(&tree);
  1.3517 -  }
  1.3518 -
  1.3519 -  return error;
  1.3520 -}
  1.3521 -
  1.3522 -
  1.3523 -/* Converts a single rgb color without alpha from one type to another, color bits truncated to
  1.3524 -their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow
  1.3525 -function, do not use to process all pixels of an image. Alpha channel not supported on purpose:
  1.3526 -this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the
  1.3527 -specification it looks like bKGD should ignore the alpha values of the palette since it can use
  1.3528 -any palette index but doesn't have an alpha channel. Idem with ignoring color key. */
  1.3529 -unsigned lodepng_convert_rgb(
  1.3530 -    unsigned* r_out, unsigned* g_out, unsigned* b_out,
  1.3531 -    unsigned r_in, unsigned g_in, unsigned b_in,
  1.3532 -    const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) {
  1.3533 -  unsigned r = 0, g = 0, b = 0;
  1.3534 -  unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/
  1.3535 -  unsigned shift = 16 - mode_out->bitdepth;
  1.3536 -
  1.3537 -  if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {
  1.3538 -    r = g = b = r_in * mul;
  1.3539 -  } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {
  1.3540 -    r = r_in * mul;
  1.3541 -    g = g_in * mul;
  1.3542 -    b = b_in * mul;
  1.3543 -  } else if(mode_in->colortype == LCT_PALETTE) {
  1.3544 -    if(r_in >= mode_in->palettesize) return 82;
  1.3545 -    r = mode_in->palette[r_in * 4 + 0] * 257u;
  1.3546 -    g = mode_in->palette[r_in * 4 + 1] * 257u;
  1.3547 -    b = mode_in->palette[r_in * 4 + 2] * 257u;
  1.3548 -  } else {
  1.3549 -    return 31;
  1.3550 -  }
  1.3551 -
  1.3552 -  /* now convert to output format */
  1.3553 -  if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {
  1.3554 -    *r_out = r >> shift ;
  1.3555 -  } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {
  1.3556 -    *r_out = r >> shift ;
  1.3557 -    *g_out = g >> shift ;
  1.3558 -    *b_out = b >> shift ;
  1.3559 -  } else if(mode_out->colortype == LCT_PALETTE) {
  1.3560 -    unsigned i;
  1.3561 -    /* a 16-bit color cannot be in the palette */
  1.3562 -    if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;
  1.3563 -    for(i = 0; i < mode_out->palettesize; i++) {
  1.3564 -      unsigned j = i * 4;
  1.3565 -      if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&
  1.3566 -          (b >> 8) == mode_out->palette[j + 2]) {
  1.3567 -        *r_out = i;
  1.3568 -        return 0;
  1.3569 -      }
  1.3570 -    }
  1.3571 -    return 82;
  1.3572 -  } else {
  1.3573 -    return 31;
  1.3574 -  }
  1.3575 -
  1.3576 -  return 0;
  1.3577 -}
  1.3578 -
  1.3579 -#ifdef LODEPNG_COMPILE_ENCODER
  1.3580 -
  1.3581 -void lodepng_color_stats_init(LodePNGColorStats* stats) {
  1.3582 -  /*stats*/
  1.3583 -  stats->colored = 0;
  1.3584 -  stats->key = 0;
  1.3585 -  stats->key_r = stats->key_g = stats->key_b = 0;
  1.3586 -  stats->alpha = 0;
  1.3587 -  stats->numcolors = 0;
  1.3588 -  stats->bits = 1;
  1.3589 -  stats->numpixels = 0;
  1.3590 -  /*settings*/
  1.3591 -  stats->allow_palette = 1;
  1.3592 -  stats->allow_greyscale = 1;
  1.3593 -}
  1.3594 -
  1.3595 -/*function used for debug purposes with C++*/
  1.3596 -/*void printColorStats(LodePNGColorStats* p) {
  1.3597 -  std::cout << "colored: " << (int)p->colored << ", ";
  1.3598 -  std::cout << "key: " << (int)p->key << ", ";
  1.3599 -  std::cout << "key_r: " << (int)p->key_r << ", ";
  1.3600 -  std::cout << "key_g: " << (int)p->key_g << ", ";
  1.3601 -  std::cout << "key_b: " << (int)p->key_b << ", ";
  1.3602 -  std::cout << "alpha: " << (int)p->alpha << ", ";
  1.3603 -  std::cout << "numcolors: " << (int)p->numcolors << ", ";
  1.3604 -  std::cout << "bits: " << (int)p->bits << std::endl;
  1.3605 -}*/
  1.3606 -
  1.3607 -/*Returns how many bits needed to represent given value (max 8 bit)*/
  1.3608 -static unsigned getValueRequiredBits(unsigned char value) {
  1.3609 -  if(value == 0 || value == 255) return 1;
  1.3610 -  /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
  1.3611 -  if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
  1.3612 -  return 8;
  1.3613 -}
  1.3614 -
  1.3615 -/*stats must already have been inited. */
  1.3616 -void lodepng_compute_color_stats(LodePNGColorStats* stats,
  1.3617 -                                 const unsigned char* in, unsigned w, unsigned h,
  1.3618 -                                 const LodePNGColorMode* mode_in) {
  1.3619 -  size_t i;
  1.3620 -  ColorTree tree;
  1.3621 -  size_t numpixels = (size_t)w * (size_t)h;
  1.3622 -
  1.3623 -  /* mark things as done already if it would be impossible to have a more expensive case */
  1.3624 -  unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;
  1.3625 -  unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;
  1.3626 -  unsigned numcolors_done = 0;
  1.3627 -  unsigned bpp = lodepng_get_bpp(mode_in);
  1.3628 -  unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0;
  1.3629 -  unsigned sixteen = 0; /* whether the input image is 16 bit */
  1.3630 -  unsigned maxnumcolors = 257;
  1.3631 -  if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp));
  1.3632 -
  1.3633 -  stats->numpixels += numpixels;
  1.3634 -
  1.3635 -  /*if palette not allowed, no need to compute numcolors*/
  1.3636 -  if(!stats->allow_palette) numcolors_done = 1;
  1.3637 -
  1.3638 -  color_tree_init(&tree);
  1.3639 -
  1.3640 -  /*If the stats was already filled in from previous data, fill its palette in tree
  1.3641 -  and mark things as done already if we know they are the most expensive case already*/
  1.3642 -  if(stats->alpha) alpha_done = 1;
  1.3643 -  if(stats->colored) colored_done = 1;
  1.3644 -  if(stats->bits == 16) numcolors_done = 1;
  1.3645 -  if(stats->bits >= bpp) bits_done = 1;
  1.3646 -  if(stats->numcolors >= maxnumcolors) numcolors_done = 1;
  1.3647 -
  1.3648 -  if(!numcolors_done) {
  1.3649 -    for(i = 0; i < stats->numcolors; i++) {
  1.3650 -      const unsigned char* color = &stats->palette[i * 4];
  1.3651 -      color_tree_add(&tree, color[0], color[1], color[2], color[3], i);
  1.3652 -    }
  1.3653 -  }
  1.3654 -
  1.3655 -  /*Check if the 16-bit input is truly 16-bit*/
  1.3656 -  if(mode_in->bitdepth == 16 && !sixteen) {
  1.3657 -    unsigned short r, g, b, a;
  1.3658 -    for(i = 0; i != numpixels; ++i) {
  1.3659 -      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  1.3660 -      if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
  1.3661 -         (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ {
  1.3662 -        stats->bits = 16;
  1.3663 -        sixteen = 1;
  1.3664 -        bits_done = 1;
  1.3665 -        numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
  1.3666 -        break;
  1.3667 -      }
  1.3668 -    }
  1.3669 -  }
  1.3670 -
  1.3671 -  if(sixteen) {
  1.3672 -    unsigned short r = 0, g = 0, b = 0, a = 0;
  1.3673 -
  1.3674 -    for(i = 0; i != numpixels; ++i) {
  1.3675 -      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  1.3676 -
  1.3677 -      if(!colored_done && (r != g || r != b)) {
  1.3678 -        stats->colored = 1;
  1.3679 -        colored_done = 1;
  1.3680 -      }
  1.3681 -
  1.3682 -      if(!alpha_done) {
  1.3683 -        unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
  1.3684 -        if(a != 65535 && (a != 0 || (stats->key && !matchkey))) {
  1.3685 -          stats->alpha = 1;
  1.3686 -          stats->key = 0;
  1.3687 -          alpha_done = 1;
  1.3688 -        } else if(a == 0 && !stats->alpha && !stats->key) {
  1.3689 -          stats->key = 1;
  1.3690 -          stats->key_r = r;
  1.3691 -          stats->key_g = g;
  1.3692 -          stats->key_b = b;
  1.3693 -        } else if(a == 65535 && stats->key && matchkey) {
  1.3694 -          /* Color key cannot be used if an opaque pixel also has that RGB color. */
  1.3695 -          stats->alpha = 1;
  1.3696 -          stats->key = 0;
  1.3697 -          alpha_done = 1;
  1.3698 -        }
  1.3699 -      }
  1.3700 -      if(alpha_done && numcolors_done && colored_done && bits_done) break;
  1.3701 -    }
  1.3702 -
  1.3703 -    if(stats->key && !stats->alpha) {
  1.3704 -      for(i = 0; i != numpixels; ++i) {
  1.3705 -        getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  1.3706 -        if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
  1.3707 -          /* Color key cannot be used if an opaque pixel also has that RGB color. */
  1.3708 -          stats->alpha = 1;
  1.3709 -          stats->key = 0;
  1.3710 -          alpha_done = 1;
  1.3711 -        }
  1.3712 -      }
  1.3713 -    }
  1.3714 -  } else /* < 16-bit */ {
  1.3715 -    unsigned char r = 0, g = 0, b = 0, a = 0;
  1.3716 -    for(i = 0; i != numpixels; ++i) {
  1.3717 -      getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  1.3718 -
  1.3719 -      if(!bits_done && stats->bits < 8) {
  1.3720 -        /*only r is checked, < 8 bits is only relevant for grayscale*/
  1.3721 -        unsigned bits = getValueRequiredBits(r);
  1.3722 -        if(bits > stats->bits) stats->bits = bits;
  1.3723 -      }
  1.3724 -      bits_done = (stats->bits >= bpp);
  1.3725 -
  1.3726 -      if(!colored_done && (r != g || r != b)) {
  1.3727 -        stats->colored = 1;
  1.3728 -        colored_done = 1;
  1.3729 -        if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
  1.3730 -      }
  1.3731 -
  1.3732 -      if(!alpha_done) {
  1.3733 -        unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
  1.3734 -        if(a != 255 && (a != 0 || (stats->key && !matchkey))) {
  1.3735 -          stats->alpha = 1;
  1.3736 -          stats->key = 0;
  1.3737 -          alpha_done = 1;
  1.3738 -          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  1.3739 -        } else if(a == 0 && !stats->alpha && !stats->key) {
  1.3740 -          stats->key = 1;
  1.3741 -          stats->key_r = r;
  1.3742 -          stats->key_g = g;
  1.3743 -          stats->key_b = b;
  1.3744 -        } else if(a == 255 && stats->key && matchkey) {
  1.3745 -          /* Color key cannot be used if an opaque pixel also has that RGB color. */
  1.3746 -          stats->alpha = 1;
  1.3747 -          stats->key = 0;
  1.3748 -          alpha_done = 1;
  1.3749 -          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  1.3750 -        }
  1.3751 -      }
  1.3752 -
  1.3753 -      if(!numcolors_done) {
  1.3754 -        if(!color_tree_has(&tree, r, g, b, a)) {
  1.3755 -          color_tree_add(&tree, r, g, b, a, stats->numcolors);
  1.3756 -          if(stats->numcolors < 256) {
  1.3757 -            unsigned char* p = stats->palette;
  1.3758 -            unsigned n = stats->numcolors;
  1.3759 -            p[n * 4 + 0] = r;
  1.3760 -            p[n * 4 + 1] = g;
  1.3761 -            p[n * 4 + 2] = b;
  1.3762 -            p[n * 4 + 3] = a;
  1.3763 -          }
  1.3764 -          ++stats->numcolors;
  1.3765 -          numcolors_done = stats->numcolors >= maxnumcolors;
  1.3766 -        }
  1.3767 -      }
  1.3768 -
  1.3769 -      if(alpha_done && numcolors_done && colored_done && bits_done) break;
  1.3770 -    }
  1.3771 -
  1.3772 -    if(stats->key && !stats->alpha) {
  1.3773 -      for(i = 0; i != numpixels; ++i) {
  1.3774 -        getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  1.3775 -        if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
  1.3776 -          /* Color key cannot be used if an opaque pixel also has that RGB color. */
  1.3777 -          stats->alpha = 1;
  1.3778 -          stats->key = 0;
  1.3779 -          alpha_done = 1;
  1.3780 -          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  1.3781 -        }
  1.3782 -      }
  1.3783 -    }
  1.3784 -
  1.3785 -    /*make the stats's key always 16-bit for consistency - repeat each byte twice*/
  1.3786 -    stats->key_r += (stats->key_r << 8);
  1.3787 -    stats->key_g += (stats->key_g << 8);
  1.3788 -    stats->key_b += (stats->key_b << 8);
  1.3789 -  }
  1.3790 -
  1.3791 -  color_tree_cleanup(&tree);
  1.3792 -}
  1.3793 -
  1.3794 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.3795 -/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit
  1.3796 -(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for
  1.3797 -all pixels of an image but only for a few additional values. */
  1.3798 -static void lodepng_color_stats_add(LodePNGColorStats* stats,
  1.3799 -                                    unsigned r, unsigned g, unsigned b, unsigned a) {
  1.3800 -  unsigned char image[8];
  1.3801 -  LodePNGColorMode mode;
  1.3802 -  lodepng_color_mode_init(&mode);
  1.3803 -  image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g;
  1.3804 -  image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a;
  1.3805 -  mode.bitdepth = 16;
  1.3806 -  mode.colortype = LCT_RGBA;
  1.3807 -  lodepng_compute_color_stats(stats, image, 1, 1, &mode);
  1.3808 -  lodepng_color_mode_cleanup(&mode);
  1.3809 -}
  1.3810 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.3811 -
  1.3812 -unsigned auto_choose_color(LodePNGColorMode* mode_out,
  1.3813 -                           const LodePNGColorMode* mode_in,
  1.3814 -                           const LodePNGColorStats* stats) {
  1.3815 -  unsigned error = 0;
  1.3816 -  unsigned palettebits;
  1.3817 -  size_t i, n;
  1.3818 -  size_t numpixels = stats->numpixels;
  1.3819 -  unsigned palette_ok, gray_ok;
  1.3820 -
  1.3821 -  unsigned alpha = stats->alpha;
  1.3822 -  unsigned key = stats->key;
  1.3823 -  unsigned bits = stats->bits;
  1.3824 -
  1.3825 -  mode_out->key_defined = 0;
  1.3826 -
  1.3827 -  if(key && numpixels <= 16) {
  1.3828 -    alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
  1.3829 -    key = 0;
  1.3830 -    if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  1.3831 -  }
  1.3832 -
  1.3833 -  gray_ok = !stats->colored;
  1.3834 -  if(!stats->allow_greyscale) gray_ok = 0;
  1.3835 -  if(!gray_ok && bits < 8) bits = 8;
  1.3836 -
  1.3837 -  n = stats->numcolors;
  1.3838 -  palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
  1.3839 -  palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/
  1.3840 -  if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
  1.3841 -  if(gray_ok && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/
  1.3842 -  if(!stats->allow_palette) palette_ok = 0;
  1.3843 -
  1.3844 -  if(palette_ok) {
  1.3845 -    const unsigned char* p = stats->palette;
  1.3846 -    lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
  1.3847 -    for(i = 0; i != stats->numcolors; ++i) {
  1.3848 -      error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
  1.3849 -      if(error) break;
  1.3850 -    }
  1.3851 -
  1.3852 -    mode_out->colortype = LCT_PALETTE;
  1.3853 -    mode_out->bitdepth = palettebits;
  1.3854 -
  1.3855 -    if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
  1.3856 -        && mode_in->bitdepth == mode_out->bitdepth) {
  1.3857 -      /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
  1.3858 -      lodepng_color_mode_cleanup(mode_out);
  1.3859 -      lodepng_color_mode_copy(mode_out, mode_in);
  1.3860 -    }
  1.3861 -  } else /*8-bit or 16-bit per channel*/ {
  1.3862 -    mode_out->bitdepth = bits;
  1.3863 -    mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA)
  1.3864 -                                : (gray_ok ? LCT_GREY : LCT_RGB);
  1.3865 -    if(key) {
  1.3866 -      unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/
  1.3867 -      mode_out->key_r = stats->key_r & mask;
  1.3868 -      mode_out->key_g = stats->key_g & mask;
  1.3869 -      mode_out->key_b = stats->key_b & mask;
  1.3870 -      mode_out->key_defined = 1;
  1.3871 -    }
  1.3872 -  }
  1.3873 -
  1.3874 -  return error;
  1.3875 -}
  1.3876 -
  1.3877 -#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
  1.3878 -
  1.3879 -/*
  1.3880 -Paeth predictor, used by PNG filter type 4
  1.3881 -The parameters are of type short, but should come from unsigned chars, the shorts
  1.3882 -are only needed to make the paeth calculation correct.
  1.3883 -*/
  1.3884 -static unsigned char paethPredictor(short a, short b, short c) {
  1.3885 -  short pa = LODEPNG_ABS(b - c);
  1.3886 -  short pb = LODEPNG_ABS(a - c);
  1.3887 -  short pc = LODEPNG_ABS(a + b - c - c);
  1.3888 -  /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */
  1.3889 -  if(pb < pa) { a = b; pa = pb; }
  1.3890 -  return (pc < pa) ? c : a;
  1.3891 -}
  1.3892 -
  1.3893 -/*shared values used by multiple Adam7 related functions*/
  1.3894 -
  1.3895 -static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
  1.3896 -static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
  1.3897 -static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
  1.3898 -static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
  1.3899 -
  1.3900 -/*
  1.3901 -Outputs various dimensions and positions in the image related to the Adam7 reduced images.
  1.3902 -passw: output containing the width of the 7 passes
  1.3903 -passh: output containing the height of the 7 passes
  1.3904 -filter_passstart: output containing the index of the start and end of each
  1.3905 - reduced image with filter bytes
  1.3906 -padded_passstart output containing the index of the start and end of each
  1.3907 - reduced image when without filter bytes but with padded scanlines
  1.3908 -passstart: output containing the index of the start and end of each reduced
  1.3909 - image without padding between scanlines, but still padding between the images
  1.3910 -w, h: width and height of non-interlaced image
  1.3911 -bpp: bits per pixel
  1.3912 -"padded" is only relevant if bpp is less than 8 and a scanline or image does not
  1.3913 - end at a full byte
  1.3914 -*/
  1.3915 -static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
  1.3916 -                                size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) {
  1.3917 -  /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
  1.3918 -  unsigned i;
  1.3919 -
  1.3920 -  /*calculate width and height in pixels of each pass*/
  1.3921 -  for(i = 0; i != 7; ++i) {
  1.3922 -    passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
  1.3923 -    passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
  1.3924 -    if(passw[i] == 0) passh[i] = 0;
  1.3925 -    if(passh[i] == 0) passw[i] = 0;
  1.3926 -  }
  1.3927 -
  1.3928 -  filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
  1.3929 -  for(i = 0; i != 7; ++i) {
  1.3930 -    /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
  1.3931 -    filter_passstart[i + 1] = filter_passstart[i]
  1.3932 -                            + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);
  1.3933 -    /*bits padded if needed to fill full byte at end of each scanline*/
  1.3934 -    padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);
  1.3935 -    /*only padded at end of reduced image*/
  1.3936 -    passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;
  1.3937 -  }
  1.3938 -}
  1.3939 -
  1.3940 -#ifdef LODEPNG_COMPILE_DECODER
  1.3941 -
  1.3942 -/* ////////////////////////////////////////////////////////////////////////// */
  1.3943 -/* / PNG Decoder                                                            / */
  1.3944 -/* ////////////////////////////////////////////////////////////////////////// */
  1.3945 -
  1.3946 -/*read the information from the header and store it in the LodePNGInfo. return value is error*/
  1.3947 -unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
  1.3948 -                         const unsigned char* in, size_t insize) {
  1.3949 -  unsigned width, height;
  1.3950 -  LodePNGInfo* info = &state->info_png;
  1.3951 -  if(insize == 0 || in == 0) {
  1.3952 -    CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
  1.3953 -  }
  1.3954 -  if(insize < 33) {
  1.3955 -    CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
  1.3956 -  }
  1.3957 -
  1.3958 -  /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
  1.3959 -  /* TODO: remove this. One should use a new LodePNGState for new sessions */
  1.3960 -  lodepng_info_cleanup(info);
  1.3961 -  lodepng_info_init(info);
  1.3962 -
  1.3963 -  if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
  1.3964 -     || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
  1.3965 -    CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
  1.3966 -  }
  1.3967 -  if(lodepng_chunk_length(in + 8) != 13) {
  1.3968 -    CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
  1.3969 -  }
  1.3970 -  if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {
  1.3971 -    CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
  1.3972 -  }
  1.3973 -
  1.3974 -  /*read the values given in the header*/
  1.3975 -  width = lodepng_read32bitInt(&in[16]);
  1.3976 -  height = lodepng_read32bitInt(&in[20]);
  1.3977 -  /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/
  1.3978 -  if(w) *w = width;
  1.3979 -  if(h) *h = height;
  1.3980 -  info->color.bitdepth = in[24];
  1.3981 -  info->color.colortype = (LodePNGColorType)in[25];
  1.3982 -  info->compression_method = in[26];
  1.3983 -  info->filter_method = in[27];
  1.3984 -  info->interlace_method = in[28];
  1.3985 -
  1.3986 -  /*errors returned only after the parsing so other values are still output*/
  1.3987 -
  1.3988 -  /*error: invalid image size*/
  1.3989 -  if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);
  1.3990 -  /*error: invalid colortype or bitdepth combination*/
  1.3991 -  state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
  1.3992 -  if(state->error) return state->error;
  1.3993 -  /*error: only compression method 0 is allowed in the specification*/
  1.3994 -  if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
  1.3995 -  /*error: only filter method 0 is allowed in the specification*/
  1.3996 -  if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
  1.3997 -  /*error: only interlace methods 0 and 1 exist in the specification*/
  1.3998 -  if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
  1.3999 -
  1.4000 -  if(!state->decoder.ignore_crc) {
  1.4001 -    unsigned CRC = lodepng_read32bitInt(&in[29]);
  1.4002 -    unsigned checksum = lodepng_crc32(&in[12], 17);
  1.4003 -    if(CRC != checksum) {
  1.4004 -      CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
  1.4005 -    }
  1.4006 -  }
  1.4007 -
  1.4008 -  return state->error;
  1.4009 -}
  1.4010 -
  1.4011 -static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
  1.4012 -                                 size_t bytewidth, unsigned char filterType, size_t length) {
  1.4013 -  /*
  1.4014 -  For PNG filter method 0
  1.4015 -  unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
  1.4016 -  the filter works byte per byte (bytewidth = 1)
  1.4017 -  precon is the previous unfiltered scanline, recon the result, scanline the current one
  1.4018 -  the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
  1.4019 -  recon and scanline MAY be the same memory address! precon must be disjoint.
  1.4020 -  */
  1.4021 -
  1.4022 -  size_t i;
  1.4023 -  switch(filterType) {
  1.4024 -    case 0:
  1.4025 -      for(i = 0; i != length; ++i) recon[i] = scanline[i];
  1.4026 -      break;
  1.4027 -    case 1:
  1.4028 -      for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
  1.4029 -      for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
  1.4030 -      break;
  1.4031 -    case 2:
  1.4032 -      if(precon) {
  1.4033 -        for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
  1.4034 -      } else {
  1.4035 -        for(i = 0; i != length; ++i) recon[i] = scanline[i];
  1.4036 -      }
  1.4037 -      break;
  1.4038 -    case 3:
  1.4039 -      if(precon) {
  1.4040 -        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);
  1.4041 -        for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1u);
  1.4042 -      } else {
  1.4043 -        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
  1.4044 -        for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1u);
  1.4045 -      }
  1.4046 -      break;
  1.4047 -    case 4:
  1.4048 -      if(precon) {
  1.4049 -        for(i = 0; i != bytewidth; ++i) {
  1.4050 -          recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
  1.4051 -        }
  1.4052 -
  1.4053 -        /* Unroll independent paths of the paeth predictor. A 6x and 8x version would also be possible but that
  1.4054 -        adds too much code. Whether this actually speeds anything up at all depends on compiler and settings. */
  1.4055 -        if(bytewidth >= 4) {
  1.4056 -          for(; i + 3 < length; i += 4) {
  1.4057 -            size_t j = i - bytewidth;
  1.4058 -            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];
  1.4059 -            unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];
  1.4060 -            unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];
  1.4061 -            unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2], q3 = precon[j + 3];
  1.4062 -            recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  1.4063 -            recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  1.4064 -            recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
  1.4065 -            recon[i + 3] = s3 + paethPredictor(r3, p3, q3);
  1.4066 -          }
  1.4067 -        } else if(bytewidth >= 3) {
  1.4068 -          for(; i + 2 < length; i += 3) {
  1.4069 -            size_t j = i - bytewidth;
  1.4070 -            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];
  1.4071 -            unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];
  1.4072 -            unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];
  1.4073 -            unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2];
  1.4074 -            recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  1.4075 -            recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  1.4076 -            recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
  1.4077 -          }
  1.4078 -        } else if(bytewidth >= 2) {
  1.4079 -          for(; i + 1 < length; i += 2) {
  1.4080 -            size_t j = i - bytewidth;
  1.4081 -            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];
  1.4082 -            unsigned char r0 = recon[j + 0], r1 = recon[j + 1];
  1.4083 -            unsigned char p0 = precon[i + 0], p1 = precon[i + 1];
  1.4084 -            unsigned char q0 = precon[j + 0], q1 = precon[j + 1];
  1.4085 -            recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  1.4086 -            recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  1.4087 -          }
  1.4088 -        }
  1.4089 -
  1.4090 -        for(; i != length; ++i) {
  1.4091 -          recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
  1.4092 -        }
  1.4093 -      } else {
  1.4094 -        for(i = 0; i != bytewidth; ++i) {
  1.4095 -          recon[i] = scanline[i];
  1.4096 -        }
  1.4097 -        for(i = bytewidth; i < length; ++i) {
  1.4098 -          /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
  1.4099 -          recon[i] = (scanline[i] + recon[i - bytewidth]);
  1.4100 -        }
  1.4101 -      }
  1.4102 -      break;
  1.4103 -    default: return 36; /*error: nonexistent filter type given*/
  1.4104 -  }
  1.4105 -  return 0;
  1.4106 -}
  1.4107 -
  1.4108 -static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  1.4109 -  /*
  1.4110 -  For PNG filter method 0
  1.4111 -  this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
  1.4112 -  out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
  1.4113 -  w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
  1.4114 -  in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
  1.4115 -  */
  1.4116 -
  1.4117 -  unsigned y;
  1.4118 -  unsigned char* prevline = 0;
  1.4119 -
  1.4120 -  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
  1.4121 -  size_t bytewidth = (bpp + 7u) / 8u;
  1.4122 -  size_t linebytes = (w * bpp + 7u) / 8u;
  1.4123 -
  1.4124 -  for(y = 0; y < h; ++y) {
  1.4125 -    size_t outindex = linebytes * y;
  1.4126 -    size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  1.4127 -    unsigned char filterType = in[inindex];
  1.4128 -
  1.4129 -    CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
  1.4130 -
  1.4131 -    prevline = &out[outindex];
  1.4132 -  }
  1.4133 -
  1.4134 -  return 0;
  1.4135 -}
  1.4136 -
  1.4137 -/*
  1.4138 -in: Adam7 interlaced image, with no padding bits between scanlines, but between
  1.4139 - reduced images so that each reduced image starts at a byte.
  1.4140 -out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
  1.4141 -bpp: bits per pixel
  1.4142 -out has the following size in bits: w * h * bpp.
  1.4143 -in is possibly bigger due to padding bits between reduced images.
  1.4144 -out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
  1.4145 -(because that's likely a little bit faster)
  1.4146 -NOTE: comments about padding bits are only relevant if bpp < 8
  1.4147 -*/
  1.4148 -static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  1.4149 -  unsigned passw[7], passh[7];
  1.4150 -  size_t filter_passstart[8], padded_passstart[8], passstart[8];
  1.4151 -  unsigned i;
  1.4152 -
  1.4153 -  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  1.4154 -
  1.4155 -  if(bpp >= 8) {
  1.4156 -    for(i = 0; i != 7; ++i) {
  1.4157 -      unsigned x, y, b;
  1.4158 -      size_t bytewidth = bpp / 8u;
  1.4159 -      for(y = 0; y < passh[i]; ++y)
  1.4160 -      for(x = 0; x < passw[i]; ++x) {
  1.4161 -        size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
  1.4162 -        size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
  1.4163 -        for(b = 0; b < bytewidth; ++b) {
  1.4164 -          out[pixeloutstart + b] = in[pixelinstart + b];
  1.4165 -        }
  1.4166 -      }
  1.4167 -    }
  1.4168 -  } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
  1.4169 -    for(i = 0; i != 7; ++i) {
  1.4170 -      unsigned x, y, b;
  1.4171 -      unsigned ilinebits = bpp * passw[i];
  1.4172 -      unsigned olinebits = bpp * w;
  1.4173 -      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
  1.4174 -      for(y = 0; y < passh[i]; ++y)
  1.4175 -      for(x = 0; x < passw[i]; ++x) {
  1.4176 -        ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
  1.4177 -        obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
  1.4178 -        for(b = 0; b < bpp; ++b) {
  1.4179 -          unsigned char bit = readBitFromReversedStream(&ibp, in);
  1.4180 -          setBitOfReversedStream(&obp, out, bit);
  1.4181 -        }
  1.4182 -      }
  1.4183 -    }
  1.4184 -  }
  1.4185 -}
  1.4186 -
  1.4187 -static void removePaddingBits(unsigned char* out, const unsigned char* in,
  1.4188 -                              size_t olinebits, size_t ilinebits, unsigned h) {
  1.4189 -  /*
  1.4190 -  After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
  1.4191 -  to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
  1.4192 -  for the Adam7 code, the color convert code and the output to the user.
  1.4193 -  in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
  1.4194 -  have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
  1.4195 -  also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
  1.4196 -  only useful if (ilinebits - olinebits) is a value in the range 1..7
  1.4197 -  */
  1.4198 -  unsigned y;
  1.4199 -  size_t diff = ilinebits - olinebits;
  1.4200 -  size_t ibp = 0, obp = 0; /*input and output bit pointers*/
  1.4201 -  for(y = 0; y < h; ++y) {
  1.4202 -    size_t x;
  1.4203 -    for(x = 0; x < olinebits; ++x) {
  1.4204 -      unsigned char bit = readBitFromReversedStream(&ibp, in);
  1.4205 -      setBitOfReversedStream(&obp, out, bit);
  1.4206 -    }
  1.4207 -    ibp += diff;
  1.4208 -  }
  1.4209 -}
  1.4210 -
  1.4211 -/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
  1.4212 -the IDAT chunks (with filter index bytes and possible padding bits)
  1.4213 -return value is error*/
  1.4214 -static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
  1.4215 -                                     unsigned w, unsigned h, const LodePNGInfo* info_png) {
  1.4216 -  /*
  1.4217 -  This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
  1.4218 -  Steps:
  1.4219 -  *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)
  1.4220 -  *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
  1.4221 -  NOTE: the in buffer will be overwritten with intermediate data!
  1.4222 -  */
  1.4223 -  unsigned bpp = lodepng_get_bpp(&info_png->color);
  1.4224 -  if(bpp == 0) return 31; /*error: invalid colortype*/
  1.4225 -
  1.4226 -  if(info_png->interlace_method == 0) {
  1.4227 -    if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
  1.4228 -      CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
  1.4229 -      removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);
  1.4230 -    }
  1.4231 -    /*we can immediately filter into the out buffer, no other steps needed*/
  1.4232 -    else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
  1.4233 -  } else /*interlace_method is 1 (Adam7)*/ {
  1.4234 -    unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
  1.4235 -    unsigned i;
  1.4236 -
  1.4237 -    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  1.4238 -
  1.4239 -    for(i = 0; i != 7; ++i) {
  1.4240 -      CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
  1.4241 -      /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
  1.4242 -      move bytes instead of bits or move not at all*/
  1.4243 -      if(bpp < 8) {
  1.4244 -        /*remove padding bits in scanlines; after this there still may be padding
  1.4245 -        bits between the different reduced images: each reduced image still starts nicely at a byte*/
  1.4246 -        removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
  1.4247 -                          ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);
  1.4248 -      }
  1.4249 -    }
  1.4250 -
  1.4251 -    Adam7_deinterlace(out, in, w, h, bpp);
  1.4252 -  }
  1.4253 -
  1.4254 -  return 0;
  1.4255 -}
  1.4256 -
  1.4257 -static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
  1.4258 -  unsigned pos = 0, i;
  1.4259 -  color->palettesize = chunkLength / 3u;
  1.4260 -  if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/
  1.4261 -  lodepng_color_mode_alloc_palette(color);
  1.4262 -  if(!color->palette && color->palettesize) {
  1.4263 -    color->palettesize = 0;
  1.4264 -    return 83; /*alloc fail*/
  1.4265 -  }
  1.4266 -
  1.4267 -  for(i = 0; i != color->palettesize; ++i) {
  1.4268 -    color->palette[4 * i + 0] = data[pos++]; /*R*/
  1.4269 -    color->palette[4 * i + 1] = data[pos++]; /*G*/
  1.4270 -    color->palette[4 * i + 2] = data[pos++]; /*B*/
  1.4271 -    color->palette[4 * i + 3] = 255; /*alpha*/
  1.4272 -  }
  1.4273 -
  1.4274 -  return 0; /* OK */
  1.4275 -}
  1.4276 -
  1.4277 -static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
  1.4278 -  unsigned i;
  1.4279 -  if(color->colortype == LCT_PALETTE) {
  1.4280 -    /*error: more alpha values given than there are palette entries*/
  1.4281 -    if(chunkLength > color->palettesize) return 39;
  1.4282 -
  1.4283 -    for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
  1.4284 -  } else if(color->colortype == LCT_GREY) {
  1.4285 -    /*error: this chunk must be 2 bytes for grayscale image*/
  1.4286 -    if(chunkLength != 2) return 30;
  1.4287 -
  1.4288 -    color->key_defined = 1;
  1.4289 -    color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
  1.4290 -  } else if(color->colortype == LCT_RGB) {
  1.4291 -    /*error: this chunk must be 6 bytes for RGB image*/
  1.4292 -    if(chunkLength != 6) return 41;
  1.4293 -
  1.4294 -    color->key_defined = 1;
  1.4295 -    color->key_r = 256u * data[0] + data[1];
  1.4296 -    color->key_g = 256u * data[2] + data[3];
  1.4297 -    color->key_b = 256u * data[4] + data[5];
  1.4298 -  }
  1.4299 -  else return 42; /*error: tRNS chunk not allowed for other color models*/
  1.4300 -
  1.4301 -  return 0; /* OK */
  1.4302 -}
  1.4303 -
  1.4304 -
  1.4305 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4306 -/*background color chunk (bKGD)*/
  1.4307 -static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4308 -  if(info->color.colortype == LCT_PALETTE) {
  1.4309 -    /*error: this chunk must be 1 byte for indexed color image*/
  1.4310 -    if(chunkLength != 1) return 43;
  1.4311 -
  1.4312 -    /*error: invalid palette index, or maybe this chunk appeared before PLTE*/
  1.4313 -    if(data[0] >= info->color.palettesize) return 103;
  1.4314 -
  1.4315 -    info->background_defined = 1;
  1.4316 -    info->background_r = info->background_g = info->background_b = data[0];
  1.4317 -  } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
  1.4318 -    /*error: this chunk must be 2 bytes for grayscale image*/
  1.4319 -    if(chunkLength != 2) return 44;
  1.4320 -
  1.4321 -    /*the values are truncated to bitdepth in the PNG file*/
  1.4322 -    info->background_defined = 1;
  1.4323 -    info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
  1.4324 -  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
  1.4325 -    /*error: this chunk must be 6 bytes for grayscale image*/
  1.4326 -    if(chunkLength != 6) return 45;
  1.4327 -
  1.4328 -    /*the values are truncated to bitdepth in the PNG file*/
  1.4329 -    info->background_defined = 1;
  1.4330 -    info->background_r = 256u * data[0] + data[1];
  1.4331 -    info->background_g = 256u * data[2] + data[3];
  1.4332 -    info->background_b = 256u * data[4] + data[5];
  1.4333 -  }
  1.4334 -
  1.4335 -  return 0; /* OK */
  1.4336 -}
  1.4337 -
  1.4338 -/*text chunk (tEXt)*/
  1.4339 -static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4340 -  unsigned error = 0;
  1.4341 -  char *key = 0, *str = 0;
  1.4342 -  unsigned i;
  1.4343 -
  1.4344 -  while(!error) /*not really a while loop, only used to break on error*/ {
  1.4345 -    unsigned length, string2_begin;
  1.4346 -
  1.4347 -    length = 0;
  1.4348 -    while(length < chunkLength && data[length] != 0) ++length;
  1.4349 -    /*even though it's not allowed by the standard, no error is thrown if
  1.4350 -    there's no null termination char, if the text is empty*/
  1.4351 -    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  1.4352 -
  1.4353 -    key = (char*)lodepng_malloc(length + 1);
  1.4354 -    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4355 -
  1.4356 -    key[length] = 0;
  1.4357 -    for(i = 0; i != length; ++i) key[i] = (char)data[i];
  1.4358 -
  1.4359 -    string2_begin = length + 1; /*skip keyword null terminator*/
  1.4360 -
  1.4361 -    length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);
  1.4362 -    str = (char*)lodepng_malloc(length + 1);
  1.4363 -    if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4364 -
  1.4365 -    str[length] = 0;
  1.4366 -    for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
  1.4367 -
  1.4368 -    error = lodepng_add_text(info, key, str);
  1.4369 -
  1.4370 -    break;
  1.4371 -  }
  1.4372 -
  1.4373 -  lodepng_free(key);
  1.4374 -  lodepng_free(str);
  1.4375 -
  1.4376 -  return error;
  1.4377 -}
  1.4378 -
  1.4379 -/*compressed text chunk (zTXt)*/
  1.4380 -static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  1.4381 -                               const unsigned char* data, size_t chunkLength) {
  1.4382 -  unsigned error = 0;
  1.4383 -  unsigned i;
  1.4384 -
  1.4385 -  unsigned length, string2_begin;
  1.4386 -  char *key = 0;
  1.4387 -  ucvector decoded;
  1.4388 -
  1.4389 -  ucvector_init(&decoded);
  1.4390 -
  1.4391 -  while(!error) /*not really a while loop, only used to break on error*/ {
  1.4392 -    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  1.4393 -    if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
  1.4394 -    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  1.4395 -
  1.4396 -    key = (char*)lodepng_malloc(length + 1);
  1.4397 -    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4398 -
  1.4399 -    key[length] = 0;
  1.4400 -    for(i = 0; i != length; ++i) key[i] = (char)data[i];
  1.4401 -
  1.4402 -    if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
  1.4403 -
  1.4404 -    string2_begin = length + 2;
  1.4405 -    if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
  1.4406 -
  1.4407 -    length = (unsigned)chunkLength - string2_begin;
  1.4408 -    /*will fail if zlib error, e.g. if length is too small*/
  1.4409 -    error = zlib_decompress(&decoded.data, &decoded.size,
  1.4410 -                            &data[string2_begin],
  1.4411 -                            length, zlibsettings);
  1.4412 -    if(error) break;
  1.4413 -    ucvector_push_back(&decoded, 0);
  1.4414 -
  1.4415 -    error = lodepng_add_text(info, key, (char*)decoded.data);
  1.4416 -
  1.4417 -    break;
  1.4418 -  }
  1.4419 -
  1.4420 -  lodepng_free(key);
  1.4421 -  ucvector_cleanup(&decoded);
  1.4422 -
  1.4423 -  return error;
  1.4424 -}
  1.4425 -
  1.4426 -/*international text chunk (iTXt)*/
  1.4427 -static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  1.4428 -                               const unsigned char* data, size_t chunkLength) {
  1.4429 -  unsigned error = 0;
  1.4430 -  unsigned i;
  1.4431 -
  1.4432 -  unsigned length, begin, compressed;
  1.4433 -  char *key = 0, *langtag = 0, *transkey = 0;
  1.4434 -  ucvector decoded;
  1.4435 -  ucvector_init(&decoded); /* TODO: only use in case of compressed text */
  1.4436 -
  1.4437 -  while(!error) /*not really a while loop, only used to break on error*/ {
  1.4438 -    /*Quick check if the chunk length isn't too small. Even without check
  1.4439 -    it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
  1.4440 -    if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
  1.4441 -
  1.4442 -    /*read the key*/
  1.4443 -    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  1.4444 -    if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
  1.4445 -    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  1.4446 -
  1.4447 -    key = (char*)lodepng_malloc(length + 1);
  1.4448 -    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4449 -
  1.4450 -    key[length] = 0;
  1.4451 -    for(i = 0; i != length; ++i) key[i] = (char)data[i];
  1.4452 -
  1.4453 -    /*read the compression method*/
  1.4454 -    compressed = data[length + 1];
  1.4455 -    if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
  1.4456 -
  1.4457 -    /*even though it's not allowed by the standard, no error is thrown if
  1.4458 -    there's no null termination char, if the text is empty for the next 3 texts*/
  1.4459 -
  1.4460 -    /*read the langtag*/
  1.4461 -    begin = length + 3;
  1.4462 -    length = 0;
  1.4463 -    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
  1.4464 -
  1.4465 -    langtag = (char*)lodepng_malloc(length + 1);
  1.4466 -    if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4467 -
  1.4468 -    langtag[length] = 0;
  1.4469 -    for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
  1.4470 -
  1.4471 -    /*read the transkey*/
  1.4472 -    begin += length + 1;
  1.4473 -    length = 0;
  1.4474 -    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
  1.4475 -
  1.4476 -    transkey = (char*)lodepng_malloc(length + 1);
  1.4477 -    if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
  1.4478 -
  1.4479 -    transkey[length] = 0;
  1.4480 -    for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
  1.4481 -
  1.4482 -    /*read the actual text*/
  1.4483 -    begin += length + 1;
  1.4484 -
  1.4485 -    length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;
  1.4486 -
  1.4487 -    if(compressed) {
  1.4488 -      /*will fail if zlib error, e.g. if length is too small*/
  1.4489 -      error = zlib_decompress(&decoded.data, &decoded.size,
  1.4490 -                              &data[begin],
  1.4491 -                              length, zlibsettings);
  1.4492 -      if(error) break;
  1.4493 -      if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
  1.4494 -      ucvector_push_back(&decoded, 0);
  1.4495 -    } else {
  1.4496 -      if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
  1.4497 -
  1.4498 -      decoded.data[length] = 0;
  1.4499 -      for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
  1.4500 -    }
  1.4501 -
  1.4502 -    error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
  1.4503 -
  1.4504 -    break;
  1.4505 -  }
  1.4506 -
  1.4507 -  lodepng_free(key);
  1.4508 -  lodepng_free(langtag);
  1.4509 -  lodepng_free(transkey);
  1.4510 -  ucvector_cleanup(&decoded);
  1.4511 -
  1.4512 -  return error;
  1.4513 -}
  1.4514 -
  1.4515 -static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4516 -  if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
  1.4517 -
  1.4518 -  info->time_defined = 1;
  1.4519 -  info->time.year = 256u * data[0] + data[1];
  1.4520 -  info->time.month = data[2];
  1.4521 -  info->time.day = data[3];
  1.4522 -  info->time.hour = data[4];
  1.4523 -  info->time.minute = data[5];
  1.4524 -  info->time.second = data[6];
  1.4525 -
  1.4526 -  return 0; /* OK */
  1.4527 -}
  1.4528 -
  1.4529 -static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4530 -  if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
  1.4531 -
  1.4532 -  info->phys_defined = 1;
  1.4533 -  info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
  1.4534 -  info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
  1.4535 -  info->phys_unit = data[8];
  1.4536 -
  1.4537 -  return 0; /* OK */
  1.4538 -}
  1.4539 -
  1.4540 -static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4541 -  if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/
  1.4542 -
  1.4543 -  info->gama_defined = 1;
  1.4544 -  info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
  1.4545 -
  1.4546 -  return 0; /* OK */
  1.4547 -}
  1.4548 -
  1.4549 -static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4550 -  if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/
  1.4551 -
  1.4552 -  info->chrm_defined = 1;
  1.4553 -  info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];
  1.4554 -  info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];
  1.4555 -  info->chrm_red_x   = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];
  1.4556 -  info->chrm_red_y   = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];
  1.4557 -  info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
  1.4558 -  info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
  1.4559 -  info->chrm_blue_x  = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];
  1.4560 -  info->chrm_blue_y  = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];
  1.4561 -
  1.4562 -  return 0; /* OK */
  1.4563 -}
  1.4564 -
  1.4565 -static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  1.4566 -  if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/
  1.4567 -
  1.4568 -  info->srgb_defined = 1;
  1.4569 -  info->srgb_intent = data[0];
  1.4570 -
  1.4571 -  return 0; /* OK */
  1.4572 -}
  1.4573 -
  1.4574 -static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  1.4575 -                               const unsigned char* data, size_t chunkLength) {
  1.4576 -  unsigned error = 0;
  1.4577 -  unsigned i;
  1.4578 -
  1.4579 -  unsigned length, string2_begin;
  1.4580 -  ucvector decoded;
  1.4581 -
  1.4582 -  info->iccp_defined = 1;
  1.4583 -  if(info->iccp_name) lodepng_clear_icc(info);
  1.4584 -
  1.4585 -  for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  1.4586 -  if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/
  1.4587 -  if(length < 1 || length > 79) return 89; /*keyword too short or long*/
  1.4588 -
  1.4589 -  info->iccp_name = (char*)lodepng_malloc(length + 1);
  1.4590 -  if(!info->iccp_name) return 83; /*alloc fail*/
  1.4591 -
  1.4592 -  info->iccp_name[length] = 0;
  1.4593 -  for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];
  1.4594 -
  1.4595 -  if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/
  1.4596 -
  1.4597 -  string2_begin = length + 2;
  1.4598 -  if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/
  1.4599 -
  1.4600 -  length = (unsigned)chunkLength - string2_begin;
  1.4601 -  ucvector_init(&decoded);
  1.4602 -  error = zlib_decompress(&decoded.data, &decoded.size,
  1.4603 -                          &data[string2_begin],
  1.4604 -                          length, zlibsettings);
  1.4605 -  if(!error) {
  1.4606 -    if(decoded.size) {
  1.4607 -      info->iccp_profile_size = decoded.size;
  1.4608 -      info->iccp_profile = (unsigned char*)lodepng_malloc(decoded.size);
  1.4609 -      if(info->iccp_profile) {
  1.4610 -        lodepng_memcpy(info->iccp_profile, decoded.data, decoded.size);
  1.4611 -      } else {
  1.4612 -        error = 83; /* alloc fail */
  1.4613 -      }
  1.4614 -    } else {
  1.4615 -      error = 100; /*invalid ICC profile size*/
  1.4616 -    }
  1.4617 -  }
  1.4618 -  ucvector_cleanup(&decoded);
  1.4619 -  return error;
  1.4620 -}
  1.4621 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4622 -
  1.4623 -unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
  1.4624 -                               const unsigned char* in, size_t insize) {
  1.4625 -  const unsigned char* chunk = in + pos;
  1.4626 -  unsigned chunkLength;
  1.4627 -  const unsigned char* data;
  1.4628 -  unsigned unhandled = 0;
  1.4629 -  unsigned error = 0;
  1.4630 -
  1.4631 -  if (pos + 4 > insize) return 30;
  1.4632 -  chunkLength = lodepng_chunk_length(chunk);
  1.4633 -  if(chunkLength > 2147483647) return 63;
  1.4634 -  data = lodepng_chunk_data_const(chunk);
  1.4635 -  if(data + chunkLength + 4 > in + insize) return 30;
  1.4636 -
  1.4637 -  if(lodepng_chunk_type_equals(chunk, "PLTE")) {
  1.4638 -    error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
  1.4639 -  } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
  1.4640 -    error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
  1.4641 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4642 -  } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
  1.4643 -    error = readChunk_bKGD(&state->info_png, data, chunkLength);
  1.4644 -  } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
  1.4645 -    error = readChunk_tEXt(&state->info_png, data, chunkLength);
  1.4646 -  } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
  1.4647 -    error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4648 -  } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
  1.4649 -    error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4650 -  } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
  1.4651 -    error = readChunk_tIME(&state->info_png, data, chunkLength);
  1.4652 -  } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
  1.4653 -    error = readChunk_pHYs(&state->info_png, data, chunkLength);
  1.4654 -  } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
  1.4655 -    error = readChunk_gAMA(&state->info_png, data, chunkLength);
  1.4656 -  } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
  1.4657 -    error = readChunk_cHRM(&state->info_png, data, chunkLength);
  1.4658 -  } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
  1.4659 -    error = readChunk_sRGB(&state->info_png, data, chunkLength);
  1.4660 -  } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
  1.4661 -    error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4662 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4663 -  } else {
  1.4664 -    /* unhandled chunk is ok (is not an error) */
  1.4665 -    unhandled = 1;
  1.4666 -  }
  1.4667 -
  1.4668 -  if(!error && !unhandled && !state->decoder.ignore_crc) {
  1.4669 -    if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/
  1.4670 -  }
  1.4671 -
  1.4672 -  return error;
  1.4673 -}
  1.4674 -
  1.4675 -/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
  1.4676 -static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
  1.4677 -                          LodePNGState* state,
  1.4678 -                          const unsigned char* in, size_t insize) {
  1.4679 -  unsigned char IEND = 0;
  1.4680 -  const unsigned char* chunk;
  1.4681 -  size_t i;
  1.4682 -  ucvector idat; /*the data from idat chunks*/
  1.4683 -  unsigned char* scanlines = 0;
  1.4684 -  size_t scanlines_size = 0, expected_size = 0;
  1.4685 -  size_t outsize = 0;
  1.4686 -
  1.4687 -  /*for unknown chunk order*/
  1.4688 -  unsigned unknown = 0;
  1.4689 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4690 -  unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
  1.4691 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4692 -
  1.4693 -
  1.4694 -  /* safe output values in case error happens */
  1.4695 -  *out = 0;
  1.4696 -  *w = *h = 0;
  1.4697 -
  1.4698 -  state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
  1.4699 -  if(state->error) return;
  1.4700 -
  1.4701 -  if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
  1.4702 -    CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
  1.4703 -  }
  1.4704 -
  1.4705 -  ucvector_init(&idat);
  1.4706 -  chunk = &in[33]; /*first byte of the first chunk after the header*/
  1.4707 -
  1.4708 -  /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
  1.4709 -  IDAT data is put at the start of the in buffer*/
  1.4710 -  while(!IEND && !state->error) {
  1.4711 -    unsigned chunkLength;
  1.4712 -    const unsigned char* data; /*the data in the chunk*/
  1.4713 -
  1.4714 -    /*error: size of the in buffer too small to contain next chunk*/
  1.4715 -    if((size_t)((chunk - in) + 12) > insize || chunk < in) {
  1.4716 -      if(state->decoder.ignore_end) break; /*other errors may still happen though*/
  1.4717 -      CERROR_BREAK(state->error, 30);
  1.4718 -    }
  1.4719 -
  1.4720 -    /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
  1.4721 -    chunkLength = lodepng_chunk_length(chunk);
  1.4722 -    /*error: chunk length larger than the max PNG chunk size*/
  1.4723 -    if(chunkLength > 2147483647) {
  1.4724 -      if(state->decoder.ignore_end) break; /*other errors may still happen though*/
  1.4725 -      CERROR_BREAK(state->error, 63);
  1.4726 -    }
  1.4727 -
  1.4728 -    if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) {
  1.4729 -      CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
  1.4730 -    }
  1.4731 -
  1.4732 -    data = lodepng_chunk_data_const(chunk);
  1.4733 -
  1.4734 -    unknown = 0;
  1.4735 -
  1.4736 -    /*IDAT chunk, containing compressed image data*/
  1.4737 -    if(lodepng_chunk_type_equals(chunk, "IDAT")) {
  1.4738 -      size_t oldsize = idat.size;
  1.4739 -      size_t newsize;
  1.4740 -      if(lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
  1.4741 -      if(!ucvector_resize(&idat, newsize)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
  1.4742 -      for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
  1.4743 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4744 -      critical_pos = 3;
  1.4745 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4746 -    } else if(lodepng_chunk_type_equals(chunk, "IEND")) {
  1.4747 -      /*IEND chunk*/
  1.4748 -      IEND = 1;
  1.4749 -    } else if(lodepng_chunk_type_equals(chunk, "PLTE")) {
  1.4750 -      /*palette chunk (PLTE)*/
  1.4751 -      state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
  1.4752 -      if(state->error) break;
  1.4753 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4754 -      critical_pos = 2;
  1.4755 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4756 -    } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
  1.4757 -      /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
  1.4758 -      in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
  1.4759 -      affects the alpha channel of pixels. */
  1.4760 -      state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
  1.4761 -      if(state->error) break;
  1.4762 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4763 -      /*background color chunk (bKGD)*/
  1.4764 -    } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
  1.4765 -      state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
  1.4766 -      if(state->error) break;
  1.4767 -    } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
  1.4768 -      /*text chunk (tEXt)*/
  1.4769 -      if(state->decoder.read_text_chunks) {
  1.4770 -        state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
  1.4771 -        if(state->error) break;
  1.4772 -      }
  1.4773 -    } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
  1.4774 -      /*compressed text chunk (zTXt)*/
  1.4775 -      if(state->decoder.read_text_chunks) {
  1.4776 -        state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4777 -        if(state->error) break;
  1.4778 -      }
  1.4779 -    } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
  1.4780 -      /*international text chunk (iTXt)*/
  1.4781 -      if(state->decoder.read_text_chunks) {
  1.4782 -        state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4783 -        if(state->error) break;
  1.4784 -      }
  1.4785 -    } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
  1.4786 -      state->error = readChunk_tIME(&state->info_png, data, chunkLength);
  1.4787 -      if(state->error) break;
  1.4788 -    } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
  1.4789 -      state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
  1.4790 -      if(state->error) break;
  1.4791 -    } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
  1.4792 -      state->error = readChunk_gAMA(&state->info_png, data, chunkLength);
  1.4793 -      if(state->error) break;
  1.4794 -    } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
  1.4795 -      state->error = readChunk_cHRM(&state->info_png, data, chunkLength);
  1.4796 -      if(state->error) break;
  1.4797 -    } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
  1.4798 -      state->error = readChunk_sRGB(&state->info_png, data, chunkLength);
  1.4799 -      if(state->error) break;
  1.4800 -    } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
  1.4801 -      state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  1.4802 -      if(state->error) break;
  1.4803 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4804 -    } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {
  1.4805 -      /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
  1.4806 -      if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
  1.4807 -        CERROR_BREAK(state->error, 69);
  1.4808 -      }
  1.4809 -
  1.4810 -      unknown = 1;
  1.4811 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4812 -      if(state->decoder.remember_unknown_chunks) {
  1.4813 -        state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
  1.4814 -                                            &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
  1.4815 -        if(state->error) break;
  1.4816 -      }
  1.4817 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4818 -    }
  1.4819 -
  1.4820 -    if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {
  1.4821 -      if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
  1.4822 -    }
  1.4823 -
  1.4824 -    if(!IEND) chunk = lodepng_chunk_next_const(chunk);
  1.4825 -  }
  1.4826 -
  1.4827 -  if (state->info_png.color.colortype == LCT_PALETTE
  1.4828 -      && !state->info_png.color.palette) {
  1.4829 -    state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */
  1.4830 -  }
  1.4831 -
  1.4832 -  /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
  1.4833 -  If the decompressed size does not match the prediction, the image must be corrupt.*/
  1.4834 -  if(state->info_png.interlace_method == 0) {
  1.4835 -    expected_size = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color);
  1.4836 -  } else {
  1.4837 -    /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/
  1.4838 -    const LodePNGColorMode* color = &state->info_png.color;
  1.4839 -    expected_size = 0;
  1.4840 -    expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color);
  1.4841 -    if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color);
  1.4842 -    expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color);
  1.4843 -    if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color);
  1.4844 -    expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color);
  1.4845 -    if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color);
  1.4846 -    expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color);
  1.4847 -  }
  1.4848 -  if(!state->error) {
  1.4849 -    /* This allocated data will be realloced by zlib_decompress, initially at
  1.4850 -    smaller size again. But the fact that it's already allocated at full size
  1.4851 -    here speeds the multiple reallocs up. TODO: make zlib_decompress support
  1.4852 -    receiving already allocated buffer with expected size instead. */
  1.4853 -    scanlines = (unsigned char*)lodepng_malloc(expected_size);
  1.4854 -    if(!scanlines) state->error = 83; /*alloc fail*/
  1.4855 -    scanlines_size = 0;
  1.4856 -  }
  1.4857 -  if(!state->error) {
  1.4858 -    state->error = zlib_decompress(&scanlines, &scanlines_size, idat.data,
  1.4859 -                                   idat.size, &state->decoder.zlibsettings);
  1.4860 -    if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/
  1.4861 -  }
  1.4862 -  ucvector_cleanup(&idat);
  1.4863 -
  1.4864 -  if(!state->error) {
  1.4865 -    outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
  1.4866 -    *out = (unsigned char*)lodepng_malloc(outsize);
  1.4867 -    if(!*out) state->error = 83; /*alloc fail*/
  1.4868 -  }
  1.4869 -  if(!state->error) {
  1.4870 -    for(i = 0; i < outsize; i++) (*out)[i] = 0;
  1.4871 -    state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);
  1.4872 -  }
  1.4873 -  lodepng_free(scanlines);
  1.4874 -}
  1.4875 -
  1.4876 -unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
  1.4877 -                        LodePNGState* state,
  1.4878 -                        const unsigned char* in, size_t insize) {
  1.4879 -  *out = 0;
  1.4880 -  decodeGeneric(out, w, h, state, in, insize);
  1.4881 -  if(state->error) return state->error;
  1.4882 -  if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
  1.4883 -    /*same color type, no copying or converting of data needed*/
  1.4884 -    /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
  1.4885 -    the raw image has to the end user*/
  1.4886 -    if(!state->decoder.color_convert) {
  1.4887 -      state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
  1.4888 -      if(state->error) return state->error;
  1.4889 -    }
  1.4890 -  } else { /*color conversion needed*/
  1.4891 -    unsigned char* data = *out;
  1.4892 -    size_t outsize;
  1.4893 -
  1.4894 -    /*TODO: check if this works according to the statement in the documentation: "The converter can convert
  1.4895 -    from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
  1.4896 -    if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
  1.4897 -       && !(state->info_raw.bitdepth == 8)) {
  1.4898 -      return 56; /*unsupported color mode conversion*/
  1.4899 -    }
  1.4900 -
  1.4901 -    outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
  1.4902 -    *out = (unsigned char*)lodepng_malloc(outsize);
  1.4903 -    if(!(*out)) {
  1.4904 -      state->error = 83; /*alloc fail*/
  1.4905 -    }
  1.4906 -    else state->error = lodepng_convert(*out, data, &state->info_raw,
  1.4907 -                                        &state->info_png.color, *w, *h);
  1.4908 -    lodepng_free(data);
  1.4909 -  }
  1.4910 -  return state->error;
  1.4911 -}
  1.4912 -
  1.4913 -unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
  1.4914 -                               size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
  1.4915 -  unsigned error;
  1.4916 -  LodePNGState state;
  1.4917 -  lodepng_state_init(&state);
  1.4918 -  state.info_raw.colortype = colortype;
  1.4919 -  state.info_raw.bitdepth = bitdepth;
  1.4920 -  error = lodepng_decode(out, w, h, &state, in, insize);
  1.4921 -  lodepng_state_cleanup(&state);
  1.4922 -  return error;
  1.4923 -}
  1.4924 -
  1.4925 -unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
  1.4926 -  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
  1.4927 -}
  1.4928 -
  1.4929 -unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
  1.4930 -  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
  1.4931 -}
  1.4932 -
  1.4933 -#ifdef LODEPNG_COMPILE_DISK
  1.4934 -unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
  1.4935 -                             LodePNGColorType colortype, unsigned bitdepth) {
  1.4936 -  unsigned char* buffer = 0;
  1.4937 -  size_t buffersize;
  1.4938 -  unsigned error;
  1.4939 -  /* safe output values in case error happens */
  1.4940 -  *out = 0;
  1.4941 -  *w = *h = 0;
  1.4942 -  error = lodepng_load_file(&buffer, &buffersize, filename);
  1.4943 -  if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
  1.4944 -  lodepng_free(buffer);
  1.4945 -  return error;
  1.4946 -}
  1.4947 -
  1.4948 -unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
  1.4949 -  return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
  1.4950 -}
  1.4951 -
  1.4952 -unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
  1.4953 -  return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
  1.4954 -}
  1.4955 -#endif /*LODEPNG_COMPILE_DISK*/
  1.4956 -
  1.4957 -void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) {
  1.4958 -  settings->color_convert = 1;
  1.4959 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.4960 -  settings->read_text_chunks = 1;
  1.4961 -  settings->remember_unknown_chunks = 0;
  1.4962 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.4963 -  settings->ignore_crc = 0;
  1.4964 -  settings->ignore_critical = 0;
  1.4965 -  settings->ignore_end = 0;
  1.4966 -  lodepng_decompress_settings_init(&settings->zlibsettings);
  1.4967 -}
  1.4968 -
  1.4969 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.4970 -
  1.4971 -#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
  1.4972 -
  1.4973 -void lodepng_state_init(LodePNGState* state) {
  1.4974 -#ifdef LODEPNG_COMPILE_DECODER
  1.4975 -  lodepng_decoder_settings_init(&state->decoder);
  1.4976 -#endif /*LODEPNG_COMPILE_DECODER*/
  1.4977 -#ifdef LODEPNG_COMPILE_ENCODER
  1.4978 -  lodepng_encoder_settings_init(&state->encoder);
  1.4979 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.4980 -  lodepng_color_mode_init(&state->info_raw);
  1.4981 -  lodepng_info_init(&state->info_png);
  1.4982 -  state->error = 1;
  1.4983 -}
  1.4984 -
  1.4985 -void lodepng_state_cleanup(LodePNGState* state) {
  1.4986 -  lodepng_color_mode_cleanup(&state->info_raw);
  1.4987 -  lodepng_info_cleanup(&state->info_png);
  1.4988 -}
  1.4989 -
  1.4990 -void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) {
  1.4991 -  lodepng_state_cleanup(dest);
  1.4992 -  *dest = *source;
  1.4993 -  lodepng_color_mode_init(&dest->info_raw);
  1.4994 -  lodepng_info_init(&dest->info_png);
  1.4995 -  dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
  1.4996 -  dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
  1.4997 -}
  1.4998 -
  1.4999 -#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
  1.5000 -
  1.5001 -#ifdef LODEPNG_COMPILE_ENCODER
  1.5002 -
  1.5003 -/* ////////////////////////////////////////////////////////////////////////// */
  1.5004 -/* / PNG Encoder                                                            / */
  1.5005 -/* ////////////////////////////////////////////////////////////////////////// */
  1.5006 -
  1.5007 -/*chunkName must be string of 4 characters*/
  1.5008 -static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) {
  1.5009 -  CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
  1.5010 -  out->allocsize = out->size; /*fix the allocsize again*/
  1.5011 -  return 0;
  1.5012 -}
  1.5013 -
  1.5014 -static void writeSignature(ucvector* out) {
  1.5015 -  /*8 bytes PNG signature, aka the magic bytes*/
  1.5016 -  ucvector_push_back(out, 137);
  1.5017 -  ucvector_push_back(out, 80);
  1.5018 -  ucvector_push_back(out, 78);
  1.5019 -  ucvector_push_back(out, 71);
  1.5020 -  ucvector_push_back(out, 13);
  1.5021 -  ucvector_push_back(out, 10);
  1.5022 -  ucvector_push_back(out, 26);
  1.5023 -  ucvector_push_back(out, 10);
  1.5024 -}
  1.5025 -
  1.5026 -static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
  1.5027 -                              LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) {
  1.5028 -  unsigned char data[13];
  1.5029 -
  1.5030 -  lodepng_set32bitInt(data + 0, w); /*width*/
  1.5031 -  lodepng_set32bitInt(data + 4, h); /*height*/
  1.5032 -  data[8] = (unsigned char)bitdepth; /*bit depth*/
  1.5033 -  data[9] = (unsigned char)colortype; /*color type*/
  1.5034 -  data[10] = 0; /*compression method*/
  1.5035 -  data[11] = 0; /*filter method*/
  1.5036 -  data[12] = interlace_method; /*interlace method*/
  1.5037 -
  1.5038 -  return addChunk(out, "IHDR", data, sizeof(data));
  1.5039 -}
  1.5040 -
  1.5041 -static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) {
  1.5042 -  unsigned error = 0;
  1.5043 -  size_t i;
  1.5044 -  ucvector PLTE;
  1.5045 -  ucvector_init(&PLTE);
  1.5046 -  for(i = 0; i != info->palettesize * 4; ++i) {
  1.5047 -    /*add all channels except alpha channel*/
  1.5048 -    if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
  1.5049 -  }
  1.5050 -  error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
  1.5051 -  ucvector_cleanup(&PLTE);
  1.5052 -
  1.5053 -  return error;
  1.5054 -}
  1.5055 -
  1.5056 -static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) {
  1.5057 -  unsigned error = 0;
  1.5058 -  size_t i;
  1.5059 -  ucvector tRNS;
  1.5060 -  ucvector_init(&tRNS);
  1.5061 -  if(info->colortype == LCT_PALETTE) {
  1.5062 -    size_t amount = info->palettesize;
  1.5063 -    /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
  1.5064 -    for(i = info->palettesize; i != 0; --i) {
  1.5065 -      if(info->palette[4 * (i - 1) + 3] == 255) --amount;
  1.5066 -      else break;
  1.5067 -    }
  1.5068 -    /*add only alpha channel*/
  1.5069 -    for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
  1.5070 -  } else if(info->colortype == LCT_GREY) {
  1.5071 -    if(info->key_defined) {
  1.5072 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
  1.5073 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
  1.5074 -    }
  1.5075 -  } else if(info->colortype == LCT_RGB) {
  1.5076 -    if(info->key_defined) {
  1.5077 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
  1.5078 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
  1.5079 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8));
  1.5080 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
  1.5081 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
  1.5082 -      ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
  1.5083 -    }
  1.5084 -  }
  1.5085 -
  1.5086 -  error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
  1.5087 -  ucvector_cleanup(&tRNS);
  1.5088 -
  1.5089 -  return error;
  1.5090 -}
  1.5091 -
  1.5092 -static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
  1.5093 -                              LodePNGCompressSettings* zlibsettings) {
  1.5094 -  ucvector zlibdata;
  1.5095 -  unsigned error = 0;
  1.5096 -
  1.5097 -  /*compress with the Zlib compressor*/
  1.5098 -  ucvector_init(&zlibdata);
  1.5099 -  error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
  1.5100 -  if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
  1.5101 -  ucvector_cleanup(&zlibdata);
  1.5102 -
  1.5103 -  return error;
  1.5104 -}
  1.5105 -
  1.5106 -static unsigned addChunk_IEND(ucvector* out) {
  1.5107 -  unsigned error = 0;
  1.5108 -  error = addChunk(out, "IEND", 0, 0);
  1.5109 -  return error;
  1.5110 -}
  1.5111 -
  1.5112 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5113 -
  1.5114 -static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) {
  1.5115 -  unsigned error = 0;
  1.5116 -  size_t i;
  1.5117 -  ucvector text;
  1.5118 -  ucvector_init(&text);
  1.5119 -  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
  1.5120 -  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  1.5121 -  ucvector_push_back(&text, 0); /*0 termination char*/
  1.5122 -  for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
  1.5123 -  error = addChunk(out, "tEXt", text.data, text.size);
  1.5124 -  ucvector_cleanup(&text);
  1.5125 -
  1.5126 -  return error;
  1.5127 -}
  1.5128 -
  1.5129 -static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
  1.5130 -                              LodePNGCompressSettings* zlibsettings) {
  1.5131 -  unsigned error = 0;
  1.5132 -  ucvector data, compressed;
  1.5133 -  size_t i, textsize = lodepng_strlen(textstring);
  1.5134 -
  1.5135 -  ucvector_init(&data);
  1.5136 -  ucvector_init(&compressed);
  1.5137 -  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
  1.5138 -  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  1.5139 -  ucvector_push_back(&data, 0); /*0 termination char*/
  1.5140 -  ucvector_push_back(&data, 0); /*compression method: 0*/
  1.5141 -
  1.5142 -  error = zlib_compress(&compressed.data, &compressed.size,
  1.5143 -                        (const unsigned char*)textstring, textsize, zlibsettings);
  1.5144 -  if(!error) {
  1.5145 -    for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
  1.5146 -    error = addChunk(out, "zTXt", data.data, data.size);
  1.5147 -  }
  1.5148 -
  1.5149 -  ucvector_cleanup(&compressed);
  1.5150 -  ucvector_cleanup(&data);
  1.5151 -  return error;
  1.5152 -}
  1.5153 -
  1.5154 -static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
  1.5155 -                              const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) {
  1.5156 -  unsigned error = 0;
  1.5157 -  ucvector data;
  1.5158 -  size_t i, textsize = lodepng_strlen(textstring);
  1.5159 -
  1.5160 -  ucvector_init(&data);
  1.5161 -
  1.5162 -  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
  1.5163 -  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  1.5164 -  ucvector_push_back(&data, 0); /*null termination char*/
  1.5165 -  ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
  1.5166 -  ucvector_push_back(&data, 0); /*compression method*/
  1.5167 -  for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
  1.5168 -  ucvector_push_back(&data, 0); /*null termination char*/
  1.5169 -  for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
  1.5170 -  ucvector_push_back(&data, 0); /*null termination char*/
  1.5171 -
  1.5172 -  if(compressed) {
  1.5173 -    ucvector compressed_data;
  1.5174 -    ucvector_init(&compressed_data);
  1.5175 -    error = zlib_compress(&compressed_data.data, &compressed_data.size,
  1.5176 -                          (const unsigned char*)textstring, textsize, zlibsettings);
  1.5177 -    if(!error) {
  1.5178 -      for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
  1.5179 -    }
  1.5180 -    ucvector_cleanup(&compressed_data);
  1.5181 -  } else /*not compressed*/ {
  1.5182 -    for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
  1.5183 -  }
  1.5184 -
  1.5185 -  if(!error) error = addChunk(out, "iTXt", data.data, data.size);
  1.5186 -  ucvector_cleanup(&data);
  1.5187 -  return error;
  1.5188 -}
  1.5189 -
  1.5190 -static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) {
  1.5191 -  unsigned char data[6];
  1.5192 -  size_t size = 0;
  1.5193 -  if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
  1.5194 -    data[0] = (unsigned char)(info->background_r >> 8);
  1.5195 -    data[1] = (unsigned char)(info->background_r & 255);
  1.5196 -    size = 2;
  1.5197 -  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
  1.5198 -    data[0] = (unsigned char)(info->background_r >> 8);
  1.5199 -    data[1] = (unsigned char)(info->background_r & 255);
  1.5200 -    data[2] = (unsigned char)(info->background_g >> 8);
  1.5201 -    data[3] = (unsigned char)(info->background_g & 255);
  1.5202 -    data[4] = (unsigned char)(info->background_b >> 8);
  1.5203 -    data[5] = (unsigned char)(info->background_b & 255);
  1.5204 -    size = 6;
  1.5205 -  } else if(info->color.colortype == LCT_PALETTE) {
  1.5206 -    data[0] =(unsigned char)(info->background_r & 255); /*palette index*/
  1.5207 -    size = 1;
  1.5208 -  }
  1.5209 -  return addChunk(out, "bKGD", data, size);
  1.5210 -}
  1.5211 -
  1.5212 -static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) {
  1.5213 -  unsigned char data[7];
  1.5214 -  data[0] = (unsigned char)(time->year >> 8);
  1.5215 -  data[1] = (unsigned char)(time->year & 255);
  1.5216 -  data[2] = (unsigned char)time->month;
  1.5217 -  data[3] = (unsigned char)time->day;
  1.5218 -  data[4] = (unsigned char)time->hour;
  1.5219 -  data[5] = (unsigned char)time->minute;
  1.5220 -  data[6] = (unsigned char)time->second;
  1.5221 -  return addChunk(out, "tIME", data, sizeof(data));
  1.5222 -}
  1.5223 -
  1.5224 -static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) {
  1.5225 -  unsigned char data[9];
  1.5226 -  lodepng_set32bitInt(data + 0, info->phys_x);
  1.5227 -  lodepng_set32bitInt(data + 4, info->phys_y);  data[8] = info->phys_unit;
  1.5228 -  return addChunk(out, "pHYs", data, sizeof(data));
  1.5229 -}
  1.5230 -
  1.5231 -static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) {
  1.5232 -  unsigned char data[4];
  1.5233 -  lodepng_set32bitInt(data, info->gama_gamma);
  1.5234 -  return addChunk(out, "gAMA", data, sizeof(data));
  1.5235 -}
  1.5236 -
  1.5237 -static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) {
  1.5238 -  unsigned char data[32];
  1.5239 -  lodepng_set32bitInt(data + 0, info->chrm_white_x);
  1.5240 -  lodepng_set32bitInt(data + 4, info->chrm_white_y);
  1.5241 -  lodepng_set32bitInt(data + 8, info->chrm_red_x);
  1.5242 -  lodepng_set32bitInt(data + 12, info->chrm_red_y);
  1.5243 -  lodepng_set32bitInt(data + 16, info->chrm_green_x);
  1.5244 -  lodepng_set32bitInt(data + 20, info->chrm_green_y);
  1.5245 -  lodepng_set32bitInt(data + 24, info->chrm_blue_x);
  1.5246 -  lodepng_set32bitInt(data + 28, info->chrm_blue_y);
  1.5247 -  return addChunk(out, "cHRM", data, sizeof(data));
  1.5248 -}
  1.5249 -
  1.5250 -static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) {
  1.5251 -  unsigned char data = info->srgb_intent;
  1.5252 -  return addChunk(out, "sRGB", &data, 1);
  1.5253 -}
  1.5254 -
  1.5255 -static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) {
  1.5256 -  unsigned error = 0;
  1.5257 -  ucvector data, compressed;
  1.5258 -  size_t i;
  1.5259 -
  1.5260 -  ucvector_init(&data);
  1.5261 -  ucvector_init(&compressed);
  1.5262 -  for(i = 0; info->iccp_name[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)info->iccp_name[i]);
  1.5263 -  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  1.5264 -  ucvector_push_back(&data, 0); /*0 termination char*/
  1.5265 -  ucvector_push_back(&data, 0); /*compression method: 0*/
  1.5266 -
  1.5267 -  error = zlib_compress(&compressed.data, &compressed.size,
  1.5268 -                        info->iccp_profile, info->iccp_profile_size, zlibsettings);
  1.5269 -  if(!error) {
  1.5270 -    for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
  1.5271 -    error = addChunk(out, "iCCP", data.data, data.size);
  1.5272 -  }
  1.5273 -
  1.5274 -  ucvector_cleanup(&compressed);
  1.5275 -  ucvector_cleanup(&data);
  1.5276 -  return error;
  1.5277 -}
  1.5278 -
  1.5279 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5280 -
  1.5281 -static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
  1.5282 -                           size_t length, size_t bytewidth, unsigned char filterType) {
  1.5283 -  size_t i;
  1.5284 -  switch(filterType) {
  1.5285 -    case 0: /*None*/
  1.5286 -      for(i = 0; i != length; ++i) out[i] = scanline[i];
  1.5287 -      break;
  1.5288 -    case 1: /*Sub*/
  1.5289 -      for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  1.5290 -      for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
  1.5291 -      break;
  1.5292 -    case 2: /*Up*/
  1.5293 -      if(prevline) {
  1.5294 -        for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
  1.5295 -      } else {
  1.5296 -        for(i = 0; i != length; ++i) out[i] = scanline[i];
  1.5297 -      }
  1.5298 -      break;
  1.5299 -    case 3: /*Average*/
  1.5300 -      if(prevline) {
  1.5301 -        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
  1.5302 -        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
  1.5303 -      } else {
  1.5304 -        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  1.5305 -        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
  1.5306 -      }
  1.5307 -      break;
  1.5308 -    case 4: /*Paeth*/
  1.5309 -      if(prevline) {
  1.5310 -        /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
  1.5311 -        for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
  1.5312 -        for(i = bytewidth; i < length; ++i) {
  1.5313 -          out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
  1.5314 -        }
  1.5315 -      } else {
  1.5316 -        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  1.5317 -        /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
  1.5318 -        for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
  1.5319 -      }
  1.5320 -      break;
  1.5321 -    default: return; /*nonexistent filter type given*/
  1.5322 -  }
  1.5323 -}
  1.5324 -
  1.5325 -/* integer binary logarithm */
  1.5326 -static size_t ilog2(size_t i) {
  1.5327 -  size_t result = 0;
  1.5328 -  while(i >= 65536) { result += 16; i >>= 16; }
  1.5329 -  while(i >= 256) { result += 8; i >>= 8; }
  1.5330 -  while(i >= 16) { result += 4; i >>= 4; }
  1.5331 -  while(i >= 2) { result += 1; i >>= 1; }
  1.5332 -  return result;
  1.5333 -}
  1.5334 -
  1.5335 -static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
  1.5336 -                       const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) {
  1.5337 -  /*
  1.5338 -  For PNG filter method 0
  1.5339 -  out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are
  1.5340 -  the scanlines with 1 extra byte per scanline
  1.5341 -  */
  1.5342 -
  1.5343 -  unsigned bpp = lodepng_get_bpp(info);
  1.5344 -  /*the width of a scanline in bytes, not including the filter type*/
  1.5345 -  size_t linebytes = (w * bpp + 7u) / 8u;
  1.5346 -  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
  1.5347 -  size_t bytewidth = (bpp + 7u) / 8u;
  1.5348 -  const unsigned char* prevline = 0;
  1.5349 -  unsigned x, y;
  1.5350 -  unsigned error = 0;
  1.5351 -  LodePNGFilterStrategy strategy = settings->filter_strategy;
  1.5352 -
  1.5353 -  /*
  1.5354 -  There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
  1.5355 -   *  If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
  1.5356 -      use fixed filtering, with the filter None).
  1.5357 -   * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
  1.5358 -     not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
  1.5359 -     all five filters and select the filter that produces the smallest sum of absolute values per row.
  1.5360 -  This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
  1.5361 -
  1.5362 -  If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
  1.5363 -  but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
  1.5364 -  heuristic is used.
  1.5365 -  */
  1.5366 -  if(settings->filter_palette_zero &&
  1.5367 -     (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
  1.5368 -
  1.5369 -  if(bpp == 0) return 31; /*error: invalid color type*/
  1.5370 -
  1.5371 -  if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) {
  1.5372 -    unsigned char type = (unsigned char)strategy;
  1.5373 -    for(y = 0; y != h; ++y) {
  1.5374 -      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  1.5375 -      size_t inindex = linebytes * y;
  1.5376 -      out[outindex] = type; /*filter type byte*/
  1.5377 -      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
  1.5378 -      prevline = &in[inindex];
  1.5379 -    }
  1.5380 -  } else if(strategy == LFS_MINSUM) {
  1.5381 -    /*adaptive filtering*/
  1.5382 -    size_t sum[5];
  1.5383 -    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  1.5384 -    size_t smallest = 0;
  1.5385 -    unsigned char type, bestType = 0;
  1.5386 -
  1.5387 -    for(type = 0; type != 5; ++type) {
  1.5388 -      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  1.5389 -      if(!attempt[type]) return 83; /*alloc fail*/
  1.5390 -    }
  1.5391 -
  1.5392 -    if(!error) {
  1.5393 -      for(y = 0; y != h; ++y) {
  1.5394 -        /*try the 5 filter types*/
  1.5395 -        for(type = 0; type != 5; ++type) {
  1.5396 -          filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  1.5397 -
  1.5398 -          /*calculate the sum of the result*/
  1.5399 -          sum[type] = 0;
  1.5400 -          if(type == 0) {
  1.5401 -            for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]);
  1.5402 -          } else {
  1.5403 -            for(x = 0; x != linebytes; ++x) {
  1.5404 -              /*For differences, each byte should be treated as signed, values above 127 are negative
  1.5405 -              (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
  1.5406 -              This means filtertype 0 is almost never chosen, but that is justified.*/
  1.5407 -              unsigned char s = attempt[type][x];
  1.5408 -              sum[type] += s < 128 ? s : (255U - s);
  1.5409 -            }
  1.5410 -          }
  1.5411 -
  1.5412 -          /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
  1.5413 -          if(type == 0 || sum[type] < smallest) {
  1.5414 -            bestType = type;
  1.5415 -            smallest = sum[type];
  1.5416 -          }
  1.5417 -        }
  1.5418 -
  1.5419 -        prevline = &in[y * linebytes];
  1.5420 -
  1.5421 -        /*now fill the out values*/
  1.5422 -        out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  1.5423 -        for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  1.5424 -      }
  1.5425 -    }
  1.5426 -
  1.5427 -    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  1.5428 -  } else if(strategy == LFS_ENTROPY) {
  1.5429 -    size_t sum[5];
  1.5430 -    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  1.5431 -    size_t bestSum = 0;
  1.5432 -    unsigned type, bestType = 0;
  1.5433 -    unsigned count[256];
  1.5434 -
  1.5435 -    for(type = 0; type != 5; ++type) {
  1.5436 -      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  1.5437 -      if(!attempt[type]) return 83; /*alloc fail*/
  1.5438 -    }
  1.5439 -
  1.5440 -    for(y = 0; y != h; ++y) {
  1.5441 -      /*try the 5 filter types*/
  1.5442 -      for(type = 0; type != 5; ++type) {
  1.5443 -        filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  1.5444 -        for(x = 0; x != 256; ++x) count[x] = 0;
  1.5445 -        for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
  1.5446 -        ++count[type]; /*the filter type itself is part of the scanline*/
  1.5447 -        sum[type] = 0;
  1.5448 -        for(x = 0; x != 256; ++x) {
  1.5449 -          sum[type] += count[x] == 0 ? 0 : ilog2(count[x]) * count[x];
  1.5450 -        }
  1.5451 -        /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
  1.5452 -        if(type == 0 || sum[type] > bestSum) {
  1.5453 -          bestType = type;
  1.5454 -          bestSum = sum[type];
  1.5455 -        }
  1.5456 -      }
  1.5457 -
  1.5458 -      prevline = &in[y * linebytes];
  1.5459 -
  1.5460 -      /*now fill the out values*/
  1.5461 -      out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  1.5462 -      for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  1.5463 -    }
  1.5464 -
  1.5465 -    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  1.5466 -  } else if(strategy == LFS_PREDEFINED) {
  1.5467 -    for(y = 0; y != h; ++y) {
  1.5468 -      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  1.5469 -      size_t inindex = linebytes * y;
  1.5470 -      unsigned char type = settings->predefined_filters[y];
  1.5471 -      out[outindex] = type; /*filter type byte*/
  1.5472 -      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
  1.5473 -      prevline = &in[inindex];
  1.5474 -    }
  1.5475 -  } else if(strategy == LFS_BRUTE_FORCE) {
  1.5476 -    /*brute force filter chooser.
  1.5477 -    deflate the scanline after every filter attempt to see which one deflates best.
  1.5478 -    This is very slow and gives only slightly smaller, sometimes even larger, result*/
  1.5479 -    size_t size[5];
  1.5480 -    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  1.5481 -    size_t smallest = 0;
  1.5482 -    unsigned type = 0, bestType = 0;
  1.5483 -    unsigned char* dummy;
  1.5484 -    LodePNGCompressSettings zlibsettings = settings->zlibsettings;
  1.5485 -    /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
  1.5486 -    to simulate the true case where the tree is the same for the whole image. Sometimes it gives
  1.5487 -    better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
  1.5488 -    cases better compression. It does make this a bit less slow, so it's worth doing this.*/
  1.5489 -    zlibsettings.btype = 1;
  1.5490 -    /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
  1.5491 -    images only, so disable it*/
  1.5492 -    zlibsettings.custom_zlib = 0;
  1.5493 -    zlibsettings.custom_deflate = 0;
  1.5494 -    for(type = 0; type != 5; ++type) {
  1.5495 -      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  1.5496 -      if(!attempt[type]) return 83; /*alloc fail*/
  1.5497 -    }
  1.5498 -    for(y = 0; y != h; ++y) /*try the 5 filter types*/ {
  1.5499 -      for(type = 0; type != 5; ++type) {
  1.5500 -        unsigned testsize = (unsigned)linebytes;
  1.5501 -        /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
  1.5502 -
  1.5503 -        filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  1.5504 -        size[type] = 0;
  1.5505 -        dummy = 0;
  1.5506 -        zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
  1.5507 -        lodepng_free(dummy);
  1.5508 -        /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
  1.5509 -        if(type == 0 || size[type] < smallest) {
  1.5510 -          bestType = type;
  1.5511 -          smallest = size[type];
  1.5512 -        }
  1.5513 -      }
  1.5514 -      prevline = &in[y * linebytes];
  1.5515 -      out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  1.5516 -      for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  1.5517 -    }
  1.5518 -    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  1.5519 -  }
  1.5520 -  else return 88; /* unknown filter strategy */
  1.5521 -
  1.5522 -  return error;
  1.5523 -}
  1.5524 -
  1.5525 -static void addPaddingBits(unsigned char* out, const unsigned char* in,
  1.5526 -                           size_t olinebits, size_t ilinebits, unsigned h) {
  1.5527 -  /*The opposite of the removePaddingBits function
  1.5528 -  olinebits must be >= ilinebits*/
  1.5529 -  unsigned y;
  1.5530 -  size_t diff = olinebits - ilinebits;
  1.5531 -  size_t obp = 0, ibp = 0; /*bit pointers*/
  1.5532 -  for(y = 0; y != h; ++y) {
  1.5533 -    size_t x;
  1.5534 -    for(x = 0; x < ilinebits; ++x) {
  1.5535 -      unsigned char bit = readBitFromReversedStream(&ibp, in);
  1.5536 -      setBitOfReversedStream(&obp, out, bit);
  1.5537 -    }
  1.5538 -    /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
  1.5539 -    "Use of uninitialised value of size ###" warning from valgrind*/
  1.5540 -    for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
  1.5541 -  }
  1.5542 -}
  1.5543 -
  1.5544 -/*
  1.5545 -in: non-interlaced image with size w*h
  1.5546 -out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
  1.5547 - no padding bits between scanlines, but between reduced images so that each
  1.5548 - reduced image starts at a byte.
  1.5549 -bpp: bits per pixel
  1.5550 -there are no padding bits, not between scanlines, not between reduced images
  1.5551 -in has the following size in bits: w * h * bpp.
  1.5552 -out is possibly bigger due to padding bits between reduced images
  1.5553 -NOTE: comments about padding bits are only relevant if bpp < 8
  1.5554 -*/
  1.5555 -static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  1.5556 -  unsigned passw[7], passh[7];
  1.5557 -  size_t filter_passstart[8], padded_passstart[8], passstart[8];
  1.5558 -  unsigned i;
  1.5559 -
  1.5560 -  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  1.5561 -
  1.5562 -  if(bpp >= 8) {
  1.5563 -    for(i = 0; i != 7; ++i) {
  1.5564 -      unsigned x, y, b;
  1.5565 -      size_t bytewidth = bpp / 8u;
  1.5566 -      for(y = 0; y < passh[i]; ++y)
  1.5567 -      for(x = 0; x < passw[i]; ++x) {
  1.5568 -        size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
  1.5569 -        size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
  1.5570 -        for(b = 0; b < bytewidth; ++b) {
  1.5571 -          out[pixeloutstart + b] = in[pixelinstart + b];
  1.5572 -        }
  1.5573 -      }
  1.5574 -    }
  1.5575 -  } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
  1.5576 -    for(i = 0; i != 7; ++i) {
  1.5577 -      unsigned x, y, b;
  1.5578 -      unsigned ilinebits = bpp * passw[i];
  1.5579 -      unsigned olinebits = bpp * w;
  1.5580 -      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
  1.5581 -      for(y = 0; y < passh[i]; ++y)
  1.5582 -      for(x = 0; x < passw[i]; ++x) {
  1.5583 -        ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
  1.5584 -        obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
  1.5585 -        for(b = 0; b < bpp; ++b) {
  1.5586 -          unsigned char bit = readBitFromReversedStream(&ibp, in);
  1.5587 -          setBitOfReversedStream(&obp, out, bit);
  1.5588 -        }
  1.5589 -      }
  1.5590 -    }
  1.5591 -  }
  1.5592 -}
  1.5593 -
  1.5594 -/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
  1.5595 -return value is error**/
  1.5596 -static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
  1.5597 -                                    unsigned w, unsigned h,
  1.5598 -                                    const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) {
  1.5599 -  /*
  1.5600 -  This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
  1.5601 -  *) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter
  1.5602 -  *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
  1.5603 -  */
  1.5604 -  unsigned bpp = lodepng_get_bpp(&info_png->color);
  1.5605 -  unsigned error = 0;
  1.5606 -
  1.5607 -  if(info_png->interlace_method == 0) {
  1.5608 -    *outsize = h + (h * ((w * bpp + 7u) / 8u)); /*image size plus an extra byte per scanline + possible padding bits*/
  1.5609 -    *out = (unsigned char*)lodepng_malloc(*outsize);
  1.5610 -    if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
  1.5611 -
  1.5612 -    if(!error) {
  1.5613 -      /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
  1.5614 -      if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
  1.5615 -        unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u));
  1.5616 -        if(!padded) error = 83; /*alloc fail*/
  1.5617 -        if(!error) {
  1.5618 -          addPaddingBits(padded, in, ((w * bpp + 7u) / 8u) * 8u, w * bpp, h);
  1.5619 -          error = filter(*out, padded, w, h, &info_png->color, settings);
  1.5620 -        }
  1.5621 -        lodepng_free(padded);
  1.5622 -      } else {
  1.5623 -        /*we can immediately filter into the out buffer, no other steps needed*/
  1.5624 -        error = filter(*out, in, w, h, &info_png->color, settings);
  1.5625 -      }
  1.5626 -    }
  1.5627 -  } else /*interlace_method is 1 (Adam7)*/ {
  1.5628 -    unsigned passw[7], passh[7];
  1.5629 -    size_t filter_passstart[8], padded_passstart[8], passstart[8];
  1.5630 -    unsigned char* adam7;
  1.5631 -
  1.5632 -    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  1.5633 -
  1.5634 -    *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
  1.5635 -    *out = (unsigned char*)lodepng_malloc(*outsize);
  1.5636 -    if(!(*out)) error = 83; /*alloc fail*/
  1.5637 -
  1.5638 -    adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
  1.5639 -    if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
  1.5640 -
  1.5641 -    if(!error) {
  1.5642 -      unsigned i;
  1.5643 -
  1.5644 -      Adam7_interlace(adam7, in, w, h, bpp);
  1.5645 -      for(i = 0; i != 7; ++i) {
  1.5646 -        if(bpp < 8) {
  1.5647 -          unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
  1.5648 -          if(!padded) ERROR_BREAK(83); /*alloc fail*/
  1.5649 -          addPaddingBits(padded, &adam7[passstart[i]],
  1.5650 -                         ((passw[i] * bpp + 7u) / 8u) * 8u, passw[i] * bpp, passh[i]);
  1.5651 -          error = filter(&(*out)[filter_passstart[i]], padded,
  1.5652 -                         passw[i], passh[i], &info_png->color, settings);
  1.5653 -          lodepng_free(padded);
  1.5654 -        } else {
  1.5655 -          error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
  1.5656 -                         passw[i], passh[i], &info_png->color, settings);
  1.5657 -        }
  1.5658 -
  1.5659 -        if(error) break;
  1.5660 -      }
  1.5661 -    }
  1.5662 -
  1.5663 -    lodepng_free(adam7);
  1.5664 -  }
  1.5665 -
  1.5666 -  return error;
  1.5667 -}
  1.5668 -
  1.5669 -/*
  1.5670 -palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
  1.5671 -returns 0 if the palette is opaque,
  1.5672 -returns 1 if the palette has a single color with alpha 0 ==> color key
  1.5673 -returns 2 if the palette is semi-translucent.
  1.5674 -*/
  1.5675 -static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) {
  1.5676 -  size_t i;
  1.5677 -  unsigned key = 0;
  1.5678 -  unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
  1.5679 -  for(i = 0; i != palettesize; ++i) {
  1.5680 -    if(!key && palette[4 * i + 3] == 0) {
  1.5681 -      r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
  1.5682 -      key = 1;
  1.5683 -      i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
  1.5684 -    }
  1.5685 -    else if(palette[4 * i + 3] != 255) return 2;
  1.5686 -    /*when key, no opaque RGB may have key's RGB*/
  1.5687 -    else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
  1.5688 -  }
  1.5689 -  return key;
  1.5690 -}
  1.5691 -
  1.5692 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5693 -static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) {
  1.5694 -  unsigned char* inchunk = data;
  1.5695 -  while((size_t)(inchunk - data) < datasize) {
  1.5696 -    CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
  1.5697 -    out->allocsize = out->size; /*fix the allocsize again*/
  1.5698 -    inchunk = lodepng_chunk_next(inchunk);
  1.5699 -  }
  1.5700 -  return 0;
  1.5701 -}
  1.5702 -
  1.5703 -static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) {
  1.5704 -  /*
  1.5705 -  It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19
  1.5706 -  are "RGB ". We do not perform any full parsing of the ICC profile here, other
  1.5707 -  than check those 4 bytes to grayscale profile. Other than that, validity of
  1.5708 -  the profile is not checked. This is needed only because the PNG specification
  1.5709 -  requires using a non-gray color model if there is an ICC profile with "RGB "
  1.5710 -  (sadly limiting compression opportunities if the input data is grayscale RGB
  1.5711 -  data), and requires using a gray color model if it is "GRAY".
  1.5712 -  */
  1.5713 -  if(size < 20) return 0;
  1.5714 -  return profile[16] == 'G' &&  profile[17] == 'R' &&  profile[18] == 'A' &&  profile[19] == 'Y';
  1.5715 -}
  1.5716 -
  1.5717 -static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) {
  1.5718 -  /* See comment in isGrayICCProfile*/
  1.5719 -  if(size < 20) return 0;
  1.5720 -  return profile[16] == 'R' &&  profile[17] == 'G' &&  profile[18] == 'B' &&  profile[19] == ' ';
  1.5721 -}
  1.5722 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5723 -
  1.5724 -unsigned lodepng_encode(unsigned char** out, size_t* outsize,
  1.5725 -                        const unsigned char* image, unsigned w, unsigned h,
  1.5726 -                        LodePNGState* state) {
  1.5727 -  unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
  1.5728 -  size_t datasize = 0;
  1.5729 -  ucvector outv;
  1.5730 -  LodePNGInfo info;
  1.5731 -  const LodePNGInfo* info_png = &state->info_png;
  1.5732 -
  1.5733 -  ucvector_init(&outv);
  1.5734 -  lodepng_info_init(&info);
  1.5735 -
  1.5736 -  /*provide some proper output values if error will happen*/
  1.5737 -  *out = 0;
  1.5738 -  *outsize = 0;
  1.5739 -  state->error = 0;
  1.5740 -
  1.5741 -  /*check input values validity*/
  1.5742 -  if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette)
  1.5743 -      && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) {
  1.5744 -    state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
  1.5745 -    goto cleanup;
  1.5746 -  }
  1.5747 -  if(state->encoder.zlibsettings.btype > 2) {
  1.5748 -    state->error = 61; /*error: nonexistent btype*/
  1.5749 -    goto cleanup;
  1.5750 -  }
  1.5751 -  if(info_png->interlace_method > 1) {
  1.5752 -    state->error = 71; /*error: nonexistent interlace mode*/
  1.5753 -    goto cleanup;
  1.5754 -  }
  1.5755 -  state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth);
  1.5756 -  if(state->error) goto cleanup; /*error: nonexistent color type given*/
  1.5757 -  state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
  1.5758 -  if(state->error) goto cleanup; /*error: nonexistent color type given*/
  1.5759 -
  1.5760 -  /* color convert and compute scanline filter types */
  1.5761 -  lodepng_info_copy(&info, &state->info_png);
  1.5762 -  if(state->encoder.auto_convert) {
  1.5763 -    LodePNGColorStats stats;
  1.5764 -    lodepng_color_stats_init(&stats);
  1.5765 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5766 -    if(info_png->iccp_defined &&
  1.5767 -        isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
  1.5768 -      /*the PNG specification does not allow to use palette with a GRAY ICC profile, even
  1.5769 -      if the palette has only gray colors, so disallow it.*/
  1.5770 -      stats.allow_palette = 0;
  1.5771 -    }
  1.5772 -    if(info_png->iccp_defined &&
  1.5773 -        isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
  1.5774 -      /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/
  1.5775 -      stats.allow_greyscale = 0;
  1.5776 -    }
  1.5777 -#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  1.5778 -    lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw);
  1.5779 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5780 -    if(info_png->background_defined) {
  1.5781 -      /*the background chunk's color must be taken into account as well*/
  1.5782 -      unsigned r = 0, g = 0, b = 0;
  1.5783 -      LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);
  1.5784 -      lodepng_convert_rgb(&r, &g, &b, info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color);
  1.5785 -      lodepng_color_stats_add(&stats, r, g, b, 65535);
  1.5786 -    }
  1.5787 -#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  1.5788 -    state->error = auto_choose_color(&info.color, &state->info_raw, &stats);
  1.5789 -    if(state->error) goto cleanup;
  1.5790 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5791 -    /*also convert the background chunk*/
  1.5792 -    if(info_png->background_defined) {
  1.5793 -      if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,
  1.5794 -          info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) {
  1.5795 -        state->error = 104;
  1.5796 -        goto cleanup;
  1.5797 -      }
  1.5798 -    }
  1.5799 -#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  1.5800 -  }
  1.5801 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5802 -  if(info_png->iccp_defined) {
  1.5803 -    unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
  1.5804 -    unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
  1.5805 -    unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;
  1.5806 -    if(!gray_icc && !rgb_icc) {
  1.5807 -      state->error = 100; /* Disallowed profile color type for PNG */
  1.5808 -      goto cleanup;
  1.5809 -    }
  1.5810 -    if(gray_icc != gray_png) {
  1.5811 -      /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa,
  1.5812 -      or in case of auto_convert, it wasn't possible to find appropriate model*/
  1.5813 -      state->error = state->encoder.auto_convert ? 102 : 101;
  1.5814 -      goto cleanup;
  1.5815 -    }
  1.5816 -  }
  1.5817 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5818 -  if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {
  1.5819 -    unsigned char* converted;
  1.5820 -    size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u;
  1.5821 -
  1.5822 -    converted = (unsigned char*)lodepng_malloc(size);
  1.5823 -    if(!converted && size) state->error = 83; /*alloc fail*/
  1.5824 -    if(!state->error) {
  1.5825 -      state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
  1.5826 -    }
  1.5827 -    if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
  1.5828 -    lodepng_free(converted);
  1.5829 -    if(state->error) goto cleanup;
  1.5830 -  }
  1.5831 -  else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
  1.5832 -
  1.5833 -  /* output all PNG chunks */ {
  1.5834 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5835 -    size_t i;
  1.5836 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5837 -    /*write signature and chunks*/
  1.5838 -    writeSignature(&outv);
  1.5839 -    /*IHDR*/
  1.5840 -    addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
  1.5841 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5842 -    /*unknown chunks between IHDR and PLTE*/
  1.5843 -    if(info.unknown_chunks_data[0]) {
  1.5844 -      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
  1.5845 -      if(state->error) goto cleanup;
  1.5846 -    }
  1.5847 -    /*color profile chunks must come before PLTE */
  1.5848 -    if(info.iccp_defined) addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);
  1.5849 -    if(info.srgb_defined) addChunk_sRGB(&outv, &info);
  1.5850 -    if(info.gama_defined) addChunk_gAMA(&outv, &info);
  1.5851 -    if(info.chrm_defined) addChunk_cHRM(&outv, &info);
  1.5852 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5853 -    /*PLTE*/
  1.5854 -    if(info.color.colortype == LCT_PALETTE) {
  1.5855 -      addChunk_PLTE(&outv, &info.color);
  1.5856 -    }
  1.5857 -    if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {
  1.5858 -      addChunk_PLTE(&outv, &info.color);
  1.5859 -    }
  1.5860 -    /*tRNS*/
  1.5861 -    if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) {
  1.5862 -      addChunk_tRNS(&outv, &info.color);
  1.5863 -    }
  1.5864 -    if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) {
  1.5865 -      addChunk_tRNS(&outv, &info.color);
  1.5866 -    }
  1.5867 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5868 -    /*bKGD (must come between PLTE and the IDAt chunks*/
  1.5869 -    if(info.background_defined) {
  1.5870 -      state->error = addChunk_bKGD(&outv, &info);
  1.5871 -      if(state->error) goto cleanup;
  1.5872 -    }
  1.5873 -    /*pHYs (must come before the IDAT chunks)*/
  1.5874 -    if(info.phys_defined) addChunk_pHYs(&outv, &info);
  1.5875 -
  1.5876 -    /*unknown chunks between PLTE and IDAT*/
  1.5877 -    if(info.unknown_chunks_data[1]) {
  1.5878 -      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
  1.5879 -      if(state->error) goto cleanup;
  1.5880 -    }
  1.5881 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5882 -    /*IDAT (multiple IDAT chunks must be consecutive)*/
  1.5883 -    state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
  1.5884 -    if(state->error) goto cleanup;
  1.5885 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.5886 -    /*tIME*/
  1.5887 -    if(info.time_defined) addChunk_tIME(&outv, &info.time);
  1.5888 -    /*tEXt and/or zTXt*/
  1.5889 -    for(i = 0; i != info.text_num; ++i) {
  1.5890 -      if(lodepng_strlen(info.text_keys[i]) > 79) {
  1.5891 -        state->error = 66; /*text chunk too large*/
  1.5892 -        goto cleanup;
  1.5893 -      }
  1.5894 -      if(lodepng_strlen(info.text_keys[i]) < 1) {
  1.5895 -        state->error = 67; /*text chunk too small*/
  1.5896 -        goto cleanup;
  1.5897 -      }
  1.5898 -      if(state->encoder.text_compression) {
  1.5899 -        addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
  1.5900 -      } else {
  1.5901 -        addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
  1.5902 -      }
  1.5903 -    }
  1.5904 -    /*LodePNG version id in text chunk*/
  1.5905 -    if(state->encoder.add_id) {
  1.5906 -      unsigned already_added_id_text = 0;
  1.5907 -      for(i = 0; i != info.text_num; ++i) {
  1.5908 -        const char* k = info.text_keys[i];
  1.5909 -        /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */
  1.5910 -        if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' &&
  1.5911 -           k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') {
  1.5912 -          already_added_id_text = 1;
  1.5913 -          break;
  1.5914 -        }
  1.5915 -      }
  1.5916 -      if(already_added_id_text == 0) {
  1.5917 -        addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
  1.5918 -      }
  1.5919 -    }
  1.5920 -    /*iTXt*/
  1.5921 -    for(i = 0; i != info.itext_num; ++i) {
  1.5922 -      if(lodepng_strlen(info.itext_keys[i]) > 79) {
  1.5923 -        state->error = 66; /*text chunk too large*/
  1.5924 -        goto cleanup;
  1.5925 -      }
  1.5926 -      if(lodepng_strlen(info.itext_keys[i]) < 1) {
  1.5927 -        state->error = 67; /*text chunk too small*/
  1.5928 -        goto cleanup;
  1.5929 -      }
  1.5930 -      addChunk_iTXt(&outv, state->encoder.text_compression,
  1.5931 -                    info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
  1.5932 -                    &state->encoder.zlibsettings);
  1.5933 -    }
  1.5934 -
  1.5935 -    /*unknown chunks between IDAT and IEND*/
  1.5936 -    if(info.unknown_chunks_data[2]) {
  1.5937 -      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
  1.5938 -      if(state->error) goto cleanup;
  1.5939 -    }
  1.5940 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.5941 -    addChunk_IEND(&outv);
  1.5942 -  }
  1.5943 -
  1.5944 -cleanup:
  1.5945 -  lodepng_info_cleanup(&info);
  1.5946 -  lodepng_free(data);
  1.5947 -
  1.5948 -  /*instead of cleaning the vector up, give it to the output*/
  1.5949 -  *out = outv.data;
  1.5950 -  *outsize = outv.size;
  1.5951 -
  1.5952 -  return state->error;
  1.5953 -}
  1.5954 -
  1.5955 -unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
  1.5956 -                               unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
  1.5957 -  unsigned error;
  1.5958 -  LodePNGState state;
  1.5959 -  lodepng_state_init(&state);
  1.5960 -  state.info_raw.colortype = colortype;
  1.5961 -  state.info_raw.bitdepth = bitdepth;
  1.5962 -  state.info_png.color.colortype = colortype;
  1.5963 -  state.info_png.color.bitdepth = bitdepth;
  1.5964 -  lodepng_encode(out, outsize, image, w, h, &state);
  1.5965 -  error = state.error;
  1.5966 -  lodepng_state_cleanup(&state);
  1.5967 -  return error;
  1.5968 -}
  1.5969 -
  1.5970 -unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
  1.5971 -  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
  1.5972 -}
  1.5973 -
  1.5974 -unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
  1.5975 -  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
  1.5976 -}
  1.5977 -
  1.5978 -#ifdef LODEPNG_COMPILE_DISK
  1.5979 -unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
  1.5980 -                             LodePNGColorType colortype, unsigned bitdepth) {
  1.5981 -  unsigned char* buffer;
  1.5982 -  size_t buffersize;
  1.5983 -  unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
  1.5984 -  if(!error) error = lodepng_save_file(buffer, buffersize, filename);
  1.5985 -  lodepng_free(buffer);
  1.5986 -  return error;
  1.5987 -}
  1.5988 -
  1.5989 -unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
  1.5990 -  return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
  1.5991 -}
  1.5992 -
  1.5993 -unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
  1.5994 -  return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
  1.5995 -}
  1.5996 -#endif /*LODEPNG_COMPILE_DISK*/
  1.5997 -
  1.5998 -void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) {
  1.5999 -  lodepng_compress_settings_init(&settings->zlibsettings);
  1.6000 -  settings->filter_palette_zero = 1;
  1.6001 -  settings->filter_strategy = LFS_MINSUM;
  1.6002 -  settings->auto_convert = 1;
  1.6003 -  settings->force_palette = 0;
  1.6004 -  settings->predefined_filters = 0;
  1.6005 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  1.6006 -  settings->add_id = 0;
  1.6007 -  settings->text_compression = 1;
  1.6008 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  1.6009 -}
  1.6010 -
  1.6011 -#endif /*LODEPNG_COMPILE_ENCODER*/
  1.6012 -#endif /*LODEPNG_COMPILE_PNG*/
  1.6013 -
  1.6014 -#ifdef LODEPNG_COMPILE_ERROR_TEXT
  1.6015 -/*
  1.6016 -This returns the description of a numerical error code in English. This is also
  1.6017 -the documentation of all the error codes.
  1.6018 -*/
  1.6019 -const char* lodepng_error_text(unsigned code) {
  1.6020 -  switch(code) {
  1.6021 -    case 0: return "no error, everything went ok";
  1.6022 -    case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
  1.6023 -    case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
  1.6024 -    case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
  1.6025 -    case 13: return "problem while processing dynamic deflate block";
  1.6026 -    case 14: return "problem while processing dynamic deflate block";
  1.6027 -    case 15: return "problem while processing dynamic deflate block";
  1.6028 -    case 16: return "nonexistent code while processing dynamic deflate block";
  1.6029 -    case 17: return "end of out buffer memory reached while inflating";
  1.6030 -    case 18: return "invalid distance code while inflating";
  1.6031 -    case 19: return "end of out buffer memory reached while inflating";
  1.6032 -    case 20: return "invalid deflate block BTYPE encountered while decoding";
  1.6033 -    case 21: return "NLEN is not ones complement of LEN in a deflate block";
  1.6034 -
  1.6035 -    /*end of out buffer memory reached while inflating:
  1.6036 -    This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
  1.6037 -    all the pixels of the image, given the color depth and image dimensions. Something that doesn't
  1.6038 -    happen in a normal, well encoded, PNG image.*/
  1.6039 -    case 22: return "end of out buffer memory reached while inflating";
  1.6040 -    case 23: return "end of in buffer memory reached while inflating";
  1.6041 -    case 24: return "invalid FCHECK in zlib header";
  1.6042 -    case 25: return "invalid compression method in zlib header";
  1.6043 -    case 26: return "FDICT encountered in zlib header while it's not used for PNG";
  1.6044 -    case 27: return "PNG file is smaller than a PNG header";
  1.6045 -    /*Checks the magic file header, the first 8 bytes of the PNG file*/
  1.6046 -    case 28: return "incorrect PNG signature, it's no PNG or corrupted";
  1.6047 -    case 29: return "first chunk is not the header chunk";
  1.6048 -    case 30: return "chunk length too large, chunk broken off at end of file";
  1.6049 -    case 31: return "illegal PNG color type or bpp";
  1.6050 -    case 32: return "illegal PNG compression method";
  1.6051 -    case 33: return "illegal PNG filter method";
  1.6052 -    case 34: return "illegal PNG interlace method";
  1.6053 -    case 35: return "chunk length of a chunk is too large or the chunk too small";
  1.6054 -    case 36: return "illegal PNG filter type encountered";
  1.6055 -    case 37: return "illegal bit depth for this color type given";
  1.6056 -    case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/
  1.6057 -    case 39: return "tRNS chunk before PLTE or has more entries than palette size";
  1.6058 -    case 40: return "tRNS chunk has wrong size for grayscale image";
  1.6059 -    case 41: return "tRNS chunk has wrong size for RGB image";
  1.6060 -    case 42: return "tRNS chunk appeared while it was not allowed for this color type";
  1.6061 -    case 43: return "bKGD chunk has wrong size for palette image";
  1.6062 -    case 44: return "bKGD chunk has wrong size for grayscale image";
  1.6063 -    case 45: return "bKGD chunk has wrong size for RGB image";
  1.6064 -    case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
  1.6065 -    case 49: return "jumped past memory while generating dynamic huffman tree";
  1.6066 -    case 50: return "jumped past memory while generating dynamic huffman tree";
  1.6067 -    case 51: return "jumped past memory while inflating huffman block";
  1.6068 -    case 52: return "jumped past memory while inflating";
  1.6069 -    case 53: return "size of zlib data too small";
  1.6070 -    case 54: return "repeat symbol in tree while there was no value symbol yet";
  1.6071 -    /*jumped past tree while generating huffman tree, this could be when the
  1.6072 -    tree will have more leaves than symbols after generating it out of the
  1.6073 -    given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
  1.6074 -    case 55: return "jumped past tree while generating huffman tree";
  1.6075 -    case 56: return "given output image colortype or bitdepth not supported for color conversion";
  1.6076 -    case 57: return "invalid CRC encountered (checking CRC can be disabled)";
  1.6077 -    case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
  1.6078 -    case 59: return "requested color conversion not supported";
  1.6079 -    case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
  1.6080 -    case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
  1.6081 -    /*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/
  1.6082 -    case 62: return "conversion from color to grayscale not supported";
  1.6083 -    /*(2^31-1)*/
  1.6084 -    case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";
  1.6085 -    /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
  1.6086 -    case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
  1.6087 -    case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
  1.6088 -    case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
  1.6089 -    case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
  1.6090 -    case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
  1.6091 -    case 71: return "nonexistent interlace mode given to encoder (must be 0 or 1)";
  1.6092 -    case 72: return "while decoding, nonexistent compression method encountering in zTXt or iTXt chunk (it must be 0)";
  1.6093 -    case 73: return "invalid tIME chunk size";
  1.6094 -    case 74: return "invalid pHYs chunk size";
  1.6095 -    /*length could be wrong, or data chopped off*/
  1.6096 -    case 75: return "no null termination char found while decoding text chunk";
  1.6097 -    case 76: return "iTXt chunk too short to contain required bytes";
  1.6098 -    case 77: return "integer overflow in buffer size";
  1.6099 -    case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
  1.6100 -    case 79: return "failed to open file for writing";
  1.6101 -    case 80: return "tried creating a tree of 0 symbols";
  1.6102 -    case 81: return "lazy matching at pos 0 is impossible";
  1.6103 -    case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds";
  1.6104 -    case 83: return "memory allocation failed";
  1.6105 -    case 84: return "given image too small to contain all pixels to be encoded";
  1.6106 -    case 86: return "impossible offset in lz77 encoding (internal bug)";
  1.6107 -    case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
  1.6108 -    case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
  1.6109 -    case 89: return "text chunk keyword too short or long: must have size 1-79";
  1.6110 -    /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
  1.6111 -    case 90: return "windowsize must be a power of two";
  1.6112 -    case 91: return "invalid decompressed idat size";
  1.6113 -    case 92: return "integer overflow due to too many pixels";
  1.6114 -    case 93: return "zero width or height is invalid";
  1.6115 -    case 94: return "header chunk must have a size of 13 bytes";
  1.6116 -    case 95: return "integer overflow with combined idat chunk size";
  1.6117 -    case 96: return "invalid gAMA chunk size";
  1.6118 -    case 97: return "invalid cHRM chunk size";
  1.6119 -    case 98: return "invalid sRGB chunk size";
  1.6120 -    case 99: return "invalid sRGB rendering intent";
  1.6121 -    case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";
  1.6122 -    case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";
  1.6123 -    case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";
  1.6124 -    case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";
  1.6125 -    case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)";
  1.6126 -    case 105: return "integer overflow of bitsize";
  1.6127 -    case 106: return "PNG file must have PLTE chunk if color type is palette";
  1.6128 -    case 107: return "color convert from palette mode requested without setting the palette data in it";
  1.6129 -    case 108: return "tried to add more than 256 values to a palette";
  1.6130 -  }
  1.6131 -  return "unknown error code";
  1.6132 -}
  1.6133 -#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
  1.6134 -
  1.6135 -/* ////////////////////////////////////////////////////////////////////////// */
  1.6136 -/* ////////////////////////////////////////////////////////////////////////// */
  1.6137 -/* // C++ Wrapper                                                          // */
  1.6138 -/* ////////////////////////////////////////////////////////////////////////// */
  1.6139 -/* ////////////////////////////////////////////////////////////////////////// */
  1.6140 -
  1.6141 -#ifdef LODEPNG_COMPILE_CPP
  1.6142 -namespace lodepng {
  1.6143 -
  1.6144 -#ifdef LODEPNG_COMPILE_DISK
  1.6145 -unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename) {
  1.6146 -  long size = lodepng_filesize(filename.c_str());
  1.6147 -  if(size < 0) return 78;
  1.6148 -  buffer.resize((size_t)size);
  1.6149 -  return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
  1.6150 -}
  1.6151 -
  1.6152 -/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
  1.6153 -unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename) {
  1.6154 -  return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
  1.6155 -}
  1.6156 -#endif /* LODEPNG_COMPILE_DISK */
  1.6157 -
  1.6158 -#ifdef LODEPNG_COMPILE_ZLIB
  1.6159 -#ifdef LODEPNG_COMPILE_DECODER
  1.6160 -unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  1.6161 -                    const LodePNGDecompressSettings& settings) {
  1.6162 -  unsigned char* buffer = 0;
  1.6163 -  size_t buffersize = 0;
  1.6164 -  unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
  1.6165 -  if(buffer) {
  1.6166 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6167 -    lodepng_free(buffer);
  1.6168 -  }
  1.6169 -  return error;
  1.6170 -}
  1.6171 -
  1.6172 -unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  1.6173 -                    const LodePNGDecompressSettings& settings) {
  1.6174 -  return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
  1.6175 -}
  1.6176 -#endif /* LODEPNG_COMPILE_DECODER */
  1.6177 -
  1.6178 -#ifdef LODEPNG_COMPILE_ENCODER
  1.6179 -unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  1.6180 -                  const LodePNGCompressSettings& settings) {
  1.6181 -  unsigned char* buffer = 0;
  1.6182 -  size_t buffersize = 0;
  1.6183 -  unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
  1.6184 -  if(buffer) {
  1.6185 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6186 -    lodepng_free(buffer);
  1.6187 -  }
  1.6188 -  return error;
  1.6189 -}
  1.6190 -
  1.6191 -unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  1.6192 -                  const LodePNGCompressSettings& settings) {
  1.6193 -  return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
  1.6194 -}
  1.6195 -#endif /* LODEPNG_COMPILE_ENCODER */
  1.6196 -#endif /* LODEPNG_COMPILE_ZLIB */
  1.6197 -
  1.6198 -
  1.6199 -#ifdef LODEPNG_COMPILE_PNG
  1.6200 -
  1.6201 -State::State() {
  1.6202 -  lodepng_state_init(this);
  1.6203 -}
  1.6204 -
  1.6205 -State::State(const State& other) {
  1.6206 -  lodepng_state_init(this);
  1.6207 -  lodepng_state_copy(this, &other);
  1.6208 -}
  1.6209 -
  1.6210 -State::~State() {
  1.6211 -  lodepng_state_cleanup(this);
  1.6212 -}
  1.6213 -
  1.6214 -State& State::operator=(const State& other) {
  1.6215 -  lodepng_state_copy(this, &other);
  1.6216 -  return *this;
  1.6217 -}
  1.6218 -
  1.6219 -#ifdef LODEPNG_COMPILE_DECODER
  1.6220 -
  1.6221 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
  1.6222 -                size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
  1.6223 -  unsigned char* buffer;
  1.6224 -  unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
  1.6225 -  if(buffer && !error) {
  1.6226 -    State state;
  1.6227 -    state.info_raw.colortype = colortype;
  1.6228 -    state.info_raw.bitdepth = bitdepth;
  1.6229 -    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
  1.6230 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6231 -    lodepng_free(buffer);
  1.6232 -  }
  1.6233 -  return error;
  1.6234 -}
  1.6235 -
  1.6236 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  1.6237 -                const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth) {
  1.6238 -  return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
  1.6239 -}
  1.6240 -
  1.6241 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  1.6242 -                State& state,
  1.6243 -                const unsigned char* in, size_t insize) {
  1.6244 -  unsigned char* buffer = NULL;
  1.6245 -  unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
  1.6246 -  if(buffer && !error) {
  1.6247 -    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
  1.6248 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6249 -  }
  1.6250 -  lodepng_free(buffer);
  1.6251 -  return error;
  1.6252 -}
  1.6253 -
  1.6254 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  1.6255 -                State& state,
  1.6256 -                const std::vector<unsigned char>& in) {
  1.6257 -  return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
  1.6258 -}
  1.6259 -
  1.6260 -#ifdef LODEPNG_COMPILE_DISK
  1.6261 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
  1.6262 -                LodePNGColorType colortype, unsigned bitdepth) {
  1.6263 -  std::vector<unsigned char> buffer;
  1.6264 -  /* safe output values in case error happens */
  1.6265 -  w = h = 0;
  1.6266 -  unsigned error = load_file(buffer, filename);
  1.6267 -  if(error) return error;
  1.6268 -  return decode(out, w, h, buffer, colortype, bitdepth);
  1.6269 -}
  1.6270 -#endif /* LODEPNG_COMPILE_DECODER */
  1.6271 -#endif /* LODEPNG_COMPILE_DISK */
  1.6272 -
  1.6273 -#ifdef LODEPNG_COMPILE_ENCODER
  1.6274 -unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
  1.6275 -                LodePNGColorType colortype, unsigned bitdepth) {
  1.6276 -  unsigned char* buffer;
  1.6277 -  size_t buffersize;
  1.6278 -  unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
  1.6279 -  if(buffer) {
  1.6280 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6281 -    lodepng_free(buffer);
  1.6282 -  }
  1.6283 -  return error;
  1.6284 -}
  1.6285 -
  1.6286 -unsigned encode(std::vector<unsigned char>& out,
  1.6287 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
  1.6288 -                LodePNGColorType colortype, unsigned bitdepth) {
  1.6289 -  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
  1.6290 -  return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
  1.6291 -}
  1.6292 -
  1.6293 -unsigned encode(std::vector<unsigned char>& out,
  1.6294 -                const unsigned char* in, unsigned w, unsigned h,
  1.6295 -                State& state) {
  1.6296 -  unsigned char* buffer;
  1.6297 -  size_t buffersize;
  1.6298 -  unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
  1.6299 -  if(buffer) {
  1.6300 -    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  1.6301 -    lodepng_free(buffer);
  1.6302 -  }
  1.6303 -  return error;
  1.6304 -}
  1.6305 -
  1.6306 -unsigned encode(std::vector<unsigned char>& out,
  1.6307 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
  1.6308 -                State& state) {
  1.6309 -  if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
  1.6310 -  return encode(out, in.empty() ? 0 : &in[0], w, h, state);
  1.6311 -}
  1.6312 -
  1.6313 -#ifdef LODEPNG_COMPILE_DISK
  1.6314 -unsigned encode(const std::string& filename,
  1.6315 -                const unsigned char* in, unsigned w, unsigned h,
  1.6316 -                LodePNGColorType colortype, unsigned bitdepth) {
  1.6317 -  std::vector<unsigned char> buffer;
  1.6318 -  unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
  1.6319 -  if(!error) error = save_file(buffer, filename);
  1.6320 -  return error;
  1.6321 -}
  1.6322 -
  1.6323 -unsigned encode(const std::string& filename,
  1.6324 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
  1.6325 -                LodePNGColorType colortype, unsigned bitdepth) {
  1.6326 -  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
  1.6327 -  return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
  1.6328 -}
  1.6329 -#endif /* LODEPNG_COMPILE_DISK */
  1.6330 -#endif /* LODEPNG_COMPILE_ENCODER */
  1.6331 -#endif /* LODEPNG_COMPILE_PNG */
  1.6332 -} /* namespace lodepng */
  1.6333 -#endif /*LODEPNG_COMPILE_CPP*/
     2.1 --- a/external/lodepng/lodepng.h	Wed Nov 06 10:01:02 2019 +0300
     2.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.3 @@ -1,1955 +0,0 @@
     2.4 -/*
     2.5 -LodePNG version 20191020
     2.6 -
     2.7 -Copyright (c) 2005-2019 Lode Vandevenne
     2.8 -
     2.9 -This software is provided 'as-is', without any express or implied
    2.10 -warranty. In no event will the authors be held liable for any damages
    2.11 -arising from the use of this software.
    2.12 -
    2.13 -Permission is granted to anyone to use this software for any purpose,
    2.14 -including commercial applications, and to alter it and redistribute it
    2.15 -freely, subject to the following restrictions:
    2.16 -
    2.17 -    1. The origin of this software must not be misrepresented; you must not
    2.18 -    claim that you wrote the original software. If you use this software
    2.19 -    in a product, an acknowledgment in the product documentation would be
    2.20 -    appreciated but is not required.
    2.21 -
    2.22 -    2. Altered source versions must be plainly marked as such, and must not be
    2.23 -    misrepresented as being the original software.
    2.24 -
    2.25 -    3. This notice may not be removed or altered from any source
    2.26 -    distribution.
    2.27 -*/
    2.28 -
    2.29 -#ifndef LODEPNG_H
    2.30 -#define LODEPNG_H
    2.31 -
    2.32 -#include <string.h> /*for size_t*/
    2.33 -
    2.34 -extern const char* LODEPNG_VERSION_STRING;
    2.35 -
    2.36 -/*
    2.37 -The following #defines are used to create code sections. They can be disabled
    2.38 -to disable code sections, which can give faster compile time and smaller binary.
    2.39 -The "NO_COMPILE" defines are designed to be used to pass as defines to the
    2.40 -compiler command to disable them without modifying this header, e.g.
    2.41 --DLODEPNG_NO_COMPILE_ZLIB for gcc.
    2.42 -In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to
    2.43 -allow implementing a custom lodepng_crc32.
    2.44 -*/
    2.45 -/*deflate & zlib. If disabled, you must specify alternative zlib functions in
    2.46 -the custom_zlib field of the compress and decompress settings*/
    2.47 -#ifndef LODEPNG_NO_COMPILE_ZLIB
    2.48 -#define LODEPNG_COMPILE_ZLIB
    2.49 -#endif
    2.50 -
    2.51 -/*png encoder and png decoder*/
    2.52 -#ifndef LODEPNG_NO_COMPILE_PNG
    2.53 -#define LODEPNG_COMPILE_PNG
    2.54 -#endif
    2.55 -
    2.56 -/*deflate&zlib decoder and png decoder*/
    2.57 -#ifndef LODEPNG_NO_COMPILE_DECODER
    2.58 -#define LODEPNG_COMPILE_DECODER
    2.59 -#endif
    2.60 -
    2.61 -/*deflate&zlib encoder and png encoder*/
    2.62 -#ifndef LODEPNG_NO_COMPILE_ENCODER
    2.63 -#define LODEPNG_COMPILE_ENCODER
    2.64 -#endif
    2.65 -
    2.66 -/*the optional built in harddisk file loading and saving functions*/
    2.67 -#ifndef LODEPNG_NO_COMPILE_DISK
    2.68 -#define LODEPNG_COMPILE_DISK
    2.69 -#endif
    2.70 -
    2.71 -/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/
    2.72 -#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
    2.73 -#define LODEPNG_COMPILE_ANCILLARY_CHUNKS
    2.74 -#endif
    2.75 -
    2.76 -/*ability to convert error numerical codes to English text string*/
    2.77 -#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT
    2.78 -#define LODEPNG_COMPILE_ERROR_TEXT
    2.79 -#endif
    2.80 -
    2.81 -/*Compile the default allocators (C's free, malloc and realloc). If you disable this,
    2.82 -you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your
    2.83 -source files with custom allocators.*/
    2.84 -#ifndef LODEPNG_NO_COMPILE_ALLOCATORS
    2.85 -#define LODEPNG_COMPILE_ALLOCATORS
    2.86 -#endif
    2.87 -
    2.88 -/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/
    2.89 -#ifdef __cplusplus
    2.90 -#ifndef LODEPNG_NO_COMPILE_CPP
    2.91 -#define LODEPNG_COMPILE_CPP
    2.92 -#endif
    2.93 -#endif
    2.94 -
    2.95 -#ifdef LODEPNG_COMPILE_CPP
    2.96 -#include <vector>
    2.97 -#include <string>
    2.98 -#endif /*LODEPNG_COMPILE_CPP*/
    2.99 -
   2.100 -#ifdef LODEPNG_COMPILE_PNG
   2.101 -/*The PNG color types (also used for raw image).*/
   2.102 -typedef enum LodePNGColorType {
   2.103 -  LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/
   2.104 -  LCT_RGB = 2, /*RGB: 8,16 bit*/
   2.105 -  LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/
   2.106 -  LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/
   2.107 -  LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/
   2.108 -  /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid
   2.109 -  byte value from 0 to 255 that could be present in an invalid PNG file header. Do
   2.110 -  not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use
   2.111 -  the valid color type names above, or numeric values like 1 or 7 when checking for
   2.112 -  particular disallowed color type byte values, or cast to integer to print it.*/
   2.113 -  LCT_MAX_OCTET_VALUE = 255
   2.114 -} LodePNGColorType;
   2.115 -
   2.116 -#ifdef LODEPNG_COMPILE_DECODER
   2.117 -/*
   2.118 -Converts PNG data in memory to raw pixel data.
   2.119 -out: Output parameter. Pointer to buffer that will contain the raw pixel data.
   2.120 -     After decoding, its size is w * h * (bytes per pixel) bytes larger than
   2.121 -     initially. Bytes per pixel depends on colortype and bitdepth.
   2.122 -     Must be freed after usage with free(*out).
   2.123 -     Note: for 16-bit per channel colors, uses big endian format like PNG does.
   2.124 -w: Output parameter. Pointer to width of pixel data.
   2.125 -h: Output parameter. Pointer to height of pixel data.
   2.126 -in: Memory buffer with the PNG file.
   2.127 -insize: size of the in buffer.
   2.128 -colortype: the desired color type for the raw output image. See explanation on PNG color types.
   2.129 -bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
   2.130 -Return value: LodePNG error code (0 means no error).
   2.131 -*/
   2.132 -unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,
   2.133 -                               const unsigned char* in, size_t insize,
   2.134 -                               LodePNGColorType colortype, unsigned bitdepth);
   2.135 -
   2.136 -/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
   2.137 -unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,
   2.138 -                          const unsigned char* in, size_t insize);
   2.139 -
   2.140 -/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
   2.141 -unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,
   2.142 -                          const unsigned char* in, size_t insize);
   2.143 -
   2.144 -#ifdef LODEPNG_COMPILE_DISK
   2.145 -/*
   2.146 -Load PNG from disk, from file with given name.
   2.147 -Same as the other decode functions, but instead takes a filename as input.
   2.148 -*/
   2.149 -unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,
   2.150 -                             const char* filename,
   2.151 -                             LodePNGColorType colortype, unsigned bitdepth);
   2.152 -
   2.153 -/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
   2.154 -unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,
   2.155 -                               const char* filename);
   2.156 -
   2.157 -/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
   2.158 -unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,
   2.159 -                               const char* filename);
   2.160 -#endif /*LODEPNG_COMPILE_DISK*/
   2.161 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.162 -
   2.163 -
   2.164 -#ifdef LODEPNG_COMPILE_ENCODER
   2.165 -/*
   2.166 -Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
   2.167 -  of the output PNG image cannot be chosen, they are automatically determined
   2.168 -  by the colortype, bitdepth and content of the input pixel data.
   2.169 -  Note: for 16-bit per channel colors, needs big endian format like PNG does.
   2.170 -out: Output parameter. Pointer to buffer that will contain the PNG image data.
   2.171 -     Must be freed after usage with free(*out).
   2.172 -outsize: Output parameter. Pointer to the size in bytes of the out buffer.
   2.173 -image: The raw pixel data to encode. The size of this buffer should be
   2.174 -       w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.
   2.175 -w: width of the raw pixel data in pixels.
   2.176 -h: height of the raw pixel data in pixels.
   2.177 -colortype: the color type of the raw input image. See explanation on PNG color types.
   2.178 -bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
   2.179 -Return value: LodePNG error code (0 means no error).
   2.180 -*/
   2.181 -unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,
   2.182 -                               const unsigned char* image, unsigned w, unsigned h,
   2.183 -                               LodePNGColorType colortype, unsigned bitdepth);
   2.184 -
   2.185 -/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
   2.186 -unsigned lodepng_encode32(unsigned char** out, size_t* outsize,
   2.187 -                          const unsigned char* image, unsigned w, unsigned h);
   2.188 -
   2.189 -/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
   2.190 -unsigned lodepng_encode24(unsigned char** out, size_t* outsize,
   2.191 -                          const unsigned char* image, unsigned w, unsigned h);
   2.192 -
   2.193 -#ifdef LODEPNG_COMPILE_DISK
   2.194 -/*
   2.195 -Converts raw pixel data into a PNG file on disk.
   2.196 -Same as the other encode functions, but instead takes a filename as output.
   2.197 -NOTE: This overwrites existing files without warning!
   2.198 -*/
   2.199 -unsigned lodepng_encode_file(const char* filename,
   2.200 -                             const unsigned char* image, unsigned w, unsigned h,
   2.201 -                             LodePNGColorType colortype, unsigned bitdepth);
   2.202 -
   2.203 -/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
   2.204 -unsigned lodepng_encode32_file(const char* filename,
   2.205 -                               const unsigned char* image, unsigned w, unsigned h);
   2.206 -
   2.207 -/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
   2.208 -unsigned lodepng_encode24_file(const char* filename,
   2.209 -                               const unsigned char* image, unsigned w, unsigned h);
   2.210 -#endif /*LODEPNG_COMPILE_DISK*/
   2.211 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.212 -
   2.213 -
   2.214 -#ifdef LODEPNG_COMPILE_CPP
   2.215 -namespace lodepng {
   2.216 -#ifdef LODEPNG_COMPILE_DECODER
   2.217 -/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype
   2.218 -is the format to output the pixels to. Default is RGBA 8-bit per channel.*/
   2.219 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
   2.220 -                const unsigned char* in, size_t insize,
   2.221 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.222 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
   2.223 -                const std::vector<unsigned char>& in,
   2.224 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.225 -#ifdef LODEPNG_COMPILE_DISK
   2.226 -/*
   2.227 -Converts PNG file from disk to raw pixel data in memory.
   2.228 -Same as the other decode functions, but instead takes a filename as input.
   2.229 -*/
   2.230 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
   2.231 -                const std::string& filename,
   2.232 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.233 -#endif /* LODEPNG_COMPILE_DISK */
   2.234 -#endif /* LODEPNG_COMPILE_DECODER */
   2.235 -
   2.236 -#ifdef LODEPNG_COMPILE_ENCODER
   2.237 -/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
   2.238 -is that of the raw input data. The output PNG color type will be auto chosen.*/
   2.239 -unsigned encode(std::vector<unsigned char>& out,
   2.240 -                const unsigned char* in, unsigned w, unsigned h,
   2.241 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.242 -unsigned encode(std::vector<unsigned char>& out,
   2.243 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
   2.244 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.245 -#ifdef LODEPNG_COMPILE_DISK
   2.246 -/*
   2.247 -Converts 32-bit RGBA raw pixel data into a PNG file on disk.
   2.248 -Same as the other encode functions, but instead takes a filename as output.
   2.249 -NOTE: This overwrites existing files without warning!
   2.250 -*/
   2.251 -unsigned encode(const std::string& filename,
   2.252 -                const unsigned char* in, unsigned w, unsigned h,
   2.253 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.254 -unsigned encode(const std::string& filename,
   2.255 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
   2.256 -                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
   2.257 -#endif /* LODEPNG_COMPILE_DISK */
   2.258 -#endif /* LODEPNG_COMPILE_ENCODER */
   2.259 -} /* namespace lodepng */
   2.260 -#endif /*LODEPNG_COMPILE_CPP*/
   2.261 -#endif /*LODEPNG_COMPILE_PNG*/
   2.262 -
   2.263 -#ifdef LODEPNG_COMPILE_ERROR_TEXT
   2.264 -/*Returns an English description of the numerical error code.*/
   2.265 -const char* lodepng_error_text(unsigned code);
   2.266 -#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
   2.267 -
   2.268 -#ifdef LODEPNG_COMPILE_DECODER
   2.269 -/*Settings for zlib decompression*/
   2.270 -typedef struct LodePNGDecompressSettings LodePNGDecompressSettings;
   2.271 -struct LodePNGDecompressSettings {
   2.272 -  /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */
   2.273 -  unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
   2.274 -  unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/
   2.275 -
   2.276 -  /*use custom zlib decoder instead of built in one (default: null)*/
   2.277 -  unsigned (*custom_zlib)(unsigned char**, size_t*,
   2.278 -                          const unsigned char*, size_t,
   2.279 -                          const LodePNGDecompressSettings*);
   2.280 -  /*use custom deflate decoder instead of built in one (default: null)
   2.281 -  if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate)*/
   2.282 -  unsigned (*custom_inflate)(unsigned char**, size_t*,
   2.283 -                             const unsigned char*, size_t,
   2.284 -                             const LodePNGDecompressSettings*);
   2.285 -
   2.286 -  const void* custom_context; /*optional custom settings for custom functions*/
   2.287 -};
   2.288 -
   2.289 -extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
   2.290 -void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);
   2.291 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.292 -
   2.293 -#ifdef LODEPNG_COMPILE_ENCODER
   2.294 -/*
   2.295 -Settings for zlib compression. Tweaking these settings tweaks the balance
   2.296 -between speed and compression ratio.
   2.297 -*/
   2.298 -typedef struct LodePNGCompressSettings LodePNGCompressSettings;
   2.299 -struct LodePNGCompressSettings /*deflate = compress*/ {
   2.300 -  /*LZ77 related settings*/
   2.301 -  unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/
   2.302 -  unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/
   2.303 -  unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/
   2.304 -  unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/
   2.305 -  unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/
   2.306 -  unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
   2.307 -
   2.308 -  /*use custom zlib encoder instead of built in one (default: null)*/
   2.309 -  unsigned (*custom_zlib)(unsigned char**, size_t*,
   2.310 -                          const unsigned char*, size_t,
   2.311 -                          const LodePNGCompressSettings*);
   2.312 -  /*use custom deflate encoder instead of built in one (default: null)
   2.313 -  if custom_zlib is used, custom_deflate is ignored since only the built in
   2.314 -  zlib function will call custom_deflate*/
   2.315 -  unsigned (*custom_deflate)(unsigned char**, size_t*,
   2.316 -                             const unsigned char*, size_t,
   2.317 -                             const LodePNGCompressSettings*);
   2.318 -
   2.319 -  const void* custom_context; /*optional custom settings for custom functions*/
   2.320 -};
   2.321 -
   2.322 -extern const LodePNGCompressSettings lodepng_default_compress_settings;
   2.323 -void lodepng_compress_settings_init(LodePNGCompressSettings* settings);
   2.324 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.325 -
   2.326 -#ifdef LODEPNG_COMPILE_PNG
   2.327 -/*
   2.328 -Color mode of an image. Contains all information required to decode the pixel
   2.329 -bits to RGBA colors. This information is the same as used in the PNG file
   2.330 -format, and is used both for PNG and raw image data in LodePNG.
   2.331 -*/
   2.332 -typedef struct LodePNGColorMode {
   2.333 -  /*header (IHDR)*/
   2.334 -  LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
   2.335 -  unsigned bitdepth;  /*bits per sample, see PNG standard or documentation further in this header file*/
   2.336 -
   2.337 -  /*
   2.338 -  palette (PLTE and tRNS)
   2.339 -
   2.340 -  Dynamically allocated with the colors of the palette, including alpha.
   2.341 -  This field may not be allocated directly, use lodepng_color_mode_init first,
   2.342 -  then lodepng_palette_add per color to correctly initialize it (to ensure size
   2.343 -  of exactly 1024 bytes).
   2.344 -
   2.345 -  The alpha channels must be set as well, set them to 255 for opaque images.
   2.346 -
   2.347 -  When decoding, by default you can ignore this palette, since LodePNG already
   2.348 -  fills the palette colors in the pixels of the raw RGBA output.
   2.349 -
   2.350 -  The palette is only supported for color type 3.
   2.351 -  */
   2.352 -  unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/
   2.353 -  size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/
   2.354 -
   2.355 -  /*
   2.356 -  transparent color key (tRNS)
   2.357 -
   2.358 -  This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
   2.359 -  For grayscale PNGs, r, g and b will all 3 be set to the same.
   2.360 -
   2.361 -  When decoding, by default you can ignore this information, since LodePNG sets
   2.362 -  pixels with this key to transparent already in the raw RGBA output.
   2.363 -
   2.364 -  The color key is only supported for color types 0 and 2.
   2.365 -  */
   2.366 -  unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
   2.367 -  unsigned key_r;       /*red/grayscale component of color key*/
   2.368 -  unsigned key_g;       /*green component of color key*/
   2.369 -  unsigned key_b;       /*blue component of color key*/
   2.370 -} LodePNGColorMode;
   2.371 -
   2.372 -/*init, cleanup and copy functions to use with this struct*/
   2.373 -void lodepng_color_mode_init(LodePNGColorMode* info);
   2.374 -void lodepng_color_mode_cleanup(LodePNGColorMode* info);
   2.375 -/*return value is error code (0 means no error)*/
   2.376 -unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);
   2.377 -/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */
   2.378 -LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth);
   2.379 -
   2.380 -void lodepng_palette_clear(LodePNGColorMode* info);
   2.381 -/*add 1 color to the palette*/
   2.382 -unsigned lodepng_palette_add(LodePNGColorMode* info,
   2.383 -                             unsigned char r, unsigned char g, unsigned char b, unsigned char a);
   2.384 -
   2.385 -/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
   2.386 -unsigned lodepng_get_bpp(const LodePNGColorMode* info);
   2.387 -/*get the amount of color channels used, based on colortype in the struct.
   2.388 -If a palette is used, it counts as 1 channel.*/
   2.389 -unsigned lodepng_get_channels(const LodePNGColorMode* info);
   2.390 -/*is it a grayscale type? (only colortype 0 or 4)*/
   2.391 -unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);
   2.392 -/*has it got an alpha channel? (only colortype 2 or 6)*/
   2.393 -unsigned lodepng_is_alpha_type(const LodePNGColorMode* info);
   2.394 -/*has it got a palette? (only colortype 3)*/
   2.395 -unsigned lodepng_is_palette_type(const LodePNGColorMode* info);
   2.396 -/*only returns true if there is a palette and there is a value in the palette with alpha < 255.
   2.397 -Loops through the palette to check this.*/
   2.398 -unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);
   2.399 -/*
   2.400 -Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
   2.401 -Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
   2.402 -Returns false if the image can only have opaque pixels.
   2.403 -In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
   2.404 -or if "key_defined" is true.
   2.405 -*/
   2.406 -unsigned lodepng_can_have_alpha(const LodePNGColorMode* info);
   2.407 -/*Returns the byte size of a raw image buffer with given width, height and color mode*/
   2.408 -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);
   2.409 -
   2.410 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   2.411 -/*The information of a Time chunk in PNG.*/
   2.412 -typedef struct LodePNGTime {
   2.413 -  unsigned year;    /*2 bytes used (0-65535)*/
   2.414 -  unsigned month;   /*1-12*/
   2.415 -  unsigned day;     /*1-31*/
   2.416 -  unsigned hour;    /*0-23*/
   2.417 -  unsigned minute;  /*0-59*/
   2.418 -  unsigned second;  /*0-60 (to allow for leap seconds)*/
   2.419 -} LodePNGTime;
   2.420 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   2.421 -
   2.422 -/*Information about the PNG image, except pixels, width and height.*/
   2.423 -typedef struct LodePNGInfo {
   2.424 -  /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
   2.425 -  unsigned compression_method;/*compression method of the original file. Always 0.*/
   2.426 -  unsigned filter_method;     /*filter method of the original file*/
   2.427 -  unsigned interlace_method;  /*interlace method of the original file: 0=none, 1=Adam7*/
   2.428 -  LodePNGColorMode color;     /*color type and bits, palette and transparency of the PNG file*/
   2.429 -
   2.430 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   2.431 -  /*
   2.432 -  Suggested background color chunk (bKGD)
   2.433 -
   2.434 -  This uses the same color mode and bit depth as the PNG (except no alpha channel),
   2.435 -  with values truncated to the bit depth in the unsigned integer.
   2.436 -
   2.437 -  For grayscale and palette PNGs, the value is stored in background_r. The values
   2.438 -  in background_g and background_b are then unused.
   2.439 -
   2.440 -  So when decoding, you may get these in a different color mode than the one you requested
   2.441 -  for the raw pixels.
   2.442 -
   2.443 -  When encoding with auto_convert, you must use the color model defined in info_png.color for
   2.444 -  these values. The encoder normally ignores info_png.color when auto_convert is on, but will
   2.445 -  use it to interpret these values (and convert copies of them to its chosen color model).
   2.446 -
   2.447 -  When encoding, avoid setting this to an expensive color, such as a non-gray value
   2.448 -  when the image is gray, or the compression will be worse since it will be forced to
   2.449 -  write the PNG with a more expensive color mode (when auto_convert is on).
   2.450 -
   2.451 -  The decoder does not use this background color to edit the color of pixels. This is a
   2.452 -  completely optional metadata feature.
   2.453 -  */
   2.454 -  unsigned background_defined; /*is a suggested background color given?*/
   2.455 -  unsigned background_r;       /*red/gray/palette component of suggested background color*/
   2.456 -  unsigned background_g;       /*green component of suggested background color*/
   2.457 -  unsigned background_b;       /*blue component of suggested background color*/
   2.458 -
   2.459 -  /*
   2.460 -  non-international text chunks (tEXt and zTXt)
   2.461 -
   2.462 -  The char** arrays each contain num strings. The actual messages are in
   2.463 -  text_strings, while text_keys are keywords that give a short description what
   2.464 -  the actual text represents, e.g. Title, Author, Description, or anything else.
   2.465 -
   2.466 -  All the string fields below including keys, names and language tags are null terminated.
   2.467 -  The PNG specification uses null characters for the keys, names and tags, and forbids null
   2.468 -  characters to appear in the main text which is why we can use null termination everywhere here.
   2.469 -
   2.470 -  A keyword is minimum 1 character and maximum 79 characters long. It's
   2.471 -  discouraged to use a single line length longer than 79 characters for texts.
   2.472 -
   2.473 -  Don't allocate these text buffers yourself. Use the init/cleanup functions
   2.474 -  correctly and use lodepng_add_text and lodepng_clear_text.
   2.475 -  */
   2.476 -  size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
   2.477 -  char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
   2.478 -  char** text_strings; /*the actual text*/
   2.479 -
   2.480 -  /*
   2.481 -  international text chunks (iTXt)
   2.482 -  Similar to the non-international text chunks, but with additional strings
   2.483 -  "langtags" and "transkeys".
   2.484 -  */
   2.485 -  size_t itext_num; /*the amount of international texts in this PNG*/
   2.486 -  char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
   2.487 -  char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
   2.488 -  char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
   2.489 -  char** itext_strings; /*the actual international text - UTF-8 string*/
   2.490 -
   2.491 -  /*time chunk (tIME)*/
   2.492 -  unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
   2.493 -  LodePNGTime time;
   2.494 -
   2.495 -  /*phys chunk (pHYs)*/
   2.496 -  unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/
   2.497 -  unsigned phys_x; /*pixels per unit in x direction*/
   2.498 -  unsigned phys_y; /*pixels per unit in y direction*/
   2.499 -  unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
   2.500 -
   2.501 -  /*
   2.502 -  Color profile related chunks: gAMA, cHRM, sRGB, iCPP
   2.503 -
   2.504 -  LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color
   2.505 -  profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please
   2.506 -  use these values with a color management library.
   2.507 -
   2.508 -  See the PNG, ICC and sRGB specifications for more information about the meaning of these values.
   2.509 -  */
   2.510 -
   2.511 -  /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */
   2.512 -  unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */
   2.513 -  unsigned gama_gamma;   /* Gamma exponent times 100000 */
   2.514 -
   2.515 -  /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */
   2.516 -  unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */
   2.517 -  unsigned chrm_white_x; /* White Point x times 100000 */
   2.518 -  unsigned chrm_white_y; /* White Point y times 100000 */
   2.519 -  unsigned chrm_red_x;   /* Red x times 100000 */
   2.520 -  unsigned chrm_red_y;   /* Red y times 100000 */
   2.521 -  unsigned chrm_green_x; /* Green x times 100000 */
   2.522 -  unsigned chrm_green_y; /* Green y times 100000 */
   2.523 -  unsigned chrm_blue_x;  /* Blue x times 100000 */
   2.524 -  unsigned chrm_blue_y;  /* Blue y times 100000 */
   2.525 -
   2.526 -  /*
   2.527 -  sRGB chunk: optional. May not appear at the same time as iCCP.
   2.528 -  If gAMA is also present gAMA must contain value 45455.
   2.529 -  If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000.
   2.530 -  */
   2.531 -  unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */
   2.532 -  unsigned srgb_intent;  /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */
   2.533 -
   2.534 -  /*
   2.535 -  iCCP chunk: optional. May not appear at the same time as sRGB.
   2.536 -
   2.537 -  LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a
   2.538 -  separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color
   2.539 -  management and conversions.
   2.540 -
   2.541 -  For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC
   2.542 -  profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and
   2.543 -  enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile.
   2.544 -
   2.545 -  For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray
   2.546 -  PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure
   2.547 -  the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is
   2.548 -  enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder
   2.549 -  error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel
   2.550 -  data if the pixels could be encoded as grayscale but the ICC profile is RGB.
   2.551 -
   2.552 -  To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so
   2.553 -  make sure you compute it carefully to avoid the above problems.
   2.554 -  */
   2.555 -  unsigned iccp_defined;      /* Whether an iCCP chunk is present (0 = not present, 1 = present). */
   2.556 -  char* iccp_name;            /* Null terminated string with profile name, 1-79 bytes */
   2.557 -  /*
   2.558 -  The ICC profile in iccp_profile_size bytes.
   2.559 -  Don't allocate this buffer yourself. Use the init/cleanup functions
   2.560 -  correctly and use lodepng_set_icc and lodepng_clear_icc.
   2.561 -  */
   2.562 -  unsigned char* iccp_profile;
   2.563 -  unsigned iccp_profile_size; /* The size of iccp_profile in bytes */
   2.564 -
   2.565 -  /* End of color profile related chunks */
   2.566 -
   2.567 -
   2.568 -  /*
   2.569 -  unknown chunks: chunks not known by LodePNG, passed on byte for byte.
   2.570 -
   2.571 -  There are 3 buffers, one for each position in the PNG where unknown chunks can appear.
   2.572 -  Each buffer contains all unknown chunks for that position consecutively.
   2.573 -  The 3 positions are:
   2.574 -  0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.
   2.575 -
   2.576 -  For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag
   2.577 -  above in here, since the encoder will blindly follow this and could then encode an invalid PNG file
   2.578 -  (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use
   2.579 -  this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST),
   2.580 -  or any non-standard PNG chunk.
   2.581 -
   2.582 -  Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
   2.583 -  later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
   2.584 -  */
   2.585 -  unsigned char* unknown_chunks_data[3];
   2.586 -  size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
   2.587 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   2.588 -} LodePNGInfo;
   2.589 -
   2.590 -/*init, cleanup and copy functions to use with this struct*/
   2.591 -void lodepng_info_init(LodePNGInfo* info);
   2.592 -void lodepng_info_cleanup(LodePNGInfo* info);
   2.593 -/*return value is error code (0 means no error)*/
   2.594 -unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);
   2.595 -
   2.596 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   2.597 -unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/
   2.598 -void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
   2.599 -
   2.600 -unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
   2.601 -                           const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/
   2.602 -void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/
   2.603 -
   2.604 -/*replaces if exists*/
   2.605 -unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size);
   2.606 -void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
   2.607 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   2.608 -
   2.609 -/*
   2.610 -Converts raw buffer from one color type to another color type, based on
   2.611 -LodePNGColorMode structs to describe the input and output color type.
   2.612 -See the reference manual at the end of this header file to see which color conversions are supported.
   2.613 -return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
   2.614 -The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
   2.615 -of the output color type (lodepng_get_bpp).
   2.616 -For < 8 bpp images, there should not be padding bits at the end of scanlines.
   2.617 -For 16-bit per channel colors, uses big endian format like PNG does.
   2.618 -Return value is LodePNG error code
   2.619 -*/
   2.620 -unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
   2.621 -                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
   2.622 -                         unsigned w, unsigned h);
   2.623 -
   2.624 -#ifdef LODEPNG_COMPILE_DECODER
   2.625 -/*
   2.626 -Settings for the decoder. This contains settings for the PNG and the Zlib
   2.627 -decoder, but not the Info settings from the Info structs.
   2.628 -*/
   2.629 -typedef struct LodePNGDecoderSettings {
   2.630 -  LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
   2.631 -
   2.632 -  /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */
   2.633 -  unsigned ignore_crc; /*ignore CRC checksums*/
   2.634 -  unsigned ignore_critical; /*ignore unknown critical chunks*/
   2.635 -  unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/
   2.636 -  /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable
   2.637 -     errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some
   2.638 -     strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters
   2.639 -     in string keys, etc... */
   2.640 -
   2.641 -  unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
   2.642 -
   2.643 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   2.644 -  unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/
   2.645 -  /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/
   2.646 -  unsigned remember_unknown_chunks;
   2.647 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   2.648 -} LodePNGDecoderSettings;
   2.649 -
   2.650 -void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);
   2.651 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.652 -
   2.653 -#ifdef LODEPNG_COMPILE_ENCODER
   2.654 -/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
   2.655 -typedef enum LodePNGFilterStrategy {
   2.656 -  /*every filter at zero*/
   2.657 -  LFS_ZERO = 0,
   2.658 -  /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/
   2.659 -  LFS_ONE = 1,
   2.660 -  LFS_TWO = 2,
   2.661 -  LFS_THREE = 3,
   2.662 -  LFS_FOUR = 4,
   2.663 -  /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
   2.664 -  LFS_MINSUM,
   2.665 -  /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending
   2.666 -  on the image, this is better or worse than minsum.*/
   2.667 -  LFS_ENTROPY,
   2.668 -  /*
   2.669 -  Brute-force-search PNG filters by compressing each filter for each scanline.
   2.670 -  Experimental, very slow, and only rarely gives better compression than MINSUM.
   2.671 -  */
   2.672 -  LFS_BRUTE_FORCE,
   2.673 -  /*use predefined_filters buffer: you specify the filter type for each scanline*/
   2.674 -  LFS_PREDEFINED
   2.675 -} LodePNGFilterStrategy;
   2.676 -
   2.677 -/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...),
   2.678 -which helps decide which color model to use for encoding.
   2.679 -Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/
   2.680 -typedef struct LodePNGColorStats {
   2.681 -  unsigned colored; /*not grayscale*/
   2.682 -  unsigned key; /*image is not opaque and color key is possible instead of full alpha*/
   2.683 -  unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/
   2.684 -  unsigned short key_g;
   2.685 -  unsigned short key_b;
   2.686 -  unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/
   2.687 -  unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/
   2.688 -  unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/
   2.689 -  unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/
   2.690 -  size_t numpixels;
   2.691 -
   2.692 -  /*user settings for computing/using the stats*/
   2.693 -  unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/
   2.694 -  unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/
   2.695 -} LodePNGColorStats;
   2.696 -
   2.697 -void lodepng_color_stats_init(LodePNGColorStats* stats);
   2.698 -
   2.699 -/*Get a LodePNGColorStats of the image. The stats must already have been inited.*/
   2.700 -void lodepng_compute_color_stats(LodePNGColorStats* stats,
   2.701 -                                 const unsigned char* image, unsigned w, unsigned h,
   2.702 -                                 const LodePNGColorMode* mode_in);
   2.703 -/*Computes a minimal PNG color model that can contain all colors as indicated by the stats and it settings.
   2.704 -The stats should be computed with lodepng_compute_color_stats.
   2.705 -mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant.
   2.706 -Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image,
   2.707 -e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ...
   2.708 -LodePNG uses this function internally if auto_convert is enabled (it is by default).
   2.709 -*/
   2.710 -unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
   2.711 -                                   const LodePNGColorMode* mode_in,
   2.712 -                                   const LodePNGColorMode* stats);
   2.713 -
   2.714 -/*Settings for the encoder.*/
   2.715 -typedef struct LodePNGEncoderSettings {
   2.716 -  LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
   2.717 -
   2.718 -  unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/
   2.719 -
   2.720 -  /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than
   2.721 -  8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to
   2.722 -  completely follow the official PNG heuristic, filter_palette_zero must be true and
   2.723 -  filter_strategy must be LFS_MINSUM*/
   2.724 -  unsigned filter_palette_zero;
   2.725 -  /*Which filter strategy to use when not using zeroes due to filter_palette_zero.
   2.726 -  Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/
   2.727 -  LodePNGFilterStrategy filter_strategy;
   2.728 -  /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with
   2.729 -  the same length as the amount of scanlines in the image, and each value must <= 5. You
   2.730 -  have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
   2.731 -  must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
   2.732 -  const unsigned char* predefined_filters;
   2.733 -
   2.734 -  /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
   2.735 -  If colortype is 3, PLTE is _always_ created.*/
   2.736 -  unsigned force_palette;
   2.737 -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
   2.738 -  /*add LodePNG identifier and version as a text chunk, for debugging*/
   2.739 -  unsigned add_id;
   2.740 -  /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
   2.741 -  unsigned text_compression;
   2.742 -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
   2.743 -} LodePNGEncoderSettings;
   2.744 -
   2.745 -void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);
   2.746 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.747 -
   2.748 -
   2.749 -#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
   2.750 -/*The settings, state and information for extended encoding and decoding.*/
   2.751 -typedef struct LodePNGState {
   2.752 -#ifdef LODEPNG_COMPILE_DECODER
   2.753 -  LodePNGDecoderSettings decoder; /*the decoding settings*/
   2.754 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.755 -#ifdef LODEPNG_COMPILE_ENCODER
   2.756 -  LodePNGEncoderSettings encoder; /*the encoding settings*/
   2.757 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.758 -  LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
   2.759 -  LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
   2.760 -  unsigned error;
   2.761 -#ifdef LODEPNG_COMPILE_CPP
   2.762 -  /* For the lodepng::State subclass. */
   2.763 -  virtual ~LodePNGState(){}
   2.764 -#endif
   2.765 -} LodePNGState;
   2.766 -
   2.767 -/*init, cleanup and copy functions to use with this struct*/
   2.768 -void lodepng_state_init(LodePNGState* state);
   2.769 -void lodepng_state_cleanup(LodePNGState* state);
   2.770 -void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);
   2.771 -#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
   2.772 -
   2.773 -#ifdef LODEPNG_COMPILE_DECODER
   2.774 -/*
   2.775 -Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
   2.776 -getting much more information about the PNG image and color mode.
   2.777 -*/
   2.778 -unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
   2.779 -                        LodePNGState* state,
   2.780 -                        const unsigned char* in, size_t insize);
   2.781 -
   2.782 -/*
   2.783 -Read the PNG header, but not the actual data. This returns only the information
   2.784 -that is in the IHDR chunk of the PNG, such as width, height and color type. The
   2.785 -information is placed in the info_png field of the LodePNGState.
   2.786 -*/
   2.787 -unsigned lodepng_inspect(unsigned* w, unsigned* h,
   2.788 -                         LodePNGState* state,
   2.789 -                         const unsigned char* in, size_t insize);
   2.790 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.791 -
   2.792 -/*
   2.793 -Reads one metadata chunk (other than IHDR) of the PNG file and outputs what it
   2.794 -read in the state. Returns error code on failure.
   2.795 -Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const
   2.796 -to find the desired chunk type, and if non null use lodepng_inspect_chunk (with
   2.797 -chunk_pointer - start_of_file as pos).
   2.798 -Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...).
   2.799 -Ignores unsupported, unknown, non-metadata or IHDR chunks (without error).
   2.800 -Requirements: &in[pos] must point to start of a chunk, must use regular
   2.801 -lodepng_inspect first since format of most other chunks depends on IHDR, and if
   2.802 -there is a PLTE chunk, that one must be inspected before tRNS or bKGD.
   2.803 -*/
   2.804 -unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
   2.805 -                               const unsigned char* in, size_t insize);
   2.806 -
   2.807 -#ifdef LODEPNG_COMPILE_ENCODER
   2.808 -/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
   2.809 -unsigned lodepng_encode(unsigned char** out, size_t* outsize,
   2.810 -                        const unsigned char* image, unsigned w, unsigned h,
   2.811 -                        LodePNGState* state);
   2.812 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.813 -
   2.814 -/*
   2.815 -The lodepng_chunk functions are normally not needed, except to traverse the
   2.816 -unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
   2.817 -It also allows traversing the chunks of an encoded PNG file yourself.
   2.818 -
   2.819 -The chunk pointer always points to the beginning of the chunk itself, that is
   2.820 -the first byte of the 4 length bytes.
   2.821 -
   2.822 -In the PNG file format, chunks have the following format:
   2.823 --4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)
   2.824 --4 bytes chunk type (ASCII a-z,A-Z only, see below)
   2.825 --length bytes of data (may be 0 bytes if length was 0)
   2.826 --4 bytes of CRC, computed on chunk name + data
   2.827 -
   2.828 -The first chunk starts at the 8th byte of the PNG file, the entire rest of the file
   2.829 -exists out of concatenated chunks with the above format.
   2.830 -
   2.831 -PNG standard chunk ASCII naming conventions:
   2.832 --First byte: uppercase = critical, lowercase = ancillary
   2.833 --Second byte: uppercase = public, lowercase = private
   2.834 --Third byte: must be uppercase
   2.835 --Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
   2.836 -*/
   2.837 -
   2.838 -/*
   2.839 -Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
   2.840 -There must be at least 4 bytes to read from. If the result value is too large,
   2.841 -it may be corrupt data.
   2.842 -*/
   2.843 -unsigned lodepng_chunk_length(const unsigned char* chunk);
   2.844 -
   2.845 -/*puts the 4-byte type in null terminated string*/
   2.846 -void lodepng_chunk_type(char type[5], const unsigned char* chunk);
   2.847 -
   2.848 -/*check if the type is the given type*/
   2.849 -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);
   2.850 -
   2.851 -/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
   2.852 -unsigned char lodepng_chunk_ancillary(const unsigned char* chunk);
   2.853 -
   2.854 -/*0: public, 1: private (see PNG standard)*/
   2.855 -unsigned char lodepng_chunk_private(const unsigned char* chunk);
   2.856 -
   2.857 -/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
   2.858 -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);
   2.859 -
   2.860 -/*get pointer to the data of the chunk, where the input points to the header of the chunk*/
   2.861 -unsigned char* lodepng_chunk_data(unsigned char* chunk);
   2.862 -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);
   2.863 -
   2.864 -/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
   2.865 -unsigned lodepng_chunk_check_crc(const unsigned char* chunk);
   2.866 -
   2.867 -/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
   2.868 -void lodepng_chunk_generate_crc(unsigned char* chunk);
   2.869 -
   2.870 -/*
   2.871 -Iterate to next chunks, allows iterating through all chunks of the PNG file.
   2.872 -Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call,
   2.873 -or the 8th byte of a PNG file which always has the first chunk), or alternatively may
   2.874 -point to the first byte of the PNG file (which is not a chunk but the magic header, the
   2.875 -function will then skip over it and return the first real chunk).
   2.876 -Expects at least 8 readable bytes of memory in the input pointer.
   2.877 -Will output pointer to the start of the next chunk or the end of the file if there
   2.878 -is no more chunk after this. Start this process at the 8th byte of the PNG file.
   2.879 -In a non-corrupt PNG file, the last chunk should have name "IEND".
   2.880 -*/
   2.881 -unsigned char* lodepng_chunk_next(unsigned char* chunk);
   2.882 -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk);
   2.883 -
   2.884 -/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/
   2.885 -unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]);
   2.886 -const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]);
   2.887 -
   2.888 -/*
   2.889 -Appends chunk to the data in out. The given chunk should already have its chunk header.
   2.890 -The out variable and outlength are updated to reflect the new reallocated buffer.
   2.891 -Returns error code (0 if it went ok)
   2.892 -*/
   2.893 -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk);
   2.894 -
   2.895 -/*
   2.896 -Appends new chunk to out. The chunk to append is given by giving its length, type
   2.897 -and data separately. The type is a 4-letter string.
   2.898 -The out variable and outlength are updated to reflect the new reallocated buffer.
   2.899 -Returne error code (0 if it went ok)
   2.900 -*/
   2.901 -unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
   2.902 -                              const char* type, const unsigned char* data);
   2.903 -
   2.904 -
   2.905 -/*Calculate CRC32 of buffer*/
   2.906 -unsigned lodepng_crc32(const unsigned char* buf, size_t len);
   2.907 -#endif /*LODEPNG_COMPILE_PNG*/
   2.908 -
   2.909 -
   2.910 -#ifdef LODEPNG_COMPILE_ZLIB
   2.911 -/*
   2.912 -This zlib part can be used independently to zlib compress and decompress a
   2.913 -buffer. It cannot be used to create gzip files however, and it only supports the
   2.914 -part of zlib that is required for PNG, it does not support dictionaries.
   2.915 -*/
   2.916 -
   2.917 -#ifdef LODEPNG_COMPILE_DECODER
   2.918 -/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
   2.919 -unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
   2.920 -                         const unsigned char* in, size_t insize,
   2.921 -                         const LodePNGDecompressSettings* settings);
   2.922 -
   2.923 -/*
   2.924 -Decompresses Zlib data. Reallocates the out buffer and appends the data. The
   2.925 -data must be according to the zlib specification.
   2.926 -Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
   2.927 -buffer and *outsize its size in bytes. out must be freed by user after usage.
   2.928 -*/
   2.929 -unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,
   2.930 -                                 const unsigned char* in, size_t insize,
   2.931 -                                 const LodePNGDecompressSettings* settings);
   2.932 -#endif /*LODEPNG_COMPILE_DECODER*/
   2.933 -
   2.934 -#ifdef LODEPNG_COMPILE_ENCODER
   2.935 -/*
   2.936 -Compresses data with Zlib. Reallocates the out buffer and appends the data.
   2.937 -Zlib adds a small header and trailer around the deflate data.
   2.938 -The data is output in the format of the zlib specification.
   2.939 -Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
   2.940 -buffer and *outsize its size in bytes. out must be freed by user after usage.
   2.941 -*/
   2.942 -unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,
   2.943 -                               const unsigned char* in, size_t insize,
   2.944 -                               const LodePNGCompressSettings* settings);
   2.945 -
   2.946 -/*
   2.947 -Find length-limited Huffman code for given frequencies. This function is in the
   2.948 -public interface only for tests, it's used internally by lodepng_deflate.
   2.949 -*/
   2.950 -unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
   2.951 -                                      size_t numcodes, unsigned maxbitlen);
   2.952 -
   2.953 -/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
   2.954 -unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
   2.955 -                         const unsigned char* in, size_t insize,
   2.956 -                         const LodePNGCompressSettings* settings);
   2.957 -
   2.958 -#endif /*LODEPNG_COMPILE_ENCODER*/
   2.959 -#endif /*LODEPNG_COMPILE_ZLIB*/
   2.960 -
   2.961 -#ifdef LODEPNG_COMPILE_DISK
   2.962 -/*
   2.963 -Load a file from disk into buffer. The function allocates the out buffer, and
   2.964 -after usage you should free it.
   2.965 -out: output parameter, contains pointer to loaded buffer.
   2.966 -outsize: output parameter, size of the allocated out buffer
   2.967 -filename: the path to the file to load
   2.968 -return value: error code (0 means ok)
   2.969 -*/
   2.970 -unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);
   2.971 -
   2.972 -/*
   2.973 -Save a file from buffer to disk. Warning, if it exists, this function overwrites
   2.974 -the file without warning!
   2.975 -buffer: the buffer to write
   2.976 -buffersize: size of the buffer to write
   2.977 -filename: the path to the file to save to
   2.978 -return value: error code (0 means ok)
   2.979 -*/
   2.980 -unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);
   2.981 -#endif /*LODEPNG_COMPILE_DISK*/
   2.982 -
   2.983 -#ifdef LODEPNG_COMPILE_CPP
   2.984 -/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
   2.985 -namespace lodepng {
   2.986 -#ifdef LODEPNG_COMPILE_PNG
   2.987 -class State : public LodePNGState {
   2.988 -  public:
   2.989 -    State();
   2.990 -    State(const State& other);
   2.991 -    virtual ~State();
   2.992 -    State& operator=(const State& other);
   2.993 -};
   2.994 -
   2.995 -#ifdef LODEPNG_COMPILE_DECODER
   2.996 -/* Same as other lodepng::decode, but using a State for more settings and information. */
   2.997 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
   2.998 -                State& state,
   2.999 -                const unsigned char* in, size_t insize);
  2.1000 -unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  2.1001 -                State& state,
  2.1002 -                const std::vector<unsigned char>& in);
  2.1003 -#endif /*LODEPNG_COMPILE_DECODER*/
  2.1004 -
  2.1005 -#ifdef LODEPNG_COMPILE_ENCODER
  2.1006 -/* Same as other lodepng::encode, but using a State for more settings and information. */
  2.1007 -unsigned encode(std::vector<unsigned char>& out,
  2.1008 -                const unsigned char* in, unsigned w, unsigned h,
  2.1009 -                State& state);
  2.1010 -unsigned encode(std::vector<unsigned char>& out,
  2.1011 -                const std::vector<unsigned char>& in, unsigned w, unsigned h,
  2.1012 -                State& state);
  2.1013 -#endif /*LODEPNG_COMPILE_ENCODER*/
  2.1014 -
  2.1015 -#ifdef LODEPNG_COMPILE_DISK
  2.1016 -/*
  2.1017 -Load a file from disk into an std::vector.
  2.1018 -return value: error code (0 means ok)
  2.1019 -*/
  2.1020 -unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);
  2.1021 -
  2.1022 -/*
  2.1023 -Save the binary data in an std::vector to a file on disk. The file is overwritten
  2.1024 -without warning.
  2.1025 -*/
  2.1026 -unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);
  2.1027 -#endif /* LODEPNG_COMPILE_DISK */
  2.1028 -#endif /* LODEPNG_COMPILE_PNG */
  2.1029 -
  2.1030 -#ifdef LODEPNG_COMPILE_ZLIB
  2.1031 -#ifdef LODEPNG_COMPILE_DECODER
  2.1032 -/* Zlib-decompress an unsigned char buffer */
  2.1033 -unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  2.1034 -                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
  2.1035 -
  2.1036 -/* Zlib-decompress an std::vector */
  2.1037 -unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  2.1038 -                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
  2.1039 -#endif /* LODEPNG_COMPILE_DECODER */
  2.1040 -
  2.1041 -#ifdef LODEPNG_COMPILE_ENCODER
  2.1042 -/* Zlib-compress an unsigned char buffer */
  2.1043 -unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  2.1044 -                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
  2.1045 -
  2.1046 -/* Zlib-compress an std::vector */
  2.1047 -unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  2.1048 -                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
  2.1049 -#endif /* LODEPNG_COMPILE_ENCODER */
  2.1050 -#endif /* LODEPNG_COMPILE_ZLIB */
  2.1051 -} /* namespace lodepng */
  2.1052 -#endif /*LODEPNG_COMPILE_CPP*/
  2.1053 -
  2.1054 -/*
  2.1055 -TODO:
  2.1056 -[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
  2.1057 -[.] check compatibility with various compilers  - done but needs to be redone for every newer version
  2.1058 -[X] converting color to 16-bit per channel types
  2.1059 -[X] support color profile chunk types (but never let them touch RGB values by default)
  2.1060 -[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST)
  2.1061 -[ ] make sure encoder generates no chunks with size > (2^31)-1
  2.1062 -[ ] partial decoding (stream processing)
  2.1063 -[X] let the "isFullyOpaque" function check color keys and transparent palettes too
  2.1064 -[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
  2.1065 -[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58)
  2.1066 -[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ...
  2.1067 -[ ] error messages with line numbers (and version)
  2.1068 -[ ] errors in state instead of as return code?
  2.1069 -[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk
  2.1070 -[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes
  2.1071 -[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...
  2.1072 -[ ] allow user to give data (void*) to custom allocator
  2.1073 -[ ] provide alternatives for C library functions not present on some platforms (memcpy, ...)
  2.1074 -[ ] rename "grey" to "gray" everywhere since "color" also uses US spelling (keep "grey" copies for backwards compatibility)
  2.1075 -*/
  2.1076 -
  2.1077 -#endif /*LODEPNG_H inclusion guard*/
  2.1078 -
  2.1079 -/*
  2.1080 -LodePNG Documentation
  2.1081 ----------------------
  2.1082 -
  2.1083 -0. table of contents
  2.1084 ---------------------
  2.1085 -
  2.1086 -  1. about
  2.1087 -   1.1. supported features
  2.1088 -   1.2. features not supported
  2.1089 -  2. C and C++ version
  2.1090 -  3. security
  2.1091 -  4. decoding
  2.1092 -  5. encoding
  2.1093 -  6. color conversions
  2.1094 -    6.1. PNG color types
  2.1095 -    6.2. color conversions
  2.1096 -    6.3. padding bits
  2.1097 -    6.4. A note about 16-bits per channel and endianness
  2.1098 -  7. error values
  2.1099 -  8. chunks and PNG editing
  2.1100 -  9. compiler support
  2.1101 -  10. examples
  2.1102 -   10.1. decoder C++ example
  2.1103 -   10.2. decoder C example
  2.1104 -  11. state settings reference
  2.1105 -  12. changes
  2.1106 -  13. contact information
  2.1107 -
  2.1108 -
  2.1109 -1. about
  2.1110 ---------
  2.1111 -
  2.1112 -PNG is a file format to store raster images losslessly with good compression,
  2.1113 -supporting different color types and alpha channel.
  2.1114 -
  2.1115 -LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
  2.1116 -Specification (Second Edition) - W3C Recommendation 10 November 2003.
  2.1117 -
  2.1118 -The specifications used are:
  2.1119 -
  2.1120 -*) Portable Network Graphics (PNG) Specification (Second Edition):
  2.1121 -     http://www.w3.org/TR/2003/REC-PNG-20031110
  2.1122 -*) RFC 1950 ZLIB Compressed Data Format version 3.3:
  2.1123 -     http://www.gzip.org/zlib/rfc-zlib.html
  2.1124 -*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
  2.1125 -     http://www.gzip.org/zlib/rfc-deflate.html
  2.1126 -
  2.1127 -The most recent version of LodePNG can currently be found at
  2.1128 -http://lodev.org/lodepng/
  2.1129 -
  2.1130 -LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
  2.1131 -extra functionality.
  2.1132 -
  2.1133 -LodePNG exists out of two files:
  2.1134 --lodepng.h: the header file for both C and C++
  2.1135 --lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage
  2.1136 -
  2.1137 -If you want to start using LodePNG right away without reading this doc, get the
  2.1138 -examples from the LodePNG website to see how to use it in code, or check the
  2.1139 -smaller examples in chapter 13 here.
  2.1140 -
  2.1141 -LodePNG is simple but only supports the basic requirements. To achieve
  2.1142 -simplicity, the following design choices were made: There are no dependencies
  2.1143 -on any external library. There are functions to decode and encode a PNG with
  2.1144 -a single function call, and extended versions of these functions taking a
  2.1145 -LodePNGState struct allowing to specify or get more information. By default
  2.1146 -the colors of the raw image are always RGB or RGBA, no matter what color type
  2.1147 -the PNG file uses. To read and write files,