Path: blob/a-new-beginning/SharedDependencies/Sources/lodepng/lodepng.cpp
2 views
/*1LodePNG version 2025050623Copyright (c) 2005-2025 Lode Vandevenne45This software is provided 'as-is', without any express or implied6warranty. In no event will the authors be held liable for any damages7arising from the use of this software.89Permission is granted to anyone to use this software for any purpose,10including commercial applications, and to alter it and redistribute it11freely, subject to the following restrictions:12131. The origin of this software must not be misrepresented; you must not14claim that you wrote the original software. If you use this software15in a product, an acknowledgment in the product documentation would be16appreciated but is not required.17182. Altered source versions must be plainly marked as such, and must not be19misrepresented as being the original software.20213. This notice may not be removed or altered from any source22distribution.23*/2425/*26The manual and changelog are in the header file "lodepng.h"27Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.28*/2930#include "lodepng.h"3132#ifdef LODEPNG_COMPILE_DISK33#include <limits.h> /* LONG_MAX */34#include <stdio.h> /* file handling */35#endif /* LODEPNG_COMPILE_DISK */3637#ifdef LODEPNG_COMPILE_ALLOCATORS38#include <stdlib.h> /* allocations */39#endif /* LODEPNG_COMPILE_ALLOCATORS */4041#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/42#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/43#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/44#endif /*_MSC_VER */4546const char* LODEPNG_VERSION_STRING = "20250506";4748/*49This source file is divided into the following large parts. The code sections50with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.51-Tools for C and common code for PNG and Zlib52-C Code for Zlib (huffman, deflate, ...)53-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)54-The C++ wrapper around all of the above55*/5657/* ////////////////////////////////////////////////////////////////////////// */58/* ////////////////////////////////////////////////////////////////////////// */59/* // Tools for C, and common code for PNG and Zlib. // */60/* ////////////////////////////////////////////////////////////////////////// */61/* ////////////////////////////////////////////////////////////////////////// */6263/*The malloc, realloc and free functions defined here with "lodepng_" in front64of the name, so that you can easily change them to others related to your65platform if needed. Everything else in the code calls these. Pass66-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out67#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and68define them in your own project's source files without needing to change69lodepng source code. Don't forget to remove "static" if you copypaste them70from here.*/7172#ifdef LODEPNG_COMPILE_ALLOCATORS73static void* lodepng_malloc(size_t size) {74#ifdef LODEPNG_MAX_ALLOC75if(size > LODEPNG_MAX_ALLOC) return 0;76#endif77return malloc(size);78}7980/* NOTE: when realloc returns NULL, it leaves the original memory untouched */81static void* lodepng_realloc(void* ptr, size_t new_size) {82#ifdef LODEPNG_MAX_ALLOC83if(new_size > LODEPNG_MAX_ALLOC) return 0;84#endif85return realloc(ptr, new_size);86}8788static void lodepng_free(void* ptr) {89free(ptr);90}91#else /*LODEPNG_COMPILE_ALLOCATORS*/92/* TODO: support giving additional void* payload to the custom allocators */93void* lodepng_malloc(size_t size);94void* lodepng_realloc(void* ptr, size_t new_size);95void lodepng_free(void* ptr);96#endif /*LODEPNG_COMPILE_ALLOCATORS*/9798/* convince the compiler to inline a function, for use when this measurably improves performance */99/* inline is not available in C90, but use it when supported by the compiler */100#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))101#define LODEPNG_INLINE inline102#else103#define LODEPNG_INLINE /* not available */104#endif105106/* restrict is not available in C90, but use it when supported by the compiler */107#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\108(defined(_MSC_VER) && (_MSC_VER >= 1400)) || \109(defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus))110#define LODEPNG_RESTRICT __restrict111#else112#define LODEPNG_RESTRICT /* not available */113#endif114115/* Replacements for C library functions such as memcpy and strlen, to support platforms116where a full C library is not available. The compiler can recognize them and compile117to something as fast. */118119static void lodepng_memcpy(void* LODEPNG_RESTRICT dst,120const void* LODEPNG_RESTRICT src, size_t size) {121size_t i;122for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i];123}124125static void lodepng_memset(void* LODEPNG_RESTRICT dst,126int value, size_t num) {127size_t i;128for(i = 0; i < num; i++) ((char*)dst)[i] = (char)value;129}130131/* does not check memory out of bounds, do not use on untrusted data */132static size_t lodepng_strlen(const char* a) {133const char* orig = a;134/* avoid warning about unused function in case of disabled COMPILE... macros */135(void)(&lodepng_strlen);136while(*a) a++;137return (size_t)(a - orig);138}139140#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))141#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))142143#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)144/* Safely check if adding two integers will overflow (no undefined145behavior, compiler removing the code, etc...) and output result. */146static int lodepng_addofl(size_t a, size_t b, size_t* result) {147*result = a + b; /* Unsigned addition is well defined and safe in C90 */148return *result < a;149}150#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/151152#ifdef LODEPNG_COMPILE_DECODER153/* Safely check if multiplying two integers will overflow (no undefined154behavior, compiler removing the code, etc...) and output result. */155static int lodepng_mulofl(size_t a, size_t b, size_t* result) {156*result = a * b; /* Unsigned multiplication is well defined and safe in C90 */157return (a != 0 && *result / a != b);158}159160#ifdef LODEPNG_COMPILE_ZLIB161/* Safely check if a + b > c, even if overflow could happen. */162static int lodepng_gtofl(size_t a, size_t b, size_t c) {163size_t d;164if(lodepng_addofl(a, b, &d)) return 1;165return d > c;166}167#endif /*LODEPNG_COMPILE_ZLIB*/168#endif /*LODEPNG_COMPILE_DECODER*/169170171/*172Often in case of an error a value is assigned to a variable and then it breaks173out of a loop (to go to the cleanup phase of a function). This macro does that.174It makes the error handling code shorter and more readable.175176Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83);177*/178#define CERROR_BREAK(errorvar, code){\179errorvar = code;\180break;\181}182183/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/184#define ERROR_BREAK(code) CERROR_BREAK(error, code)185186/*Set error var to the error code, and return it.*/187#define CERROR_RETURN_ERROR(errorvar, code){\188errorvar = code;\189return code;\190}191192/*Try the code, if it returns error, also return the error.*/193#define CERROR_TRY_RETURN(call){\194unsigned error = call;\195if(error) return error;\196}197198/*Set error var to the error code, and return from the void function.*/199#define CERROR_RETURN(errorvar, code){\200errorvar = code;\201return;\202}203204/*205About uivector, ucvector and string:206-All of them wrap dynamic arrays or text strings in a similar way.207-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.208-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.209-They're not used in the interface, only internally in this file as static functions.210-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.211*/212213#ifdef LODEPNG_COMPILE_ZLIB214#ifdef LODEPNG_COMPILE_ENCODER215/*dynamic vector of unsigned ints*/216typedef struct uivector {217unsigned* data;218size_t size; /*size in number of unsigned longs*/219size_t allocsize; /*allocated size in bytes*/220} uivector;221222static void uivector_cleanup(void* p) {223((uivector*)p)->size = ((uivector*)p)->allocsize = 0;224lodepng_free(((uivector*)p)->data);225((uivector*)p)->data = NULL;226}227228/*returns 1 if success, 0 if failure ==> nothing done*/229static unsigned uivector_resize(uivector* p, size_t size) {230size_t allocsize = size * sizeof(unsigned);231if(allocsize > p->allocsize) {232size_t newsize = allocsize + (p->allocsize >> 1u);233void* data = lodepng_realloc(p->data, newsize);234if(data) {235p->allocsize = newsize;236p->data = (unsigned*)data;237}238else return 0; /*error: not enough memory*/239}240p->size = size;241return 1; /*success*/242}243244static void uivector_init(uivector* p) {245p->data = NULL;246p->size = p->allocsize = 0;247}248249/*returns 1 if success, 0 if failure ==> nothing done*/250static unsigned uivector_push_back(uivector* p, unsigned c) {251if(!uivector_resize(p, p->size + 1)) return 0;252p->data[p->size - 1] = c;253return 1;254}255#endif /*LODEPNG_COMPILE_ENCODER*/256#endif /*LODEPNG_COMPILE_ZLIB*/257258/* /////////////////////////////////////////////////////////////////////////// */259260/*dynamic vector of unsigned chars*/261typedef struct ucvector {262unsigned char* data;263size_t size; /*used size*/264size_t allocsize; /*allocated size*/265} ucvector;266267/*returns 1 if success, 0 if failure ==> nothing done*/268static unsigned ucvector_reserve(ucvector* p, size_t size) {269if(size > p->allocsize) {270size_t newsize = size + (p->allocsize >> 1u);271void* data = lodepng_realloc(p->data, newsize);272if(data) {273p->allocsize = newsize;274p->data = (unsigned char*)data;275}276else return 0; /*error: not enough memory*/277}278return 1; /*success*/279}280281/*returns 1 if success, 0 if failure ==> nothing done*/282static unsigned ucvector_resize(ucvector* p, size_t size) {283p->size = size;284return ucvector_reserve(p, size);285}286287static ucvector ucvector_init(unsigned char* buffer, size_t size) {288ucvector v;289v.data = buffer;290v.allocsize = v.size = size;291return v;292}293294/* ////////////////////////////////////////////////////////////////////////// */295296#ifdef LODEPNG_COMPILE_PNG297#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS298299/*free string pointer and set it to NULL*/300static void string_cleanup(char** out) {301lodepng_free(*out);302*out = NULL;303}304305/*also appends null termination character*/306static char* alloc_string_sized(const char* in, size_t insize) {307char* out = (char*)lodepng_malloc(insize + 1);308if(out) {309lodepng_memcpy(out, in, insize);310out[insize] = 0;311}312return out;313}314315/* dynamically allocates a new string with a copy of the null terminated input text */316static char* alloc_string(const char* in) {317return alloc_string_sized(in, lodepng_strlen(in));318}319#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/320#endif /*LODEPNG_COMPILE_PNG*/321322/* ////////////////////////////////////////////////////////////////////////// */323324#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)325static unsigned lodepng_read32bitInt(const unsigned char* buffer) {326return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) |327((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);328}329#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/330331#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)332/*buffer must have at least 4 allocated bytes available*/333static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {334buffer[0] = (unsigned char)((value >> 24) & 0xff);335buffer[1] = (unsigned char)((value >> 16) & 0xff);336buffer[2] = (unsigned char)((value >> 8) & 0xff);337buffer[3] = (unsigned char)((value ) & 0xff);338}339#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/340341/* ////////////////////////////////////////////////////////////////////////// */342/* / File IO / */343/* ////////////////////////////////////////////////////////////////////////// */344345#ifdef LODEPNG_COMPILE_DISK346347/* returns negative value on error. This should be pure C compatible, so no fstat. */348static long lodepng_filesize(FILE* file) {349long size;350if(fseek(file, 0, SEEK_END) != 0) return -1;351size = ftell(file);352/* It may give LONG_MAX as directory size, this is invalid for us. */353if(size == LONG_MAX) return -1;354if(fseek(file, 0, SEEK_SET) != 0) return -1;355return size;356}357358/* Allocates the output buffer to the file size and reads the file into it. Returns error code.*/359static unsigned lodepng_load_file_(unsigned char** out, size_t* outsize, FILE* file) {360long size = lodepng_filesize(file);361if(size < 0) return 78;362*outsize = (size_t)size;363*out = (unsigned char*)lodepng_malloc((size_t)size);364if(!(*out) && size > 0) return 83; /*the above malloc failed*/365if(fread(*out, 1, *outsize, file) != *outsize) return 78;366return 0; /*ok*/367}368369unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {370unsigned error;371FILE* file = fopen(filename, "rb");372if(!file) return 78;373error = lodepng_load_file_(out, outsize, file);374fclose(file);375return error;376}377378/*write given buffer to the file, overwriting the file, it doesn't append to it.*/379unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {380FILE* file = fopen(filename, "wb" );381if(!file) return 79;382fwrite(buffer, 1, buffersize, file);383fclose(file);384return 0;385}386387#endif /*LODEPNG_COMPILE_DISK*/388389/* ////////////////////////////////////////////////////////////////////////// */390/* ////////////////////////////////////////////////////////////////////////// */391/* // End of common code and tools. Begin of Zlib related code. // */392/* ////////////////////////////////////////////////////////////////////////// */393/* ////////////////////////////////////////////////////////////////////////// */394395#ifdef LODEPNG_COMPILE_ZLIB396#ifdef LODEPNG_COMPILE_ENCODER397398typedef struct {399ucvector* data;400unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/401} LodePNGBitWriter;402403static void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) {404writer->data = data;405writer->bp = 0;406}407408/*TODO: this ignores potential out of memory errors*/409#define WRITEBIT(writer, bit){\410/* append new byte */\411if(((writer->bp) & 7u) == 0) {\412if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\413writer->data->data[writer->data->size - 1] = 0;\414}\415(writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\416++writer->bp;\417}418419/* LSB of value is written first, and LSB of bytes is used first */420static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) {421if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */422WRITEBIT(writer, value);423} else {424/* TODO: increase output size only once here rather than in each WRITEBIT */425size_t i;426for(i = 0; i != nbits; ++i) {427WRITEBIT(writer, (unsigned char)((value >> i) & 1));428}429}430}431432/* This one is to use for adding huffman symbol, the value bits are written MSB first */433static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) {434size_t i;435for(i = 0; i != nbits; ++i) {436/* TODO: increase output size only once here rather than in each WRITEBIT */437WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u));438}439}440#endif /*LODEPNG_COMPILE_ENCODER*/441442#ifdef LODEPNG_COMPILE_DECODER443444typedef struct {445const unsigned char* data;446size_t size; /*size of data in bytes*/447size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/448size_t bp;449unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/450} LodePNGBitReader;451452/* data size argument is in bytes. Returns error if size too large causing overflow */453static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) {454size_t temp;455reader->data = data;456reader->size = size;457/* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */458if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;459/*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and460trying to ensure 32 more bits*/461if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;462reader->bp = 0;463reader->buffer = 0;464return 0; /*ok*/465}466467/*468ensureBits functions:469Ensures the reader can at least read nbits bits in one or more readBits calls,470safely even if not enough bits are available.471The nbits parameter is unused but is given for documentation purposes, error472checking for amount of bits must be done beforehand.473*/474475/*See ensureBits documentation above. This one ensures up to 9 bits */476static LODEPNG_INLINE void ensureBits9(LodePNGBitReader* reader, size_t nbits) {477size_t start = reader->bp >> 3u;478size_t size = reader->size;479if(start + 1u < size) {480reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u);481reader->buffer >>= (reader->bp & 7u);482} else {483reader->buffer = 0;484if(start + 0u < size) reader->buffer = reader->data[start + 0];485reader->buffer >>= (reader->bp & 7u);486}487(void)nbits;488}489490/*See ensureBits documentation above. This one ensures up to 17 bits */491static LODEPNG_INLINE void ensureBits17(LodePNGBitReader* reader, size_t nbits) {492size_t start = reader->bp >> 3u;493size_t size = reader->size;494if(start + 2u < size) {495reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |496((unsigned)reader->data[start + 2] << 16u);497reader->buffer >>= (reader->bp & 7u);498} else {499reader->buffer = 0;500if(start + 0u < size) reader->buffer |= reader->data[start + 0];501if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);502reader->buffer >>= (reader->bp & 7u);503}504(void)nbits;505}506507/*See ensureBits documentation above. This one ensures up to 25 bits */508static LODEPNG_INLINE void ensureBits25(LodePNGBitReader* reader, size_t nbits) {509size_t start = reader->bp >> 3u;510size_t size = reader->size;511if(start + 3u < size) {512reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |513((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);514reader->buffer >>= (reader->bp & 7u);515} else {516reader->buffer = 0;517if(start + 0u < size) reader->buffer |= reader->data[start + 0];518if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);519if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);520reader->buffer >>= (reader->bp & 7u);521}522(void)nbits;523}524525/*See ensureBits documentation above. This one ensures up to 32 bits */526static LODEPNG_INLINE void ensureBits32(LodePNGBitReader* reader, size_t nbits) {527size_t start = reader->bp >> 3u;528size_t size = reader->size;529if(start + 4u < size) {530reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |531((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);532reader->buffer >>= (reader->bp & 7u);533reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u)));534} else {535reader->buffer = 0;536if(start + 0u < size) reader->buffer |= reader->data[start + 0];537if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);538if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);539if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u);540reader->buffer >>= (reader->bp & 7u);541}542(void)nbits;543}544545/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */546static LODEPNG_INLINE unsigned peekBits(LodePNGBitReader* reader, size_t nbits) {547/* The shift allows nbits to be only up to 31. */548return reader->buffer & ((1u << nbits) - 1u);549}550551/* Must have enough bits available with ensureBits */552static LODEPNG_INLINE void advanceBits(LodePNGBitReader* reader, size_t nbits) {553reader->buffer >>= nbits;554reader->bp += nbits;555}556557/* Must have enough bits available with ensureBits */558static LODEPNG_INLINE unsigned readBits(LodePNGBitReader* reader, size_t nbits) {559unsigned result = peekBits(reader, nbits);560advanceBits(reader, nbits);561return result;562}563#endif /*LODEPNG_COMPILE_DECODER*/564565static unsigned reverseBits(unsigned bits, unsigned num) {566/*TODO: implement faster lookup table based version when needed*/567unsigned i, result = 0;568for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;569return result;570}571572/* ////////////////////////////////////////////////////////////////////////// */573/* / Deflate - Huffman / */574/* ////////////////////////////////////////////////////////////////////////// */575576#define FIRST_LENGTH_CODE_INDEX 257577#define LAST_LENGTH_CODE_INDEX 285578/*256 literals, the end code, some length codes, and 2 unused codes*/579#define NUM_DEFLATE_CODE_SYMBOLS 288580/*the distance codes have their own symbols, 30 used, 2 unused*/581#define NUM_DISTANCE_SYMBOLS 32582/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/583#define NUM_CODE_LENGTH_CODES 19584585/*the base lengths represented by codes 257-285*/586static const unsigned LENGTHBASE[29]587= {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,58867, 83, 99, 115, 131, 163, 195, 227, 258};589590/*the extra bits used by codes 257-285 (added to base length)*/591static const unsigned LENGTHEXTRA[29]592= {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,5934, 4, 4, 4, 5, 5, 5, 5, 0};594595/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/596static const unsigned DISTANCEBASE[30]597= {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,598769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};599600/*the extra bits of backwards distances (added to base)*/601static const unsigned DISTANCEEXTRA[30]602= {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,6038, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};604605/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman606tree of the dynamic huffman tree lengths is generated*/607static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]608= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};609610/* ////////////////////////////////////////////////////////////////////////// */611612/*613Huffman tree struct, containing multiple representations of the tree614*/615typedef struct HuffmanTree {616unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/617unsigned* lengths; /*the lengths of the huffman codes*/618unsigned maxbitlen; /*maximum number of bits a single code can get*/619unsigned numcodes; /*number of symbols in the alphabet = number of codes*/620/* for reading only */621unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/622unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/623} HuffmanTree;624625static void HuffmanTree_init(HuffmanTree* tree) {626tree->codes = 0;627tree->lengths = 0;628tree->table_len = 0;629tree->table_value = 0;630}631632static void HuffmanTree_cleanup(HuffmanTree* tree) {633lodepng_free(tree->codes);634lodepng_free(tree->lengths);635lodepng_free(tree->table_len);636lodepng_free(tree->table_value);637}638639/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/640/* values 8u and 9u work the fastest */641#define FIRSTBITS 9u642643/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination,644which is possible in case of only 0 or 1 present symbols. */645#define INVALIDSYMBOL 65535u646647/* make table for huffman decoding */648static unsigned HuffmanTree_makeTable(HuffmanTree* tree) {649static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/650static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;651size_t i, numpresent, pointer, size; /*total table size*/652unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned));653if(!maxlens) return 83; /*alloc fail*/654655/* compute maxlens: max total bit length of symbols sharing prefix in the first table*/656lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens));657for(i = 0; i < tree->numcodes; i++) {658unsigned symbol = tree->codes[i];659unsigned l = tree->lengths[i];660unsigned index;661if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/662/*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/663index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);664maxlens[index] = LODEPNG_MAX(maxlens[index], l);665}666/* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */667size = headsize;668for(i = 0; i < headsize; ++i) {669unsigned l = maxlens[i];670if(l > FIRSTBITS) size += (((size_t)1) << (l - FIRSTBITS));671}672tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len));673tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value));674if(!tree->table_len || !tree->table_value) {675lodepng_free(maxlens);676/* freeing tree->table values is done at a higher scope */677return 83; /*alloc fail*/678}679/*initialize with an invalid length to indicate unused entries*/680for(i = 0; i < size; ++i) tree->table_len[i] = 16;681682/*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/683pointer = headsize;684for(i = 0; i < headsize; ++i) {685unsigned l = maxlens[i];686if(l <= FIRSTBITS) continue;687tree->table_len[i] = l;688tree->table_value[i] = (unsigned short)pointer;689pointer += (((size_t)1) << (l - FIRSTBITS));690}691lodepng_free(maxlens);692693/*fill in the first table for short symbols, or secondary table for long symbols*/694numpresent = 0;695for(i = 0; i < tree->numcodes; ++i) {696unsigned l = tree->lengths[i];697unsigned symbol, reverse;698if(l == 0) continue;699symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/700/*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/701reverse = reverseBits(symbol, l);702numpresent++;703704if(l <= FIRSTBITS) {705/*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/706unsigned num = 1u << (FIRSTBITS - l);707unsigned j;708for(j = 0; j < num; ++j) {709/*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/710unsigned index = reverse | (j << l);711if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/712tree->table_len[index] = l;713tree->table_value[index] = (unsigned short)i;714}715} else {716/*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/717/*the FIRSTBITS MSBs of the symbol are the first table index*/718unsigned index = reverse & mask;719unsigned maxlen = tree->table_len[index];720/*log2 of secondary table length, should be >= l - FIRSTBITS*/721unsigned tablelen = maxlen - FIRSTBITS;722unsigned start = tree->table_value[index]; /*starting index in secondary table*/723unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/724unsigned j;725if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/726for(j = 0; j < num; ++j) {727unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */728unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));729tree->table_len[index2] = l;730tree->table_value[index2] = (unsigned short)i;731}732}733}734735if(numpresent < 2) {736/* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits,737but deflate uses 1 bit instead. In case of 0 symbols, no symbols can738appear at all, but such huffman tree could still exist (e.g. if distance739codes are never used). In both cases, not all symbols of the table will be740filled in. Fill them in with an invalid symbol value so returning them from741huffmanDecodeSymbol will cause error. */742for(i = 0; i < size; ++i) {743if(tree->table_len[i] == 16) {744/* As length, use a value smaller than FIRSTBITS for the head table,745and a value larger than FIRSTBITS for the secondary table, to ensure746valid behavior for advanceBits when reading this symbol. */747tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1);748tree->table_value[i] = INVALIDSYMBOL;749}750}751} else {752/* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.753If that is not the case (due to too long length codes), the table will not754have been fully used, and this is an error (not all bit combinations can be755decoded): an oversubscribed huffman tree, indicated by error 55. */756for(i = 0; i < size; ++i) {757if(tree->table_len[i] == 16) return 55;758}759}760761return 0;762}763764/*765Second step for the ...makeFromLengths and ...makeFromFrequencies functions.766numcodes, lengths and maxbitlen must already be filled in correctly. return767value is error.768*/769static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {770unsigned* blcount;771unsigned* nextcode;772unsigned error = 0;773unsigned bits, n;774775tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));776blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));777nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));778if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/779780if(!error) {781for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;782/*step 1: count number of instances of each code length*/783for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];784/*step 2: generate the nextcode values*/785for(bits = 1; bits <= tree->maxbitlen; ++bits) {786nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u;787}788/*step 3: generate all the codes*/789for(n = 0; n != tree->numcodes; ++n) {790if(tree->lengths[n] != 0) {791tree->codes[n] = nextcode[tree->lengths[n]]++;792/*remove superfluous bits from the code*/793tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);794}795}796}797798lodepng_free(blcount);799lodepng_free(nextcode);800801if(!error) error = HuffmanTree_makeTable(tree);802return error;803}804805/*806given the code lengths (as stored in the PNG file), generate the tree as defined807by Deflate. maxbitlen is the maximum bits that a code in the tree can have.808return value is error.809*/810static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,811size_t numcodes, unsigned maxbitlen) {812unsigned i;813tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));814if(!tree->lengths) return 83; /*alloc fail*/815for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];816tree->numcodes = (unsigned)numcodes; /*number of symbols*/817tree->maxbitlen = maxbitlen;818return HuffmanTree_makeFromLengths2(tree);819}820821#ifdef LODEPNG_COMPILE_ENCODER822823/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",824Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/825826/*chain node for boundary package merge*/827typedef struct BPMNode {828int weight; /*the sum of all weights in this chain*/829unsigned index; /*index of this leaf node (called "count" in the paper)*/830struct BPMNode* tail; /*the next nodes in this chain (null if last)*/831int in_use;832} BPMNode;833834/*lists of chains*/835typedef struct BPMLists {836/*memory pool*/837unsigned memsize;838BPMNode* memory;839unsigned numfree;840unsigned nextfree;841BPMNode** freelist;842/*two heads of lookahead chains per list*/843unsigned listsize;844BPMNode** chains0;845BPMNode** chains1;846} BPMLists;847848/*creates a new chain node with the given parameters, from the memory in the lists */849static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {850unsigned i;851BPMNode* result;852853/*memory full, so garbage collect*/854if(lists->nextfree >= lists->numfree) {855/*mark only those that are in use*/856for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;857for(i = 0; i != lists->listsize; ++i) {858BPMNode* node;859for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;860for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;861}862/*collect those that are free*/863lists->numfree = 0;864for(i = 0; i != lists->memsize; ++i) {865if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];866}867lists->nextfree = 0;868}869870result = lists->freelist[lists->nextfree++];871result->weight = weight;872result->index = index;873result->tail = tail;874return result;875}876877/*sort the leaves with stable mergesort*/878static void bpmnode_sort(BPMNode* leaves, size_t num) {879BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);880size_t width, counter = 0;881for(width = 1; width < num; width *= 2) {882BPMNode* a = (counter & 1) ? mem : leaves;883BPMNode* b = (counter & 1) ? leaves : mem;884size_t p;885for(p = 0; p < num; p += 2 * width) {886size_t q = (p + width > num) ? num : (p + width);887size_t r = (p + 2 * width > num) ? num : (p + 2 * width);888size_t i = p, j = q, k;889for(k = p; k < r; k++) {890if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];891else b[k] = a[j++];892}893}894counter++;895}896if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num);897lodepng_free(mem);898}899900/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/901static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {902unsigned lastindex = lists->chains1[c]->index;903904if(c == 0) {905if(lastindex >= numpresent) return;906lists->chains0[c] = lists->chains1[c];907lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);908} else {909/*sum of the weights of the head nodes of the previous lookahead chains.*/910int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;911lists->chains0[c] = lists->chains1[c];912if(lastindex < numpresent && sum > leaves[lastindex].weight) {913lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);914return;915}916lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);917/*in the end we are only interested in the chain of the last list, so no918need to recurse if we're at the last one (this gives measurable speedup)*/919if(num + 1 < (int)(2 * numpresent - 2)) {920boundaryPM(lists, leaves, numpresent, c - 1, num);921boundaryPM(lists, leaves, numpresent, c - 1, num);922}923}924}925926unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,927size_t numcodes, unsigned maxbitlen) {928unsigned error = 0;929unsigned i;930size_t numpresent = 0; /*number of symbols with non-zero frequency*/931BPMNode* leaves; /*the symbols, only those with > 0 frequency*/932933if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/934if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/935936leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));937if(!leaves) return 83; /*alloc fail*/938939for(i = 0; i != numcodes; ++i) {940if(frequencies[i] > 0) {941leaves[numpresent].weight = (int)frequencies[i];942leaves[numpresent].index = i;943++numpresent;944}945}946947lodepng_memset(lengths, 0, numcodes * sizeof(*lengths));948949/*ensure at least two present symbols. There should be at least one symbol950according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To951make these work as well ensure there are at least two symbols. The952Package-Merge code below also doesn't work correctly if there's only one953symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/954if(numpresent == 0) {955lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/956} else if(numpresent == 1) {957lengths[leaves[0].index] = 1;958lengths[leaves[0].index == 0 ? 1 : 0] = 1;959} else {960BPMLists lists;961BPMNode* node;962963bpmnode_sort(leaves, numpresent);964965lists.listsize = maxbitlen;966lists.memsize = 2 * maxbitlen * (maxbitlen + 1);967lists.nextfree = 0;968lists.numfree = lists.memsize;969lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));970lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));971lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));972lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));973if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/974975if(!error) {976for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];977978bpmnode_create(&lists, leaves[0].weight, 1, 0);979bpmnode_create(&lists, leaves[1].weight, 2, 0);980981for(i = 0; i != lists.listsize; ++i) {982lists.chains0[i] = &lists.memory[0];983lists.chains1[i] = &lists.memory[1];984}985986/*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/987for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);988989for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {990for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];991}992}993994lodepng_free(lists.memory);995lodepng_free(lists.freelist);996lodepng_free(lists.chains0);997lodepng_free(lists.chains1);998}9991000lodepng_free(leaves);1001return error;1002}10031004/*Create the Huffman tree given the symbol frequencies*/1005static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,1006size_t mincodes, size_t numcodes, unsigned maxbitlen) {1007unsigned error = 0;1008while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/1009tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));1010if(!tree->lengths) return 83; /*alloc fail*/1011tree->maxbitlen = maxbitlen;1012tree->numcodes = (unsigned)numcodes; /*number of symbols*/10131014error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);1015if(!error) error = HuffmanTree_makeFromLengths2(tree);1016return error;1017}1018#endif /*LODEPNG_COMPILE_ENCODER*/10191020/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/1021static unsigned generateFixedLitLenTree(HuffmanTree* tree) {1022unsigned i, error = 0;1023unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));1024if(!bitlen) return 83; /*alloc fail*/10251026/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/1027for(i = 0; i <= 143; ++i) bitlen[i] = 8;1028for(i = 144; i <= 255; ++i) bitlen[i] = 9;1029for(i = 256; i <= 279; ++i) bitlen[i] = 7;1030for(i = 280; i <= 287; ++i) bitlen[i] = 8;10311032error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);10331034lodepng_free(bitlen);1035return error;1036}10371038/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/1039static unsigned generateFixedDistanceTree(HuffmanTree* tree) {1040unsigned i, error = 0;1041unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));1042if(!bitlen) return 83; /*alloc fail*/10431044/*there are 32 distance codes, but 30-31 are unused*/1045for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;1046error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);10471048lodepng_free(bitlen);1049return error;1050}10511052#ifdef LODEPNG_COMPILE_DECODER10531054/*1055returns the code. The bit reader must already have been ensured at least 15 bits1056*/1057static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) {1058unsigned short code = peekBits(reader, FIRSTBITS);1059unsigned short l = codetree->table_len[code];1060unsigned short value = codetree->table_value[code];1061if(l <= FIRSTBITS) {1062advanceBits(reader, l);1063return value;1064} else {1065advanceBits(reader, FIRSTBITS);1066value += peekBits(reader, l - FIRSTBITS);1067advanceBits(reader, codetree->table_len[value] - FIRSTBITS);1068return codetree->table_value[value];1069}1070}1071#endif /*LODEPNG_COMPILE_DECODER*/10721073#ifdef LODEPNG_COMPILE_DECODER10741075/* ////////////////////////////////////////////////////////////////////////// */1076/* / Inflator (Decompressor) / */1077/* ////////////////////////////////////////////////////////////////////////// */10781079/*get the tree of a deflated block with fixed tree, as specified in the deflate specification1080Returns error code.*/1081static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {1082unsigned error = generateFixedLitLenTree(tree_ll);1083if(error) return error;1084return generateFixedDistanceTree(tree_d);1085}10861087/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/1088static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,1089LodePNGBitReader* reader) {1090/*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/1091unsigned error = 0;1092unsigned n, HLIT, HDIST, HCLEN, i;10931094/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/1095unsigned* bitlen_ll = 0; /*lit,len code lengths*/1096unsigned* bitlen_d = 0; /*dist code lengths*/1097/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/1098unsigned* bitlen_cl = 0;1099HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/11001101if(reader->bitsize - reader->bp < 14) return 49; /*error: the bit pointer is or will go past the memory*/1102ensureBits17(reader, 14);11031104/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/1105HLIT = readBits(reader, 5) + 257;1106/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/1107HDIST = readBits(reader, 5) + 1;1108/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/1109HCLEN = readBits(reader, 4) + 4;11101111bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));1112if(!bitlen_cl) return 83 /*alloc fail*/;11131114HuffmanTree_init(&tree_cl);11151116while(!error) {1117/*read the code length codes out of 3 * (amount of code length codes) bits*/1118if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {1119ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/1120}1121for(i = 0; i != HCLEN; ++i) {1122ensureBits9(reader, 3); /*out of bounds already checked above */1123bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);1124}1125for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {1126bitlen_cl[CLCL_ORDER[i]] = 0;1127}11281129error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);1130if(error) break;11311132/*now we can use this tree to read the lengths for the tree that this function will return*/1133bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));1134bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));1135if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);1136lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll));1137lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d));11381139/*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/1140i = 0;1141while(i < HLIT + HDIST) {1142unsigned code;1143ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/1144code = huffmanDecodeSymbol(reader, &tree_cl);1145if(code <= 15) /*a length code*/ {1146if(i < HLIT) bitlen_ll[i] = code;1147else bitlen_d[i - HLIT] = code;1148++i;1149} else if(code == 16) /*repeat previous*/ {1150unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/1151unsigned value; /*set value to the previous code*/11521153if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/11541155replength += readBits(reader, 2);11561157if(i < HLIT + 1) value = bitlen_ll[i - 1];1158else value = bitlen_d[i - HLIT - 1];1159/*repeat this value in the next lengths*/1160for(n = 0; n < replength; ++n) {1161if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/1162if(i < HLIT) bitlen_ll[i] = value;1163else bitlen_d[i - HLIT] = value;1164++i;1165}1166} else if(code == 17) /*repeat "0" 3-10 times*/ {1167unsigned replength = 3; /*read in the bits that indicate repeat length*/1168replength += readBits(reader, 3);11691170/*repeat this value in the next lengths*/1171for(n = 0; n < replength; ++n) {1172if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/11731174if(i < HLIT) bitlen_ll[i] = 0;1175else bitlen_d[i - HLIT] = 0;1176++i;1177}1178} else if(code == 18) /*repeat "0" 11-138 times*/ {1179unsigned replength = 11; /*read in the bits that indicate repeat length*/1180replength += readBits(reader, 7);11811182/*repeat this value in the next lengths*/1183for(n = 0; n < replength; ++n) {1184if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/11851186if(i < HLIT) bitlen_ll[i] = 0;1187else bitlen_d[i - HLIT] = 0;1188++i;1189}1190} else /*if(code == INVALIDSYMBOL)*/ {1191ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/1192}1193/*check if any of the ensureBits above went out of bounds*/1194if(reader->bp > reader->bitsize) {1195/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol1196(10=no endcode, 11=wrong jump outside of tree)*/1197/* TODO: revise error codes 10,11,50: the above comment is no longer valid */1198ERROR_BREAK(50); /*error, bit pointer jumps past memory*/1199}1200}1201if(error) break;12021203if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/12041205/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/1206error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);1207if(error) break;1208error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);12091210break; /*end of error-while*/1211}12121213lodepng_free(bitlen_cl);1214lodepng_free(bitlen_ll);1215lodepng_free(bitlen_d);1216HuffmanTree_cleanup(&tree_cl);12171218return error;1219}12201221/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/1222static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader,1223unsigned btype, size_t max_output_size) {1224unsigned error = 0;1225HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/1226HuffmanTree tree_d; /*the huffman tree for distance codes*/1227const size_t reserved_size = 260; /* must be at least 258 for max length, and a few extra for adding a few extra literals */1228int done = 0;12291230if(!ucvector_reserve(out, out->size + reserved_size)) return 83; /*alloc fail*/12311232HuffmanTree_init(&tree_ll);1233HuffmanTree_init(&tree_d);12341235if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d);1236else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);123712381239while(!error && !done) /*decode all symbols until end reached, breaks at end code*/ {1240/*code_ll is literal, length or end code*/1241unsigned code_ll;1242/* ensure enough bits for 2 huffman code reads (15 bits each): if the first is a literal, a second literal is read at once. This1243appears to be slightly faster, than ensuring 20 bits here for 1 huffman symbol and the potential 5 extra bits for the length symbol.*/1244ensureBits32(reader, 30);1245code_ll = huffmanDecodeSymbol(reader, &tree_ll);1246if(code_ll <= 255) {1247/*slightly faster code path if multiple literals in a row*/1248out->data[out->size++] = (unsigned char)code_ll;1249code_ll = huffmanDecodeSymbol(reader, &tree_ll);1250}1251if(code_ll <= 255) /*literal symbol*/ {1252out->data[out->size++] = (unsigned char)code_ll;1253} else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {1254unsigned code_d, distance;1255unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/1256size_t start, backward, length;12571258/*part 1: get length base*/1259length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];12601261/*part 2: get extra bits and add the value of that to length*/1262numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];1263if(numextrabits_l != 0) {1264/* bits already ensured above */1265ensureBits25(reader, 5);1266length += readBits(reader, numextrabits_l);1267}12681269/*part 3: get distance code*/1270ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */1271code_d = huffmanDecodeSymbol(reader, &tree_d);1272if(code_d > 29) {1273if(code_d <= 31) {1274ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/1275} else /* if(code_d == INVALIDSYMBOL) */{1276ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/1277}1278}1279distance = DISTANCEBASE[code_d];12801281/*part 4: get extra bits from distance*/1282numextrabits_d = DISTANCEEXTRA[code_d];1283if(numextrabits_d != 0) {1284/* bits already ensured above */1285distance += readBits(reader, numextrabits_d);1286}12871288/*part 5: fill in all the out[n] values based on the length and dist*/1289start = out->size;1290if(distance > start) ERROR_BREAK(52); /*too long backward distance*/1291backward = start - distance;12921293out->size += length;1294if(distance < length) {1295size_t forward;1296lodepng_memcpy(out->data + start, out->data + backward, distance);1297start += distance;1298for(forward = distance; forward < length; ++forward) {1299out->data[start++] = out->data[backward++];1300}1301} else {1302lodepng_memcpy(out->data + start, out->data + backward, length);1303}1304} else if(code_ll == 256) {1305done = 1; /*end code, finish the loop*/1306} else /*if(code_ll == INVALIDSYMBOL)*/ {1307ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/1308}1309if(out->allocsize - out->size < reserved_size) {1310if(!ucvector_reserve(out, out->size + reserved_size)) ERROR_BREAK(83); /*alloc fail*/1311}1312/*check if any of the ensureBits above went out of bounds*/1313if(reader->bp > reader->bitsize) {1314/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol1315(10=no endcode, 11=wrong jump outside of tree)*/1316/* TODO: revise error codes 10,11,50: the above comment is no longer valid */1317ERROR_BREAK(51); /*error, bit pointer jumps past memory*/1318}1319if(max_output_size && out->size > max_output_size) {1320ERROR_BREAK(109); /*error, larger than max size*/1321}1322}13231324HuffmanTree_cleanup(&tree_ll);1325HuffmanTree_cleanup(&tree_d);13261327return error;1328}13291330static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader,1331const LodePNGDecompressSettings* settings) {1332size_t bytepos;1333size_t size = reader->size;1334unsigned LEN, NLEN, error = 0;13351336/*go to first boundary of byte*/1337bytepos = (reader->bp + 7u) >> 3u;13381339/*read LEN (2 bytes) and NLEN (2 bytes)*/1340if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/1341LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;1342NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;13431344/*check if 16-bit NLEN is really the one's complement of LEN*/1345if(!settings->ignore_nlen && LEN + NLEN != 65535) {1346return 21; /*error: NLEN is not one's complement of LEN*/1347}13481349if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/13501351/*read the literal data: LEN bytes are now stored in the out buffer*/1352if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/13531354/*out->data can be NULL (when LEN is zero), and arithmetics on NULL ptr is undefined*/1355if (LEN) {1356lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN);1357bytepos += LEN;1358}13591360reader->bp = bytepos << 3u;13611362return error;1363}13641365static unsigned lodepng_inflatev(ucvector* out,1366const unsigned char* in, size_t insize,1367const LodePNGDecompressSettings* settings) {1368unsigned BFINAL = 0;1369LodePNGBitReader reader;1370unsigned error = LodePNGBitReader_init(&reader, in, insize);13711372if(error) return error;13731374while(!BFINAL) {1375unsigned BTYPE;1376if(reader.bitsize - reader.bp < 3) return 52; /*error, bit pointer will jump past memory*/1377ensureBits9(&reader, 3);1378BFINAL = readBits(&reader, 1);1379BTYPE = readBits(&reader, 2);13801381if(BTYPE == 3) return 20; /*error: invalid BTYPE*/1382else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/1383else error = inflateHuffmanBlock(out, &reader, BTYPE, settings->max_output_size); /*compression, BTYPE 01 or 10*/1384if(!error && settings->max_output_size && out->size > settings->max_output_size) error = 109;1385if(error) break;1386}13871388return error;1389}13901391unsigned lodepng_inflate(unsigned char** out, size_t* outsize,1392const unsigned char* in, size_t insize,1393const LodePNGDecompressSettings* settings) {1394ucvector v = ucvector_init(*out, *outsize);1395unsigned error = lodepng_inflatev(&v, in, insize, settings);1396*out = v.data;1397*outsize = v.size;1398return error;1399}14001401static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize,1402const LodePNGDecompressSettings* settings) {1403if(settings->custom_inflate) {1404unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings);1405out->allocsize = out->size;1406if(error) {1407/*the custom inflate is allowed to have its own error codes, however, we translate it to code 110*/1408error = 110;1409/*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/1410if(settings->max_output_size && out->size > settings->max_output_size) error = 109;1411}1412return error;1413} else {1414return lodepng_inflatev(out, in, insize, settings);1415}1416}14171418#endif /*LODEPNG_COMPILE_DECODER*/14191420#ifdef LODEPNG_COMPILE_ENCODER14211422/* ////////////////////////////////////////////////////////////////////////// */1423/* / Deflator (Compressor) / */1424/* ////////////////////////////////////////////////////////////////////////// */14251426static const unsigned MAX_SUPPORTED_DEFLATE_LENGTH = 258;14271428/*search the index in the array, that has the largest value smaller than or equal to the given value,1429given array must be sorted (if no value is smaller, it returns the size of the given array)*/1430static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) {1431/*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/1432size_t left = 1;1433size_t right = array_size - 1;14341435while(left <= right) {1436size_t mid = (left + right) >> 1;1437if(array[mid] >= value) right = mid - 1;1438else left = mid + 1;1439}1440if(left >= array_size || array[left] > value) left--;1441return left;1442}14431444static void addLengthDistance(uivector* values, size_t length, size_t distance) {1445/*values in encoded vector are those used by deflate:14460-255: literal bytes1447256: end1448257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)1449286-287: invalid*/14501451unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);1452unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);1453unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);1454unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);14551456size_t pos = values->size;1457/*TODO: return error when this fails (out of memory)*/1458unsigned ok = uivector_resize(values, values->size + 4);1459if(ok) {1460values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX;1461values->data[pos + 1] = extra_length;1462values->data[pos + 2] = dist_code;1463values->data[pos + 3] = extra_distance;1464}1465}14661467/*3 bytes of data get encoded into two bytes. The hash cannot use more than 31468bytes as input because 3 is the minimum match length for deflate*/1469static const unsigned HASH_NUM_VALUES = 65536;1470static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/14711472typedef struct Hash {1473int* head; /*hash value to head circular pos - can be outdated if went around window*/1474/*circular pos to prev circular pos*/1475unsigned short* chain;1476int* val; /*circular pos to hash value*/14771478/*TODO: do this not only for zeros but for any repeated byte. However for PNG1479it's always going to be the zeros that dominate, so not important for PNG*/1480int* headz; /*similar to head, but for chainz*/1481unsigned short* chainz; /*those with same amount of zeros*/1482unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/1483} Hash;14841485static unsigned hash_init(Hash* hash, unsigned windowsize) {1486unsigned i;1487hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);1488hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);1489hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);14901491hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);1492hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));1493hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);14941495if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) {1496return 83; /*alloc fail*/1497}14981499/*initialize hash table*/1500for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;1501for(i = 0; i != windowsize; ++i) hash->val[i] = -1;1502for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/15031504for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;1505for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/15061507return 0;1508}15091510static void hash_cleanup(Hash* hash) {1511lodepng_free(hash->head);1512lodepng_free(hash->val);1513lodepng_free(hash->chain);15141515lodepng_free(hash->zeros);1516lodepng_free(hash->headz);1517lodepng_free(hash->chainz);1518}1519152015211522static unsigned getHash(const unsigned char* data, size_t size, size_t pos) {1523unsigned result = 0;1524if(pos + 2 < size) {1525/*A simple shift and xor hash is used. Since the data of PNGs is dominated1526by zeroes due to the filters, a better hash does not have a significant1527effect on speed in traversing the chain, and causes more time spend on1528calculating the hash.*/1529result ^= ((unsigned)data[pos + 0] << 0u);1530result ^= ((unsigned)data[pos + 1] << 4u);1531result ^= ((unsigned)data[pos + 2] << 8u);1532} else {1533size_t amount, i;1534if(pos >= size) return 0;1535amount = size - pos;1536for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u));1537}1538return result & HASH_BIT_MASK;1539}15401541static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) {1542const unsigned char* start = data + pos;1543const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;1544if(end > data + size) end = data + size;1545data = start;1546while(data != end && *data == 0) ++data;1547/*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/1548return (unsigned)(data - start);1549}15501551/*wpos = pos & (windowsize - 1)*/1552static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) {1553hash->val[wpos] = (int)hashval;1554if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];1555hash->head[hashval] = (int)wpos;15561557hash->zeros[wpos] = numzeros;1558if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];1559hash->headz[numzeros] = (int)wpos;1560}15611562/*1563LZ77-encode the data. Return value is error code. The input are raw bytes, the output1564is in the form of unsigned integers with codes representing for example literal bytes, or1565length/distance pairs.1566It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a1567sliding window (of windowsize) is used, and all past bytes in that window can be used as1568the "dictionary". A brute force search through all possible distances would be slow, and1569this hash technique is one out of several ways to speed this up.1570*/1571static unsigned encodeLZ77(uivector* out, Hash* hash,1572const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,1573unsigned minmatch, unsigned nicematch, unsigned lazymatching) {1574size_t pos;1575unsigned i, error = 0;1576/*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/1577unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u;1578unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;15791580unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/1581unsigned numzeros = 0;15821583unsigned offset; /*the offset represents the distance in LZ77 terminology*/1584unsigned length;1585unsigned lazy = 0;1586unsigned lazylength = 0, lazyoffset = 0;1587unsigned hashval;1588unsigned current_offset, current_length;1589unsigned prev_offset;1590const unsigned char *lastptr, *foreptr, *backptr;1591unsigned hashpos;15921593if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/1594if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/15951596if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;15971598for(pos = inpos; pos < insize; ++pos) {1599size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/1600unsigned chainlength = 0;16011602hashval = getHash(in, insize, pos);16031604if(usezeros && hashval == 0) {1605if(numzeros == 0) numzeros = countZeros(in, insize, pos);1606else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;1607} else {1608numzeros = 0;1609}16101611updateHashChain(hash, wpos, hashval, numzeros);16121613/*the length and offset found for the current position*/1614length = 0;1615offset = 0;16161617hashpos = hash->chain[wpos];16181619lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];16201621/*search for the longest string*/1622prev_offset = 0;1623for(;;) {1624if(chainlength++ >= maxchainlength) break;1625current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);16261627if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/1628prev_offset = current_offset;1629if(current_offset > 0) {1630/*test the next characters*/1631foreptr = &in[pos];1632backptr = &in[pos - current_offset];16331634/*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/1635if(numzeros >= 3) {1636unsigned skip = hash->zeros[hashpos];1637if(skip > numzeros) skip = numzeros;1638backptr += skip;1639foreptr += skip;1640}16411642while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ {1643++backptr;1644++foreptr;1645}1646current_length = (unsigned)(foreptr - &in[pos]);16471648if(current_length > length) {1649length = current_length; /*the longest length*/1650offset = current_offset; /*the offset that is related to this longest length*/1651/*jump out once a length of max length is found (speed gain). This also jumps1652out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/1653if(current_length >= nicematch) break;1654}1655}16561657if(hashpos == hash->chain[hashpos]) break;16581659if(numzeros >= 3 && length > numzeros) {1660hashpos = hash->chainz[hashpos];1661if(hash->zeros[hashpos] != numzeros) break;1662} else {1663hashpos = hash->chain[hashpos];1664/*outdated hash value, happens if particular value was not encountered in whole last window*/1665if(hash->val[hashpos] != (int)hashval) break;1666}1667}16681669if(lazymatching) {1670if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {1671lazy = 1;1672lazylength = length;1673lazyoffset = offset;1674continue; /*try the next byte*/1675}1676if(lazy) {1677lazy = 0;1678if(pos == 0) ERROR_BREAK(81);1679if(length > lazylength + 1) {1680/*push the previous character as literal*/1681if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);1682} else {1683length = lazylength;1684offset = lazyoffset;1685hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/1686hash->headz[numzeros] = -1; /*idem*/1687--pos;1688}1689}1690}1691if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);16921693/*encode it as length/distance pair or literal value*/1694if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ {1695if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);1696} else if(length < minmatch || (length == 3 && offset > 4096)) {1697/*compensate for the fact that longer offsets have more extra bits, a1698length of only 3 may be not worth it then*/1699if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);1700} else {1701addLengthDistance(out, length, offset);1702for(i = 1; i < length; ++i) {1703++pos;1704wpos = pos & (windowsize - 1);1705hashval = getHash(in, insize, pos);1706if(usezeros && hashval == 0) {1707if(numzeros == 0) numzeros = countZeros(in, insize, pos);1708else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;1709} else {1710numzeros = 0;1711}1712updateHashChain(hash, wpos, hashval, numzeros);1713}1714}1715} /*end of the loop through each character of input*/17161717return error;1718}17191720/* /////////////////////////////////////////////////////////////////////////// */17211722static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) {1723/*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,17242 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/17251726size_t i, numdeflateblocks = (datasize + 65534u) / 65535u;1727size_t datapos = 0;1728for(i = 0; i != numdeflateblocks; ++i) {1729unsigned BFINAL, BTYPE, LEN, NLEN;1730unsigned char firstbyte;1731size_t pos = out->size;17321733BFINAL = (i == numdeflateblocks - 1);1734BTYPE = 0;17351736LEN = 65535;1737if(datasize - datapos < 65535u) LEN = (unsigned)datasize - (unsigned)datapos;1738NLEN = 65535 - LEN;17391740if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/17411742firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u));1743out->data[pos + 0] = firstbyte;1744out->data[pos + 1] = (unsigned char)(LEN & 255);1745out->data[pos + 2] = (unsigned char)(LEN >> 8u);1746out->data[pos + 3] = (unsigned char)(NLEN & 255);1747out->data[pos + 4] = (unsigned char)(NLEN >> 8u);1748lodepng_memcpy(out->data + pos + 5, data + datapos, LEN);1749datapos += LEN;1750}17511752return 0;1753}17541755/*1756write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.1757tree_ll: the tree for lit and len codes.1758tree_d: the tree for distance codes.1759*/1760static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded,1761const HuffmanTree* tree_ll, const HuffmanTree* tree_d) {1762size_t i = 0;1763for(i = 0; i != lz77_encoded->size; ++i) {1764unsigned val = lz77_encoded->data[i];1765writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[val]);1766if(val > 256) /*for a length code, 3 more things have to be added*/ {1767unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;1768unsigned n_length_extra_bits = LENGTHEXTRA[length_index];1769unsigned length_extra_bits = lz77_encoded->data[++i];17701771unsigned distance_code = lz77_encoded->data[++i];17721773unsigned distance_index = distance_code;1774unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];1775unsigned distance_extra_bits = lz77_encoded->data[++i];17761777writeBits(writer, length_extra_bits, n_length_extra_bits);1778writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]);1779writeBits(writer, distance_extra_bits, n_distance_extra_bits);1780}1781}1782}17831784/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/1785static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash,1786const unsigned char* data, size_t datapos, size_t dataend,1787const LodePNGCompressSettings* settings, unsigned final) {1788unsigned error = 0;17891790/*1791A block is compressed as follows: The PNG data is lz77 encoded, resulting in1792literal bytes and length/distance pairs. This is then huffman compressed with1793two huffman trees. One huffman tree is used for the lit and len values ("ll"),1794another huffman tree is used for the dist values ("d"). These two trees are1795stored using their code lengths, and to compress even more these code lengths1796are also run-length encoded and huffman compressed. This gives a huffman tree1797of code lengths "cl". The code lengths used to describe this third tree are1798the code length code lengths ("clcl").1799*/18001801/*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/1802uivector lz77_encoded;1803HuffmanTree tree_ll; /*tree for lit,len values*/1804HuffmanTree tree_d; /*tree for distance codes*/1805HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/1806unsigned* frequencies_ll = 0; /*frequency of lit,len codes*/1807unsigned* frequencies_d = 0; /*frequency of dist codes*/1808unsigned* frequencies_cl = 0; /*frequency of code length codes*/1809unsigned* bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/1810unsigned* bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/1811size_t datasize = dataend - datapos;18121813/*1814If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent1815tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are1816some analogies:1817bitlen_lld is to tree_cl what data is to tree_ll and tree_d.1818bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.1819bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.1820*/18211822unsigned BFINAL = final;1823size_t i;1824size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl;1825unsigned HLIT, HDIST, HCLEN;18261827uivector_init(&lz77_encoded);1828HuffmanTree_init(&tree_ll);1829HuffmanTree_init(&tree_d);1830HuffmanTree_init(&tree_cl);1831/* could fit on stack, but >1KB is on the larger side so allocate instead */1832frequencies_ll = (unsigned*)lodepng_malloc(286 * sizeof(*frequencies_ll));1833frequencies_d = (unsigned*)lodepng_malloc(30 * sizeof(*frequencies_d));1834frequencies_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));18351836if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/18371838/*This while loop never loops due to a break at the end, it is here to1839allow breaking out of it to the cleanup phase on error conditions.*/1840while(!error) {1841lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll));1842lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d));1843lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));18441845if(settings->use_lz77) {1846error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,1847settings->minmatch, settings->nicematch, settings->lazymatching);1848if(error) break;1849} else {1850if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);1851for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/1852}18531854/*Count the frequencies of lit, len and dist codes*/1855for(i = 0; i != lz77_encoded.size; ++i) {1856unsigned symbol = lz77_encoded.data[i];1857++frequencies_ll[symbol];1858if(symbol > 256) {1859unsigned dist = lz77_encoded.data[i + 2];1860++frequencies_d[dist];1861i += 3;1862}1863}1864frequencies_ll[256] = 1; /*there will be exactly 1 end code, at the end of the block*/18651866/*Make both huffman trees, one for the lit and len codes, one for the dist codes*/1867error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll, 257, 286, 15);1868if(error) break;1869/*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/1870error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d, 2, 30, 15);1871if(error) break;18721873numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286);1874numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30);1875/*store the code lengths of both generated trees in bitlen_lld*/1876numcodes_lld = numcodes_ll + numcodes_d;1877bitlen_lld = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld));1878/*numcodes_lld_e never needs more size than bitlen_lld*/1879bitlen_lld_e = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e));1880if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/1881numcodes_lld_e = 0;18821883for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i];1884for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[i];18851886/*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),188717 (3-10 zeroes), 18 (11-138 zeroes)*/1888for(i = 0; i != numcodes_lld; ++i) {1889unsigned j = 0; /*amount of repetitions*/1890while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j;18911892if(bitlen_lld[i] == 0 && j >= 2) /*repeat code for zeroes*/ {1893++j; /*include the first zero*/1894if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ {1895bitlen_lld_e[numcodes_lld_e++] = 17;1896bitlen_lld_e[numcodes_lld_e++] = j - 3;1897} else /*repeat code 18 supports max 138 zeroes*/ {1898if(j > 138) j = 138;1899bitlen_lld_e[numcodes_lld_e++] = 18;1900bitlen_lld_e[numcodes_lld_e++] = j - 11;1901}1902i += (j - 1);1903} else if(j >= 3) /*repeat code for value other than zero*/ {1904size_t k;1905unsigned num = j / 6u, rest = j % 6u;1906bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];1907for(k = 0; k < num; ++k) {1908bitlen_lld_e[numcodes_lld_e++] = 16;1909bitlen_lld_e[numcodes_lld_e++] = 6 - 3;1910}1911if(rest >= 3) {1912bitlen_lld_e[numcodes_lld_e++] = 16;1913bitlen_lld_e[numcodes_lld_e++] = rest - 3;1914}1915else j -= rest;1916i += j;1917} else /*too short to benefit from repeat code*/ {1918bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];1919}1920}19211922/*generate tree_cl, the huffmantree of huffmantrees*/1923for(i = 0; i != numcodes_lld_e; ++i) {1924++frequencies_cl[bitlen_lld_e[i]];1925/*after a repeat code come the bits that specify the number of repetitions,1926those don't need to be in the frequencies_cl calculation*/1927if(bitlen_lld_e[i] >= 16) ++i;1928}19291930error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl,1931NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7);1932if(error) break;19331934/*compute amount of code-length-code-lengths to output*/1935numcodes_cl = NUM_CODE_LENGTH_CODES;1936/*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/1937while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) {1938numcodes_cl--;1939}19401941/*1942Write everything into the output19431944After the BFINAL and BTYPE, the dynamic block consists out of the following:1945- 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN1946- (HCLEN+4)*3 bits code lengths of code length alphabet1947- HLIT + 257 code lengths of lit/length alphabet (encoded using the code length1948alphabet, + possible repetition codes 16, 17, 18)1949- HDIST + 1 code lengths of distance alphabet (encoded using the code length1950alphabet, + possible repetition codes 16, 17, 18)1951- compressed data1952- 256 (end code)1953*/19541955/*Write block type*/1956writeBits(writer, BFINAL, 1);1957writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/1958writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/19591960/*write the HLIT, HDIST and HCLEN values*/1961/*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies1962or in the loop for numcodes_cl above, which saves space. */1963HLIT = (unsigned)(numcodes_ll - 257);1964HDIST = (unsigned)(numcodes_d - 1);1965HCLEN = (unsigned)(numcodes_cl - 4);1966writeBits(writer, HLIT, 5);1967writeBits(writer, HDIST, 5);1968writeBits(writer, HCLEN, 4);19691970/*write the code lengths of the code length alphabet ("bitlen_cl")*/1971for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3);19721973/*write the lengths of the lit/len AND the dist alphabet*/1974for(i = 0; i != numcodes_lld_e; ++i) {1975writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]);1976/*extra bits of repeat codes*/1977if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2);1978else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3);1979else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7);1980}19811982/*write the compressed data symbols*/1983writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);1984/*error: the length of the end code 256 must be larger than 0*/1985if(tree_ll.lengths[256] == 0) ERROR_BREAK(64);19861987/*write the end code*/1988writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]);19891990break; /*end of error-while*/1991}19921993/*cleanup*/1994uivector_cleanup(&lz77_encoded);1995HuffmanTree_cleanup(&tree_ll);1996HuffmanTree_cleanup(&tree_d);1997HuffmanTree_cleanup(&tree_cl);1998lodepng_free(frequencies_ll);1999lodepng_free(frequencies_d);2000lodepng_free(frequencies_cl);2001lodepng_free(bitlen_lld);2002lodepng_free(bitlen_lld_e);20032004return error;2005}20062007static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash,2008const unsigned char* data,2009size_t datapos, size_t dataend,2010const LodePNGCompressSettings* settings, unsigned final) {2011HuffmanTree tree_ll; /*tree for literal values and length codes*/2012HuffmanTree tree_d; /*tree for distance codes*/20132014unsigned BFINAL = final;2015unsigned error = 0;2016size_t i;20172018HuffmanTree_init(&tree_ll);2019HuffmanTree_init(&tree_d);20202021error = generateFixedLitLenTree(&tree_ll);2022if(!error) error = generateFixedDistanceTree(&tree_d);20232024if(!error) {2025writeBits(writer, BFINAL, 1);2026writeBits(writer, 1, 1); /*first bit of BTYPE*/2027writeBits(writer, 0, 1); /*second bit of BTYPE*/20282029if(settings->use_lz77) /*LZ77 encoded*/ {2030uivector lz77_encoded;2031uivector_init(&lz77_encoded);2032error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,2033settings->minmatch, settings->nicematch, settings->lazymatching);2034if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);2035uivector_cleanup(&lz77_encoded);2036} else /*no LZ77, but still will be Huffman compressed*/ {2037for(i = datapos; i < dataend; ++i) {2038writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]);2039}2040}2041/*add END code*/2042if(!error) writeBitsReversed(writer,tree_ll.codes[256], tree_ll.lengths[256]);2043}20442045/*cleanup*/2046HuffmanTree_cleanup(&tree_ll);2047HuffmanTree_cleanup(&tree_d);20482049return error;2050}20512052static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,2053const LodePNGCompressSettings* settings) {2054unsigned error = 0;2055size_t i, blocksize, numdeflateblocks;2056Hash hash;2057LodePNGBitWriter writer;20582059LodePNGBitWriter_init(&writer, out);20602061if(settings->btype > 2) return 61;2062else if(settings->btype == 0) return deflateNoCompression(out, in, insize);2063else if(settings->btype == 1) blocksize = insize;2064else /*if(settings->btype == 2)*/ {2065/*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/2066blocksize = insize / 8u + 8;2067if(blocksize < 65536) blocksize = 65536;2068if(blocksize > 262144) blocksize = 262144;2069}20702071numdeflateblocks = (insize + blocksize - 1) / blocksize;2072if(numdeflateblocks == 0) numdeflateblocks = 1;20732074error = hash_init(&hash, settings->windowsize);20752076if(!error) {2077for(i = 0; i != numdeflateblocks && !error; ++i) {2078unsigned final = (i == numdeflateblocks - 1);2079size_t start = i * blocksize;2080size_t end = start + blocksize;2081if(end > insize) end = insize;20822083if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final);2084else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final);2085}2086}20872088hash_cleanup(&hash);20892090return error;2091}20922093unsigned lodepng_deflate(unsigned char** out, size_t* outsize,2094const unsigned char* in, size_t insize,2095const LodePNGCompressSettings* settings) {2096ucvector v = ucvector_init(*out, *outsize);2097unsigned error = lodepng_deflatev(&v, in, insize, settings);2098*out = v.data;2099*outsize = v.size;2100return error;2101}21022103static unsigned deflate(unsigned char** out, size_t* outsize,2104const unsigned char* in, size_t insize,2105const LodePNGCompressSettings* settings) {2106if(settings->custom_deflate) {2107unsigned error = settings->custom_deflate(out, outsize, in, insize, settings);2108/*the custom deflate is allowed to have its own error codes, however, we translate it to code 111*/2109return error ? 111 : 0;2110} else {2111return lodepng_deflate(out, outsize, in, insize, settings);2112}2113}21142115#endif /*LODEPNG_COMPILE_DECODER*/21162117/* ////////////////////////////////////////////////////////////////////////// */2118/* / Adler32 / */2119/* ////////////////////////////////////////////////////////////////////////// */21202121static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) {2122unsigned s1 = adler & 0xffffu;2123unsigned s2 = (adler >> 16u) & 0xffffu;21242125while(len != 0u) {2126unsigned i;2127/*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/2128unsigned amount = len > 5552u ? 5552u : len;2129len -= amount;2130for(i = 0; i != amount; ++i) {2131s1 += (*data++);2132s2 += s1;2133}2134s1 %= 65521u;2135s2 %= 65521u;2136}21372138return (s2 << 16u) | s1;2139}21402141/*Return the adler32 of the bytes data[0..len-1]*/2142static unsigned adler32(const unsigned char* data, unsigned len) {2143return update_adler32(1u, data, len);2144}21452146/* ////////////////////////////////////////////////////////////////////////// */2147/* / Zlib / */2148/* ////////////////////////////////////////////////////////////////////////// */21492150#ifdef LODEPNG_COMPILE_DECODER21512152static unsigned lodepng_zlib_decompressv(ucvector* out,2153const unsigned char* in, size_t insize,2154const LodePNGDecompressSettings* settings) {2155unsigned error = 0;2156unsigned CM, CINFO, FDICT;21572158if(insize < 2) return 53; /*error, size of zlib data too small*/2159/*read information from zlib header*/2160if((in[0] * 256 + in[1]) % 31 != 0) {2161/*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/2162return 24;2163}21642165CM = in[0] & 15;2166CINFO = (in[0] >> 4) & 15;2167/*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/2168FDICT = (in[1] >> 5) & 1;2169/*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/21702171if(CM != 8 || CINFO > 7) {2172/*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/2173return 25;2174}2175if(FDICT != 0) {2176/*error: the specification of PNG says about the zlib stream:2177"The additional flags shall not specify a preset dictionary."*/2178return 26;2179}21802181error = inflatev(out, in + 2, insize - 2, settings);2182if(error) return error;21832184if(!settings->ignore_adler32) {2185unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);2186unsigned checksum = adler32(out->data, (unsigned)(out->size));2187if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/2188}21892190return 0; /*no error*/2191}219221932194unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,2195size_t insize, const LodePNGDecompressSettings* settings) {2196ucvector v = ucvector_init(*out, *outsize);2197unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings);2198*out = v.data;2199*outsize = v.size;2200return error;2201}22022203/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */2204static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size,2205const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) {2206unsigned error;2207if(settings->custom_zlib) {2208error = settings->custom_zlib(out, outsize, in, insize, settings);2209if(error) {2210/*the custom zlib is allowed to have its own error codes, however, we translate it to code 110*/2211error = 110;2212/*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/2213if(settings->max_output_size && *outsize > settings->max_output_size) error = 109;2214}2215} else {2216ucvector v = ucvector_init(*out, *outsize);2217if(expected_size) {2218/*reserve the memory to avoid intermediate reallocations*/2219ucvector_resize(&v, *outsize + expected_size);2220v.size = *outsize;2221}2222error = lodepng_zlib_decompressv(&v, in, insize, settings);2223*out = v.data;2224*outsize = v.size;2225}2226return error;2227}22282229#endif /*LODEPNG_COMPILE_DECODER*/22302231#ifdef LODEPNG_COMPILE_ENCODER22322233unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,2234size_t insize, const LodePNGCompressSettings* settings) {2235size_t i;2236unsigned error;2237unsigned char* deflatedata = 0;2238size_t deflatesize = 0;22392240error = deflate(&deflatedata, &deflatesize, in, insize, settings);22412242*out = NULL;2243*outsize = 0;2244if(!error) {2245*outsize = deflatesize + 6;2246*out = (unsigned char*)lodepng_malloc(*outsize);2247if(!*out) error = 83; /*alloc fail*/2248}22492250if(!error) {2251unsigned ADLER32 = adler32(in, (unsigned)insize);2252/*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/2253unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/2254unsigned FLEVEL = 0;2255unsigned FDICT = 0;2256unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;2257unsigned FCHECK = 31 - CMFFLG % 31;2258CMFFLG += FCHECK;22592260(*out)[0] = (unsigned char)(CMFFLG >> 8);2261(*out)[1] = (unsigned char)(CMFFLG & 255);2262for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i];2263lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32);2264}22652266lodepng_free(deflatedata);2267return error;2268}22692270/* compress using the default or custom zlib function */2271static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,2272size_t insize, const LodePNGCompressSettings* settings) {2273if(settings->custom_zlib) {2274unsigned error = settings->custom_zlib(out, outsize, in, insize, settings);2275/*the custom zlib is allowed to have its own error codes, however, we translate it to code 111*/2276return error ? 111 : 0;2277} else {2278return lodepng_zlib_compress(out, outsize, in, insize, settings);2279}2280}22812282#endif /*LODEPNG_COMPILE_ENCODER*/22832284#else /*no LODEPNG_COMPILE_ZLIB*/22852286#ifdef LODEPNG_COMPILE_DECODER2287static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size,2288const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) {2289if(!settings->custom_zlib) return 87; /*no custom zlib function provided */2290(void)expected_size;2291return settings->custom_zlib(out, outsize, in, insize, settings);2292}2293#endif /*LODEPNG_COMPILE_DECODER*/2294#ifdef LODEPNG_COMPILE_ENCODER2295static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,2296size_t insize, const LodePNGCompressSettings* settings) {2297if(!settings->custom_zlib) return 87; /*no custom zlib function provided */2298return settings->custom_zlib(out, outsize, in, insize, settings);2299}2300#endif /*LODEPNG_COMPILE_ENCODER*/23012302#endif /*LODEPNG_COMPILE_ZLIB*/23032304/* ////////////////////////////////////////////////////////////////////////// */23052306#ifdef LODEPNG_COMPILE_ENCODER23072308/*this is a good tradeoff between speed and compression ratio*/2309#define DEFAULT_WINDOWSIZE 204823102311void lodepng_compress_settings_init(LodePNGCompressSettings* settings) {2312/*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/2313settings->btype = 2;2314settings->use_lz77 = 1;2315settings->windowsize = DEFAULT_WINDOWSIZE;2316settings->minmatch = 3;2317settings->nicematch = 128;2318settings->lazymatching = 1;23192320settings->custom_zlib = 0;2321settings->custom_deflate = 0;2322settings->custom_context = 0;2323}23242325const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};232623272328#endif /*LODEPNG_COMPILE_ENCODER*/23292330#ifdef LODEPNG_COMPILE_DECODER23312332void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) {2333settings->ignore_adler32 = 0;2334settings->ignore_nlen = 0;2335settings->max_output_size = 0;23362337settings->custom_zlib = 0;2338settings->custom_inflate = 0;2339settings->custom_context = 0;2340}23412342const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0, 0};23432344#endif /*LODEPNG_COMPILE_DECODER*/23452346/* ////////////////////////////////////////////////////////////////////////// */2347/* ////////////////////////////////////////////////////////////////////////// */2348/* // End of Zlib related code. Begin of PNG related code. // */2349/* ////////////////////////////////////////////////////////////////////////// */2350/* ////////////////////////////////////////////////////////////////////////// */23512352#ifdef LODEPNG_COMPILE_PNG23532354/* ////////////////////////////////////////////////////////////////////////// */2355/* / CRC32 / */2356/* ////////////////////////////////////////////////////////////////////////// */235723582359#ifdef LODEPNG_COMPILE_CRC23602361static const unsigned lodepng_crc32_table0[256] = {23620x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u,23630x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u,23640x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u,23650x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u,23660x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu,23670x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u,23680x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu,23690x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du,23700x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u,23710x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u,23720x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u,23730x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u,23740x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu,23750x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u,23760x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu,23770x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu,23780xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u,23790xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u,23800xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u,23810xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u,23820xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu,23830xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u,23840xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu,23850xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du,23860x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u,23870x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u,23880x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u,23890x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u,23900xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu,23910xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u,23920xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu,23930xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du2394};23952396static const unsigned lodepng_crc32_table1[256] = {23970x00000000u, 0x191b3141u, 0x32366282u, 0x2b2d53c3u, 0x646cc504u, 0x7d77f445u, 0x565aa786u, 0x4f4196c7u,23980xc8d98a08u, 0xd1c2bb49u, 0xfaefe88au, 0xe3f4d9cbu, 0xacb54f0cu, 0xb5ae7e4du, 0x9e832d8eu, 0x87981ccfu,23990x4ac21251u, 0x53d92310u, 0x78f470d3u, 0x61ef4192u, 0x2eaed755u, 0x37b5e614u, 0x1c98b5d7u, 0x05838496u,24000x821b9859u, 0x9b00a918u, 0xb02dfadbu, 0xa936cb9au, 0xe6775d5du, 0xff6c6c1cu, 0xd4413fdfu, 0xcd5a0e9eu,24010x958424a2u, 0x8c9f15e3u, 0xa7b24620u, 0xbea97761u, 0xf1e8e1a6u, 0xe8f3d0e7u, 0xc3de8324u, 0xdac5b265u,24020x5d5daeaau, 0x44469febu, 0x6f6bcc28u, 0x7670fd69u, 0x39316baeu, 0x202a5aefu, 0x0b07092cu, 0x121c386du,24030xdf4636f3u, 0xc65d07b2u, 0xed705471u, 0xf46b6530u, 0xbb2af3f7u, 0xa231c2b6u, 0x891c9175u, 0x9007a034u,24040x179fbcfbu, 0x0e848dbau, 0x25a9de79u, 0x3cb2ef38u, 0x73f379ffu, 0x6ae848beu, 0x41c51b7du, 0x58de2a3cu,24050xf0794f05u, 0xe9627e44u, 0xc24f2d87u, 0xdb541cc6u, 0x94158a01u, 0x8d0ebb40u, 0xa623e883u, 0xbf38d9c2u,24060x38a0c50du, 0x21bbf44cu, 0x0a96a78fu, 0x138d96ceu, 0x5ccc0009u, 0x45d73148u, 0x6efa628bu, 0x77e153cau,24070xbabb5d54u, 0xa3a06c15u, 0x888d3fd6u, 0x91960e97u, 0xded79850u, 0xc7cca911u, 0xece1fad2u, 0xf5facb93u,24080x7262d75cu, 0x6b79e61du, 0x4054b5deu, 0x594f849fu, 0x160e1258u, 0x0f152319u, 0x243870dau, 0x3d23419bu,24090x65fd6ba7u, 0x7ce65ae6u, 0x57cb0925u, 0x4ed03864u, 0x0191aea3u, 0x188a9fe2u, 0x33a7cc21u, 0x2abcfd60u,24100xad24e1afu, 0xb43fd0eeu, 0x9f12832du, 0x8609b26cu, 0xc94824abu, 0xd05315eau, 0xfb7e4629u, 0xe2657768u,24110x2f3f79f6u, 0x362448b7u, 0x1d091b74u, 0x04122a35u, 0x4b53bcf2u, 0x52488db3u, 0x7965de70u, 0x607eef31u,24120xe7e6f3feu, 0xfefdc2bfu, 0xd5d0917cu, 0xcccba03du, 0x838a36fau, 0x9a9107bbu, 0xb1bc5478u, 0xa8a76539u,24130x3b83984bu, 0x2298a90au, 0x09b5fac9u, 0x10aecb88u, 0x5fef5d4fu, 0x46f46c0eu, 0x6dd93fcdu, 0x74c20e8cu,24140xf35a1243u, 0xea412302u, 0xc16c70c1u, 0xd8774180u, 0x9736d747u, 0x8e2de606u, 0xa500b5c5u, 0xbc1b8484u,24150x71418a1au, 0x685abb5bu, 0x4377e898u, 0x5a6cd9d9u, 0x152d4f1eu, 0x0c367e5fu, 0x271b2d9cu, 0x3e001cddu,24160xb9980012u, 0xa0833153u, 0x8bae6290u, 0x92b553d1u, 0xddf4c516u, 0xc4eff457u, 0xefc2a794u, 0xf6d996d5u,24170xae07bce9u, 0xb71c8da8u, 0x9c31de6bu, 0x852aef2au, 0xca6b79edu, 0xd37048acu, 0xf85d1b6fu, 0xe1462a2eu,24180x66de36e1u, 0x7fc507a0u, 0x54e85463u, 0x4df36522u, 0x02b2f3e5u, 0x1ba9c2a4u, 0x30849167u, 0x299fa026u,24190xe4c5aeb8u, 0xfdde9ff9u, 0xd6f3cc3au, 0xcfe8fd7bu, 0x80a96bbcu, 0x99b25afdu, 0xb29f093eu, 0xab84387fu,24200x2c1c24b0u, 0x350715f1u, 0x1e2a4632u, 0x07317773u, 0x4870e1b4u, 0x516bd0f5u, 0x7a468336u, 0x635db277u,24210xcbfad74eu, 0xd2e1e60fu, 0xf9ccb5ccu, 0xe0d7848du, 0xaf96124au, 0xb68d230bu, 0x9da070c8u, 0x84bb4189u,24220x03235d46u, 0x1a386c07u, 0x31153fc4u, 0x280e0e85u, 0x674f9842u, 0x7e54a903u, 0x5579fac0u, 0x4c62cb81u,24230x8138c51fu, 0x9823f45eu, 0xb30ea79du, 0xaa1596dcu, 0xe554001bu, 0xfc4f315au, 0xd7626299u, 0xce7953d8u,24240x49e14f17u, 0x50fa7e56u, 0x7bd72d95u, 0x62cc1cd4u, 0x2d8d8a13u, 0x3496bb52u, 0x1fbbe891u, 0x06a0d9d0u,24250x5e7ef3ecu, 0x4765c2adu, 0x6c48916eu, 0x7553a02fu, 0x3a1236e8u, 0x230907a9u, 0x0824546au, 0x113f652bu,24260x96a779e4u, 0x8fbc48a5u, 0xa4911b66u, 0xbd8a2a27u, 0xf2cbbce0u, 0xebd08da1u, 0xc0fdde62u, 0xd9e6ef23u,24270x14bce1bdu, 0x0da7d0fcu, 0x268a833fu, 0x3f91b27eu, 0x70d024b9u, 0x69cb15f8u, 0x42e6463bu, 0x5bfd777au,24280xdc656bb5u, 0xc57e5af4u, 0xee530937u, 0xf7483876u, 0xb809aeb1u, 0xa1129ff0u, 0x8a3fcc33u, 0x9324fd72u2429};24302431static const unsigned lodepng_crc32_table2[256] = {24320x00000000u, 0x01c26a37u, 0x0384d46eu, 0x0246be59u, 0x0709a8dcu, 0x06cbc2ebu, 0x048d7cb2u, 0x054f1685u,24330x0e1351b8u, 0x0fd13b8fu, 0x0d9785d6u, 0x0c55efe1u, 0x091af964u, 0x08d89353u, 0x0a9e2d0au, 0x0b5c473du,24340x1c26a370u, 0x1de4c947u, 0x1fa2771eu, 0x1e601d29u, 0x1b2f0bacu, 0x1aed619bu, 0x18abdfc2u, 0x1969b5f5u,24350x1235f2c8u, 0x13f798ffu, 0x11b126a6u, 0x10734c91u, 0x153c5a14u, 0x14fe3023u, 0x16b88e7au, 0x177ae44du,24360x384d46e0u, 0x398f2cd7u, 0x3bc9928eu, 0x3a0bf8b9u, 0x3f44ee3cu, 0x3e86840bu, 0x3cc03a52u, 0x3d025065u,24370x365e1758u, 0x379c7d6fu, 0x35dac336u, 0x3418a901u, 0x3157bf84u, 0x3095d5b3u, 0x32d36beau, 0x331101ddu,24380x246be590u, 0x25a98fa7u, 0x27ef31feu, 0x262d5bc9u, 0x23624d4cu, 0x22a0277bu, 0x20e69922u, 0x2124f315u,24390x2a78b428u, 0x2bbade1fu, 0x29fc6046u, 0x283e0a71u, 0x2d711cf4u, 0x2cb376c3u, 0x2ef5c89au, 0x2f37a2adu,24400x709a8dc0u, 0x7158e7f7u, 0x731e59aeu, 0x72dc3399u, 0x7793251cu, 0x76514f2bu, 0x7417f172u, 0x75d59b45u,24410x7e89dc78u, 0x7f4bb64fu, 0x7d0d0816u, 0x7ccf6221u, 0x798074a4u, 0x78421e93u, 0x7a04a0cau, 0x7bc6cafdu,24420x6cbc2eb0u, 0x6d7e4487u, 0x6f38fadeu, 0x6efa90e9u, 0x6bb5866cu, 0x6a77ec5bu, 0x68315202u, 0x69f33835u,24430x62af7f08u, 0x636d153fu, 0x612bab66u, 0x60e9c151u, 0x65a6d7d4u, 0x6464bde3u, 0x662203bau, 0x67e0698du,24440x48d7cb20u, 0x4915a117u, 0x4b531f4eu, 0x4a917579u, 0x4fde63fcu, 0x4e1c09cbu, 0x4c5ab792u, 0x4d98dda5u,24450x46c49a98u, 0x4706f0afu, 0x45404ef6u, 0x448224c1u, 0x41cd3244u, 0x400f5873u, 0x4249e62au, 0x438b8c1du,24460x54f16850u, 0x55330267u, 0x5775bc3eu, 0x56b7d609u, 0x53f8c08cu, 0x523aaabbu, 0x507c14e2u, 0x51be7ed5u,24470x5ae239e8u, 0x5b2053dfu, 0x5966ed86u, 0x58a487b1u, 0x5deb9134u, 0x5c29fb03u, 0x5e6f455au, 0x5fad2f6du,24480xe1351b80u, 0xe0f771b7u, 0xe2b1cfeeu, 0xe373a5d9u, 0xe63cb35cu, 0xe7fed96bu, 0xe5b86732u, 0xe47a0d05u,24490xef264a38u, 0xeee4200fu, 0xeca29e56u, 0xed60f461u, 0xe82fe2e4u, 0xe9ed88d3u, 0xebab368au, 0xea695cbdu,24500xfd13b8f0u, 0xfcd1d2c7u, 0xfe976c9eu, 0xff5506a9u, 0xfa1a102cu, 0xfbd87a1bu, 0xf99ec442u, 0xf85cae75u,24510xf300e948u, 0xf2c2837fu, 0xf0843d26u, 0xf1465711u, 0xf4094194u, 0xf5cb2ba3u, 0xf78d95fau, 0xf64fffcdu,24520xd9785d60u, 0xd8ba3757u, 0xdafc890eu, 0xdb3ee339u, 0xde71f5bcu, 0xdfb39f8bu, 0xddf521d2u, 0xdc374be5u,24530xd76b0cd8u, 0xd6a966efu, 0xd4efd8b6u, 0xd52db281u, 0xd062a404u, 0xd1a0ce33u, 0xd3e6706au, 0xd2241a5du,24540xc55efe10u, 0xc49c9427u, 0xc6da2a7eu, 0xc7184049u, 0xc25756ccu, 0xc3953cfbu, 0xc1d382a2u, 0xc011e895u,24550xcb4dafa8u, 0xca8fc59fu, 0xc8c97bc6u, 0xc90b11f1u, 0xcc440774u, 0xcd866d43u, 0xcfc0d31au, 0xce02b92du,24560x91af9640u, 0x906dfc77u, 0x922b422eu, 0x93e92819u, 0x96a63e9cu, 0x976454abu, 0x9522eaf2u, 0x94e080c5u,24570x9fbcc7f8u, 0x9e7eadcfu, 0x9c381396u, 0x9dfa79a1u, 0x98b56f24u, 0x99770513u, 0x9b31bb4au, 0x9af3d17du,24580x8d893530u, 0x8c4b5f07u, 0x8e0de15eu, 0x8fcf8b69u, 0x8a809decu, 0x8b42f7dbu, 0x89044982u, 0x88c623b5u,24590x839a6488u, 0x82580ebfu, 0x801eb0e6u, 0x81dcdad1u, 0x8493cc54u, 0x8551a663u, 0x8717183au, 0x86d5720du,24600xa9e2d0a0u, 0xa820ba97u, 0xaa6604ceu, 0xaba46ef9u, 0xaeeb787cu, 0xaf29124bu, 0xad6fac12u, 0xacadc625u,24610xa7f18118u, 0xa633eb2fu, 0xa4755576u, 0xa5b73f41u, 0xa0f829c4u, 0xa13a43f3u, 0xa37cfdaau, 0xa2be979du,24620xb5c473d0u, 0xb40619e7u, 0xb640a7beu, 0xb782cd89u, 0xb2cddb0cu, 0xb30fb13bu, 0xb1490f62u, 0xb08b6555u,24630xbbd72268u, 0xba15485fu, 0xb853f606u, 0xb9919c31u, 0xbcde8ab4u, 0xbd1ce083u, 0xbf5a5edau, 0xbe9834edu2464};24652466static const unsigned lodepng_crc32_table3[256] = {24670x00000000u, 0xb8bc6765u, 0xaa09c88bu, 0x12b5afeeu, 0x8f629757u, 0x37def032u, 0x256b5fdcu, 0x9dd738b9u,24680xc5b428efu, 0x7d084f8au, 0x6fbde064u, 0xd7018701u, 0x4ad6bfb8u, 0xf26ad8ddu, 0xe0df7733u, 0x58631056u,24690x5019579fu, 0xe8a530fau, 0xfa109f14u, 0x42acf871u, 0xdf7bc0c8u, 0x67c7a7adu, 0x75720843u, 0xcdce6f26u,24700x95ad7f70u, 0x2d111815u, 0x3fa4b7fbu, 0x8718d09eu, 0x1acfe827u, 0xa2738f42u, 0xb0c620acu, 0x087a47c9u,24710xa032af3eu, 0x188ec85bu, 0x0a3b67b5u, 0xb28700d0u, 0x2f503869u, 0x97ec5f0cu, 0x8559f0e2u, 0x3de59787u,24720x658687d1u, 0xdd3ae0b4u, 0xcf8f4f5au, 0x7733283fu, 0xeae41086u, 0x525877e3u, 0x40edd80du, 0xf851bf68u,24730xf02bf8a1u, 0x48979fc4u, 0x5a22302au, 0xe29e574fu, 0x7f496ff6u, 0xc7f50893u, 0xd540a77du, 0x6dfcc018u,24740x359fd04eu, 0x8d23b72bu, 0x9f9618c5u, 0x272a7fa0u, 0xbafd4719u, 0x0241207cu, 0x10f48f92u, 0xa848e8f7u,24750x9b14583du, 0x23a83f58u, 0x311d90b6u, 0x89a1f7d3u, 0x1476cf6au, 0xaccaa80fu, 0xbe7f07e1u, 0x06c36084u,24760x5ea070d2u, 0xe61c17b7u, 0xf4a9b859u, 0x4c15df3cu, 0xd1c2e785u, 0x697e80e0u, 0x7bcb2f0eu, 0xc377486bu,24770xcb0d0fa2u, 0x73b168c7u, 0x6104c729u, 0xd9b8a04cu, 0x446f98f5u, 0xfcd3ff90u, 0xee66507eu, 0x56da371bu,24780x0eb9274du, 0xb6054028u, 0xa4b0efc6u, 0x1c0c88a3u, 0x81dbb01au, 0x3967d77fu, 0x2bd27891u, 0x936e1ff4u,24790x3b26f703u, 0x839a9066u, 0x912f3f88u, 0x299358edu, 0xb4446054u, 0x0cf80731u, 0x1e4da8dfu, 0xa6f1cfbau,24800xfe92dfecu, 0x462eb889u, 0x549b1767u, 0xec277002u, 0x71f048bbu, 0xc94c2fdeu, 0xdbf98030u, 0x6345e755u,24810x6b3fa09cu, 0xd383c7f9u, 0xc1366817u, 0x798a0f72u, 0xe45d37cbu, 0x5ce150aeu, 0x4e54ff40u, 0xf6e89825u,24820xae8b8873u, 0x1637ef16u, 0x048240f8u, 0xbc3e279du, 0x21e91f24u, 0x99557841u, 0x8be0d7afu, 0x335cb0cau,24830xed59b63bu, 0x55e5d15eu, 0x47507eb0u, 0xffec19d5u, 0x623b216cu, 0xda874609u, 0xc832e9e7u, 0x708e8e82u,24840x28ed9ed4u, 0x9051f9b1u, 0x82e4565fu, 0x3a58313au, 0xa78f0983u, 0x1f336ee6u, 0x0d86c108u, 0xb53aa66du,24850xbd40e1a4u, 0x05fc86c1u, 0x1749292fu, 0xaff54e4au, 0x322276f3u, 0x8a9e1196u, 0x982bbe78u, 0x2097d91du,24860x78f4c94bu, 0xc048ae2eu, 0xd2fd01c0u, 0x6a4166a5u, 0xf7965e1cu, 0x4f2a3979u, 0x5d9f9697u, 0xe523f1f2u,24870x4d6b1905u, 0xf5d77e60u, 0xe762d18eu, 0x5fdeb6ebu, 0xc2098e52u, 0x7ab5e937u, 0x680046d9u, 0xd0bc21bcu,24880x88df31eau, 0x3063568fu, 0x22d6f961u, 0x9a6a9e04u, 0x07bda6bdu, 0xbf01c1d8u, 0xadb46e36u, 0x15080953u,24890x1d724e9au, 0xa5ce29ffu, 0xb77b8611u, 0x0fc7e174u, 0x9210d9cdu, 0x2aacbea8u, 0x38191146u, 0x80a57623u,24900xd8c66675u, 0x607a0110u, 0x72cfaefeu, 0xca73c99bu, 0x57a4f122u, 0xef189647u, 0xfdad39a9u, 0x45115eccu,24910x764dee06u, 0xcef18963u, 0xdc44268du, 0x64f841e8u, 0xf92f7951u, 0x41931e34u, 0x5326b1dau, 0xeb9ad6bfu,24920xb3f9c6e9u, 0x0b45a18cu, 0x19f00e62u, 0xa14c6907u, 0x3c9b51beu, 0x842736dbu, 0x96929935u, 0x2e2efe50u,24930x2654b999u, 0x9ee8defcu, 0x8c5d7112u, 0x34e11677u, 0xa9362eceu, 0x118a49abu, 0x033fe645u, 0xbb838120u,24940xe3e09176u, 0x5b5cf613u, 0x49e959fdu, 0xf1553e98u, 0x6c820621u, 0xd43e6144u, 0xc68bceaau, 0x7e37a9cfu,24950xd67f4138u, 0x6ec3265du, 0x7c7689b3u, 0xc4caeed6u, 0x591dd66fu, 0xe1a1b10au, 0xf3141ee4u, 0x4ba87981u,24960x13cb69d7u, 0xab770eb2u, 0xb9c2a15cu, 0x017ec639u, 0x9ca9fe80u, 0x241599e5u, 0x36a0360bu, 0x8e1c516eu,24970x866616a7u, 0x3eda71c2u, 0x2c6fde2cu, 0x94d3b949u, 0x090481f0u, 0xb1b8e695u, 0xa30d497bu, 0x1bb12e1eu,24980x43d23e48u, 0xfb6e592du, 0xe9dbf6c3u, 0x516791a6u, 0xccb0a91fu, 0x740cce7au, 0x66b96194u, 0xde0506f1u2499};25002501static const unsigned lodepng_crc32_table4[256] = {25020x00000000u, 0x3d6029b0u, 0x7ac05360u, 0x47a07ad0u, 0xf580a6c0u, 0xc8e08f70u, 0x8f40f5a0u, 0xb220dc10u,25030x30704bc1u, 0x0d106271u, 0x4ab018a1u, 0x77d03111u, 0xc5f0ed01u, 0xf890c4b1u, 0xbf30be61u, 0x825097d1u,25040x60e09782u, 0x5d80be32u, 0x1a20c4e2u, 0x2740ed52u, 0x95603142u, 0xa80018f2u, 0xefa06222u, 0xd2c04b92u,25050x5090dc43u, 0x6df0f5f3u, 0x2a508f23u, 0x1730a693u, 0xa5107a83u, 0x98705333u, 0xdfd029e3u, 0xe2b00053u,25060xc1c12f04u, 0xfca106b4u, 0xbb017c64u, 0x866155d4u, 0x344189c4u, 0x0921a074u, 0x4e81daa4u, 0x73e1f314u,25070xf1b164c5u, 0xccd14d75u, 0x8b7137a5u, 0xb6111e15u, 0x0431c205u, 0x3951ebb5u, 0x7ef19165u, 0x4391b8d5u,25080xa121b886u, 0x9c419136u, 0xdbe1ebe6u, 0xe681c256u, 0x54a11e46u, 0x69c137f6u, 0x2e614d26u, 0x13016496u,25090x9151f347u, 0xac31daf7u, 0xeb91a027u, 0xd6f18997u, 0x64d15587u, 0x59b17c37u, 0x1e1106e7u, 0x23712f57u,25100x58f35849u, 0x659371f9u, 0x22330b29u, 0x1f532299u, 0xad73fe89u, 0x9013d739u, 0xd7b3ade9u, 0xead38459u,25110x68831388u, 0x55e33a38u, 0x124340e8u, 0x2f236958u, 0x9d03b548u, 0xa0639cf8u, 0xe7c3e628u, 0xdaa3cf98u,25120x3813cfcbu, 0x0573e67bu, 0x42d39cabu, 0x7fb3b51bu, 0xcd93690bu, 0xf0f340bbu, 0xb7533a6bu, 0x8a3313dbu,25130x0863840au, 0x3503adbau, 0x72a3d76au, 0x4fc3fedau, 0xfde322cau, 0xc0830b7au, 0x872371aau, 0xba43581au,25140x9932774du, 0xa4525efdu, 0xe3f2242du, 0xde920d9du, 0x6cb2d18du, 0x51d2f83du, 0x167282edu, 0x2b12ab5du,25150xa9423c8cu, 0x9422153cu, 0xd3826fecu, 0xeee2465cu, 0x5cc29a4cu, 0x61a2b3fcu, 0x2602c92cu, 0x1b62e09cu,25160xf9d2e0cfu, 0xc4b2c97fu, 0x8312b3afu, 0xbe729a1fu, 0x0c52460fu, 0x31326fbfu, 0x7692156fu, 0x4bf23cdfu,25170xc9a2ab0eu, 0xf4c282beu, 0xb362f86eu, 0x8e02d1deu, 0x3c220dceu, 0x0142247eu, 0x46e25eaeu, 0x7b82771eu,25180xb1e6b092u, 0x8c869922u, 0xcb26e3f2u, 0xf646ca42u, 0x44661652u, 0x79063fe2u, 0x3ea64532u, 0x03c66c82u,25190x8196fb53u, 0xbcf6d2e3u, 0xfb56a833u, 0xc6368183u, 0x74165d93u, 0x49767423u, 0x0ed60ef3u, 0x33b62743u,25200xd1062710u, 0xec660ea0u, 0xabc67470u, 0x96a65dc0u, 0x248681d0u, 0x19e6a860u, 0x5e46d2b0u, 0x6326fb00u,25210xe1766cd1u, 0xdc164561u, 0x9bb63fb1u, 0xa6d61601u, 0x14f6ca11u, 0x2996e3a1u, 0x6e369971u, 0x5356b0c1u,25220x70279f96u, 0x4d47b626u, 0x0ae7ccf6u, 0x3787e546u, 0x85a73956u, 0xb8c710e6u, 0xff676a36u, 0xc2074386u,25230x4057d457u, 0x7d37fde7u, 0x3a978737u, 0x07f7ae87u, 0xb5d77297u, 0x88b75b27u, 0xcf1721f7u, 0xf2770847u,25240x10c70814u, 0x2da721a4u, 0x6a075b74u, 0x576772c4u, 0xe547aed4u, 0xd8278764u, 0x9f87fdb4u, 0xa2e7d404u,25250x20b743d5u, 0x1dd76a65u, 0x5a7710b5u, 0x67173905u, 0xd537e515u, 0xe857cca5u, 0xaff7b675u, 0x92979fc5u,25260xe915e8dbu, 0xd475c16bu, 0x93d5bbbbu, 0xaeb5920bu, 0x1c954e1bu, 0x21f567abu, 0x66551d7bu, 0x5b3534cbu,25270xd965a31au, 0xe4058aaau, 0xa3a5f07au, 0x9ec5d9cau, 0x2ce505dau, 0x11852c6au, 0x562556bau, 0x6b457f0au,25280x89f57f59u, 0xb49556e9u, 0xf3352c39u, 0xce550589u, 0x7c75d999u, 0x4115f029u, 0x06b58af9u, 0x3bd5a349u,25290xb9853498u, 0x84e51d28u, 0xc34567f8u, 0xfe254e48u, 0x4c059258u, 0x7165bbe8u, 0x36c5c138u, 0x0ba5e888u,25300x28d4c7dfu, 0x15b4ee6fu, 0x521494bfu, 0x6f74bd0fu, 0xdd54611fu, 0xe03448afu, 0xa794327fu, 0x9af41bcfu,25310x18a48c1eu, 0x25c4a5aeu, 0x6264df7eu, 0x5f04f6ceu, 0xed242adeu, 0xd044036eu, 0x97e479beu, 0xaa84500eu,25320x4834505du, 0x755479edu, 0x32f4033du, 0x0f942a8du, 0xbdb4f69du, 0x80d4df2du, 0xc774a5fdu, 0xfa148c4du,25330x78441b9cu, 0x4524322cu, 0x028448fcu, 0x3fe4614cu, 0x8dc4bd5cu, 0xb0a494ecu, 0xf704ee3cu, 0xca64c78cu2534};25352536static const unsigned lodepng_crc32_table5[256] = {25370x00000000u, 0xcb5cd3a5u, 0x4dc8a10bu, 0x869472aeu, 0x9b914216u, 0x50cd91b3u, 0xd659e31du, 0x1d0530b8u,25380xec53826du, 0x270f51c8u, 0xa19b2366u, 0x6ac7f0c3u, 0x77c2c07bu, 0xbc9e13deu, 0x3a0a6170u, 0xf156b2d5u,25390x03d6029bu, 0xc88ad13eu, 0x4e1ea390u, 0x85427035u, 0x9847408du, 0x531b9328u, 0xd58fe186u, 0x1ed33223u,25400xef8580f6u, 0x24d95353u, 0xa24d21fdu, 0x6911f258u, 0x7414c2e0u, 0xbf481145u, 0x39dc63ebu, 0xf280b04eu,25410x07ac0536u, 0xccf0d693u, 0x4a64a43du, 0x81387798u, 0x9c3d4720u, 0x57619485u, 0xd1f5e62bu, 0x1aa9358eu,25420xebff875bu, 0x20a354feu, 0xa6372650u, 0x6d6bf5f5u, 0x706ec54du, 0xbb3216e8u, 0x3da66446u, 0xf6fab7e3u,25430x047a07adu, 0xcf26d408u, 0x49b2a6a6u, 0x82ee7503u, 0x9feb45bbu, 0x54b7961eu, 0xd223e4b0u, 0x197f3715u,25440xe82985c0u, 0x23755665u, 0xa5e124cbu, 0x6ebdf76eu, 0x73b8c7d6u, 0xb8e41473u, 0x3e7066ddu, 0xf52cb578u,25450x0f580a6cu, 0xc404d9c9u, 0x4290ab67u, 0x89cc78c2u, 0x94c9487au, 0x5f959bdfu, 0xd901e971u, 0x125d3ad4u,25460xe30b8801u, 0x28575ba4u, 0xaec3290au, 0x659ffaafu, 0x789aca17u, 0xb3c619b2u, 0x35526b1cu, 0xfe0eb8b9u,25470x0c8e08f7u, 0xc7d2db52u, 0x4146a9fcu, 0x8a1a7a59u, 0x971f4ae1u, 0x5c439944u, 0xdad7ebeau, 0x118b384fu,25480xe0dd8a9au, 0x2b81593fu, 0xad152b91u, 0x6649f834u, 0x7b4cc88cu, 0xb0101b29u, 0x36846987u, 0xfdd8ba22u,25490x08f40f5au, 0xc3a8dcffu, 0x453cae51u, 0x8e607df4u, 0x93654d4cu, 0x58399ee9u, 0xdeadec47u, 0x15f13fe2u,25500xe4a78d37u, 0x2ffb5e92u, 0xa96f2c3cu, 0x6233ff99u, 0x7f36cf21u, 0xb46a1c84u, 0x32fe6e2au, 0xf9a2bd8fu,25510x0b220dc1u, 0xc07ede64u, 0x46eaaccau, 0x8db67f6fu, 0x90b34fd7u, 0x5bef9c72u, 0xdd7beedcu, 0x16273d79u,25520xe7718facu, 0x2c2d5c09u, 0xaab92ea7u, 0x61e5fd02u, 0x7ce0cdbau, 0xb7bc1e1fu, 0x31286cb1u, 0xfa74bf14u,25530x1eb014d8u, 0xd5ecc77du, 0x5378b5d3u, 0x98246676u, 0x852156ceu, 0x4e7d856bu, 0xc8e9f7c5u, 0x03b52460u,25540xf2e396b5u, 0x39bf4510u, 0xbf2b37beu, 0x7477e41bu, 0x6972d4a3u, 0xa22e0706u, 0x24ba75a8u, 0xefe6a60du,25550x1d661643u, 0xd63ac5e6u, 0x50aeb748u, 0x9bf264edu, 0x86f75455u, 0x4dab87f0u, 0xcb3ff55eu, 0x006326fbu,25560xf135942eu, 0x3a69478bu, 0xbcfd3525u, 0x77a1e680u, 0x6aa4d638u, 0xa1f8059du, 0x276c7733u, 0xec30a496u,25570x191c11eeu, 0xd240c24bu, 0x54d4b0e5u, 0x9f886340u, 0x828d53f8u, 0x49d1805du, 0xcf45f2f3u, 0x04192156u,25580xf54f9383u, 0x3e134026u, 0xb8873288u, 0x73dbe12du, 0x6eded195u, 0xa5820230u, 0x2316709eu, 0xe84aa33bu,25590x1aca1375u, 0xd196c0d0u, 0x5702b27eu, 0x9c5e61dbu, 0x815b5163u, 0x4a0782c6u, 0xcc93f068u, 0x07cf23cdu,25600xf6999118u, 0x3dc542bdu, 0xbb513013u, 0x700de3b6u, 0x6d08d30eu, 0xa65400abu, 0x20c07205u, 0xeb9ca1a0u,25610x11e81eb4u, 0xdab4cd11u, 0x5c20bfbfu, 0x977c6c1au, 0x8a795ca2u, 0x41258f07u, 0xc7b1fda9u, 0x0ced2e0cu,25620xfdbb9cd9u, 0x36e74f7cu, 0xb0733dd2u, 0x7b2fee77u, 0x662adecfu, 0xad760d6au, 0x2be27fc4u, 0xe0beac61u,25630x123e1c2fu, 0xd962cf8au, 0x5ff6bd24u, 0x94aa6e81u, 0x89af5e39u, 0x42f38d9cu, 0xc467ff32u, 0x0f3b2c97u,25640xfe6d9e42u, 0x35314de7u, 0xb3a53f49u, 0x78f9ececu, 0x65fcdc54u, 0xaea00ff1u, 0x28347d5fu, 0xe368aefau,25650x16441b82u, 0xdd18c827u, 0x5b8cba89u, 0x90d0692cu, 0x8dd55994u, 0x46898a31u, 0xc01df89fu, 0x0b412b3au,25660xfa1799efu, 0x314b4a4au, 0xb7df38e4u, 0x7c83eb41u, 0x6186dbf9u, 0xaada085cu, 0x2c4e7af2u, 0xe712a957u,25670x15921919u, 0xdececabcu, 0x585ab812u, 0x93066bb7u, 0x8e035b0fu, 0x455f88aau, 0xc3cbfa04u, 0x089729a1u,25680xf9c19b74u, 0x329d48d1u, 0xb4093a7fu, 0x7f55e9dau, 0x6250d962u, 0xa90c0ac7u, 0x2f987869u, 0xe4c4abccu2569};25702571static const unsigned lodepng_crc32_table6[256] = {25720x00000000u, 0xa6770bb4u, 0x979f1129u, 0x31e81a9du, 0xf44f2413u, 0x52382fa7u, 0x63d0353au, 0xc5a73e8eu,25730x33ef4e67u, 0x959845d3u, 0xa4705f4eu, 0x020754fau, 0xc7a06a74u, 0x61d761c0u, 0x503f7b5du, 0xf64870e9u,25740x67de9cceu, 0xc1a9977au, 0xf0418de7u, 0x56368653u, 0x9391b8ddu, 0x35e6b369u, 0x040ea9f4u, 0xa279a240u,25750x5431d2a9u, 0xf246d91du, 0xc3aec380u, 0x65d9c834u, 0xa07ef6bau, 0x0609fd0eu, 0x37e1e793u, 0x9196ec27u,25760xcfbd399cu, 0x69ca3228u, 0x582228b5u, 0xfe552301u, 0x3bf21d8fu, 0x9d85163bu, 0xac6d0ca6u, 0x0a1a0712u,25770xfc5277fbu, 0x5a257c4fu, 0x6bcd66d2u, 0xcdba6d66u, 0x081d53e8u, 0xae6a585cu, 0x9f8242c1u, 0x39f54975u,25780xa863a552u, 0x0e14aee6u, 0x3ffcb47bu, 0x998bbfcfu, 0x5c2c8141u, 0xfa5b8af5u, 0xcbb39068u, 0x6dc49bdcu,25790x9b8ceb35u, 0x3dfbe081u, 0x0c13fa1cu, 0xaa64f1a8u, 0x6fc3cf26u, 0xc9b4c492u, 0xf85cde0fu, 0x5e2bd5bbu,25800x440b7579u, 0xe27c7ecdu, 0xd3946450u, 0x75e36fe4u, 0xb044516au, 0x16335adeu, 0x27db4043u, 0x81ac4bf7u,25810x77e43b1eu, 0xd19330aau, 0xe07b2a37u, 0x460c2183u, 0x83ab1f0du, 0x25dc14b9u, 0x14340e24u, 0xb2430590u,25820x23d5e9b7u, 0x85a2e203u, 0xb44af89eu, 0x123df32au, 0xd79acda4u, 0x71edc610u, 0x4005dc8du, 0xe672d739u,25830x103aa7d0u, 0xb64dac64u, 0x87a5b6f9u, 0x21d2bd4du, 0xe47583c3u, 0x42028877u, 0x73ea92eau, 0xd59d995eu,25840x8bb64ce5u, 0x2dc14751u, 0x1c295dccu, 0xba5e5678u, 0x7ff968f6u, 0xd98e6342u, 0xe86679dfu, 0x4e11726bu,25850xb8590282u, 0x1e2e0936u, 0x2fc613abu, 0x89b1181fu, 0x4c162691u, 0xea612d25u, 0xdb8937b8u, 0x7dfe3c0cu,25860xec68d02bu, 0x4a1fdb9fu, 0x7bf7c102u, 0xdd80cab6u, 0x1827f438u, 0xbe50ff8cu, 0x8fb8e511u, 0x29cfeea5u,25870xdf879e4cu, 0x79f095f8u, 0x48188f65u, 0xee6f84d1u, 0x2bc8ba5fu, 0x8dbfb1ebu, 0xbc57ab76u, 0x1a20a0c2u,25880x8816eaf2u, 0x2e61e146u, 0x1f89fbdbu, 0xb9fef06fu, 0x7c59cee1u, 0xda2ec555u, 0xebc6dfc8u, 0x4db1d47cu,25890xbbf9a495u, 0x1d8eaf21u, 0x2c66b5bcu, 0x8a11be08u, 0x4fb68086u, 0xe9c18b32u, 0xd82991afu, 0x7e5e9a1bu,25900xefc8763cu, 0x49bf7d88u, 0x78576715u, 0xde206ca1u, 0x1b87522fu, 0xbdf0599bu, 0x8c184306u, 0x2a6f48b2u,25910xdc27385bu, 0x7a5033efu, 0x4bb82972u, 0xedcf22c6u, 0x28681c48u, 0x8e1f17fcu, 0xbff70d61u, 0x198006d5u,25920x47abd36eu, 0xe1dcd8dau, 0xd034c247u, 0x7643c9f3u, 0xb3e4f77du, 0x1593fcc9u, 0x247be654u, 0x820cede0u,25930x74449d09u, 0xd23396bdu, 0xe3db8c20u, 0x45ac8794u, 0x800bb91au, 0x267cb2aeu, 0x1794a833u, 0xb1e3a387u,25940x20754fa0u, 0x86024414u, 0xb7ea5e89u, 0x119d553du, 0xd43a6bb3u, 0x724d6007u, 0x43a57a9au, 0xe5d2712eu,25950x139a01c7u, 0xb5ed0a73u, 0x840510eeu, 0x22721b5au, 0xe7d525d4u, 0x41a22e60u, 0x704a34fdu, 0xd63d3f49u,25960xcc1d9f8bu, 0x6a6a943fu, 0x5b828ea2u, 0xfdf58516u, 0x3852bb98u, 0x9e25b02cu, 0xafcdaab1u, 0x09baa105u,25970xfff2d1ecu, 0x5985da58u, 0x686dc0c5u, 0xce1acb71u, 0x0bbdf5ffu, 0xadcafe4bu, 0x9c22e4d6u, 0x3a55ef62u,25980xabc30345u, 0x0db408f1u, 0x3c5c126cu, 0x9a2b19d8u, 0x5f8c2756u, 0xf9fb2ce2u, 0xc813367fu, 0x6e643dcbu,25990x982c4d22u, 0x3e5b4696u, 0x0fb35c0bu, 0xa9c457bfu, 0x6c636931u, 0xca146285u, 0xfbfc7818u, 0x5d8b73acu,26000x03a0a617u, 0xa5d7ada3u, 0x943fb73eu, 0x3248bc8au, 0xf7ef8204u, 0x519889b0u, 0x6070932du, 0xc6079899u,26010x304fe870u, 0x9638e3c4u, 0xa7d0f959u, 0x01a7f2edu, 0xc400cc63u, 0x6277c7d7u, 0x539fdd4au, 0xf5e8d6feu,26020x647e3ad9u, 0xc209316du, 0xf3e12bf0u, 0x55962044u, 0x90311ecau, 0x3646157eu, 0x07ae0fe3u, 0xa1d90457u,26030x579174beu, 0xf1e67f0au, 0xc00e6597u, 0x66796e23u, 0xa3de50adu, 0x05a95b19u, 0x34414184u, 0x92364a30u2604};26052606static const unsigned lodepng_crc32_table7[256] = {26070x00000000u, 0xccaa009eu, 0x4225077du, 0x8e8f07e3u, 0x844a0efau, 0x48e00e64u, 0xc66f0987u, 0x0ac50919u,26080xd3e51bb5u, 0x1f4f1b2bu, 0x91c01cc8u, 0x5d6a1c56u, 0x57af154fu, 0x9b0515d1u, 0x158a1232u, 0xd92012acu,26090x7cbb312bu, 0xb01131b5u, 0x3e9e3656u, 0xf23436c8u, 0xf8f13fd1u, 0x345b3f4fu, 0xbad438acu, 0x767e3832u,26100xaf5e2a9eu, 0x63f42a00u, 0xed7b2de3u, 0x21d12d7du, 0x2b142464u, 0xe7be24fau, 0x69312319u, 0xa59b2387u,26110xf9766256u, 0x35dc62c8u, 0xbb53652bu, 0x77f965b5u, 0x7d3c6cacu, 0xb1966c32u, 0x3f196bd1u, 0xf3b36b4fu,26120x2a9379e3u, 0xe639797du, 0x68b67e9eu, 0xa41c7e00u, 0xaed97719u, 0x62737787u, 0xecfc7064u, 0x205670fau,26130x85cd537du, 0x496753e3u, 0xc7e85400u, 0x0b42549eu, 0x01875d87u, 0xcd2d5d19u, 0x43a25afau, 0x8f085a64u,26140x562848c8u, 0x9a824856u, 0x140d4fb5u, 0xd8a74f2bu, 0xd2624632u, 0x1ec846acu, 0x9047414fu, 0x5ced41d1u,26150x299dc2edu, 0xe537c273u, 0x6bb8c590u, 0xa712c50eu, 0xadd7cc17u, 0x617dcc89u, 0xeff2cb6au, 0x2358cbf4u,26160xfa78d958u, 0x36d2d9c6u, 0xb85dde25u, 0x74f7debbu, 0x7e32d7a2u, 0xb298d73cu, 0x3c17d0dfu, 0xf0bdd041u,26170x5526f3c6u, 0x998cf358u, 0x1703f4bbu, 0xdba9f425u, 0xd16cfd3cu, 0x1dc6fda2u, 0x9349fa41u, 0x5fe3fadfu,26180x86c3e873u, 0x4a69e8edu, 0xc4e6ef0eu, 0x084cef90u, 0x0289e689u, 0xce23e617u, 0x40ace1f4u, 0x8c06e16au,26190xd0eba0bbu, 0x1c41a025u, 0x92cea7c6u, 0x5e64a758u, 0x54a1ae41u, 0x980baedfu, 0x1684a93cu, 0xda2ea9a2u,26200x030ebb0eu, 0xcfa4bb90u, 0x412bbc73u, 0x8d81bcedu, 0x8744b5f4u, 0x4beeb56au, 0xc561b289u, 0x09cbb217u,26210xac509190u, 0x60fa910eu, 0xee7596edu, 0x22df9673u, 0x281a9f6au, 0xe4b09ff4u, 0x6a3f9817u, 0xa6959889u,26220x7fb58a25u, 0xb31f8abbu, 0x3d908d58u, 0xf13a8dc6u, 0xfbff84dfu, 0x37558441u, 0xb9da83a2u, 0x7570833cu,26230x533b85dau, 0x9f918544u, 0x111e82a7u, 0xddb48239u, 0xd7718b20u, 0x1bdb8bbeu, 0x95548c5du, 0x59fe8cc3u,26240x80de9e6fu, 0x4c749ef1u, 0xc2fb9912u, 0x0e51998cu, 0x04949095u, 0xc83e900bu, 0x46b197e8u, 0x8a1b9776u,26250x2f80b4f1u, 0xe32ab46fu, 0x6da5b38cu, 0xa10fb312u, 0xabcaba0bu, 0x6760ba95u, 0xe9efbd76u, 0x2545bde8u,26260xfc65af44u, 0x30cfafdau, 0xbe40a839u, 0x72eaa8a7u, 0x782fa1beu, 0xb485a120u, 0x3a0aa6c3u, 0xf6a0a65du,26270xaa4de78cu, 0x66e7e712u, 0xe868e0f1u, 0x24c2e06fu, 0x2e07e976u, 0xe2ade9e8u, 0x6c22ee0bu, 0xa088ee95u,26280x79a8fc39u, 0xb502fca7u, 0x3b8dfb44u, 0xf727fbdau, 0xfde2f2c3u, 0x3148f25du, 0xbfc7f5beu, 0x736df520u,26290xd6f6d6a7u, 0x1a5cd639u, 0x94d3d1dau, 0x5879d144u, 0x52bcd85du, 0x9e16d8c3u, 0x1099df20u, 0xdc33dfbeu,26300x0513cd12u, 0xc9b9cd8cu, 0x4736ca6fu, 0x8b9ccaf1u, 0x8159c3e8u, 0x4df3c376u, 0xc37cc495u, 0x0fd6c40bu,26310x7aa64737u, 0xb60c47a9u, 0x3883404au, 0xf42940d4u, 0xfeec49cdu, 0x32464953u, 0xbcc94eb0u, 0x70634e2eu,26320xa9435c82u, 0x65e95c1cu, 0xeb665bffu, 0x27cc5b61u, 0x2d095278u, 0xe1a352e6u, 0x6f2c5505u, 0xa386559bu,26330x061d761cu, 0xcab77682u, 0x44387161u, 0x889271ffu, 0x825778e6u, 0x4efd7878u, 0xc0727f9bu, 0x0cd87f05u,26340xd5f86da9u, 0x19526d37u, 0x97dd6ad4u, 0x5b776a4au, 0x51b26353u, 0x9d1863cdu, 0x1397642eu, 0xdf3d64b0u,26350x83d02561u, 0x4f7a25ffu, 0xc1f5221cu, 0x0d5f2282u, 0x079a2b9bu, 0xcb302b05u, 0x45bf2ce6u, 0x89152c78u,26360x50353ed4u, 0x9c9f3e4au, 0x121039a9u, 0xdeba3937u, 0xd47f302eu, 0x18d530b0u, 0x965a3753u, 0x5af037cdu,26370xff6b144au, 0x33c114d4u, 0xbd4e1337u, 0x71e413a9u, 0x7b211ab0u, 0xb78b1a2eu, 0x39041dcdu, 0xf5ae1d53u,26380x2c8e0fffu, 0xe0240f61u, 0x6eab0882u, 0xa201081cu, 0xa8c40105u, 0x646e019bu, 0xeae10678u, 0x264b06e6u2639};26402641/* Computes the cyclic redundancy check as used by PNG chunks*/2642unsigned lodepng_crc32(const unsigned char* data, size_t length) {2643/*Using the Slicing by Eight algorithm*/2644unsigned r = 0xffffffffu;2645while(length >= 8) {2646r = lodepng_crc32_table7[(data[0] ^ (r & 0xffu))] ^2647lodepng_crc32_table6[(data[1] ^ ((r >> 8) & 0xffu))] ^2648lodepng_crc32_table5[(data[2] ^ ((r >> 16) & 0xffu))] ^2649lodepng_crc32_table4[(data[3] ^ ((r >> 24) & 0xffu))] ^2650lodepng_crc32_table3[data[4]] ^2651lodepng_crc32_table2[data[5]] ^2652lodepng_crc32_table1[data[6]] ^2653lodepng_crc32_table0[data[7]];2654data += 8;2655length -= 8;2656}2657while(length--) {2658r = lodepng_crc32_table0[(r ^ *data++) & 0xffu] ^ (r >> 8);2659}2660return r ^ 0xffffffffu;2661}2662#else /* LODEPNG_COMPILE_CRC */2663/*in this case, the function is only declared here, and must be defined externally2664so that it will be linked in.26652666Example implementation that uses a much smaller lookup table for memory constrained cases:26672668unsigned lodepng_crc32(const unsigned char* data, size_t length) {2669unsigned r = 0xffffffffu;2670static const unsigned table[16] = {26710x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,26720xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c2673};2674while(length--) {2675r = table[(r ^ *data) & 0xf] ^ (r >> 4);2676r = table[(r ^ (*data >> 4)) & 0xf] ^ (r >> 4);2677data++;2678}2679return r ^ 0xffffffffu;2680}2681*/2682unsigned lodepng_crc32(const unsigned char* data, size_t length);2683#endif /* LODEPNG_COMPILE_CRC */26842685/* ////////////////////////////////////////////////////////////////////////// */2686/* / Reading and writing PNG color channel bits / */2687/* ////////////////////////////////////////////////////////////////////////// */26882689/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,2690so LodePNGBitWriter and LodePNGBitReader can't be used for those. */26912692static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) {2693unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);2694++(*bitpointer);2695return result;2696}26972698/* TODO: make this faster */2699static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {2700unsigned result = 0;2701size_t i;2702for(i = 0 ; i < nbits; ++i) {2703result <<= 1u;2704result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);2705}2706return result;2707}27082709static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {2710/*the current bit in bitstream may be 0 or 1 for this to work*/2711if(bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u))));2712else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u)));2713++(*bitpointer);2714}27152716/* ////////////////////////////////////////////////////////////////////////// */2717/* / PNG chunks / */2718/* ////////////////////////////////////////////////////////////////////////// */27192720unsigned lodepng_chunk_length(const unsigned char* chunk) {2721return lodepng_read32bitInt(chunk);2722}27232724void lodepng_chunk_type(char type[5], const unsigned char* chunk) {2725unsigned i;2726for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];2727type[4] = 0; /*null termination char*/2728}27292730unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) {2731if(lodepng_strlen(type) != 4) return 0;2732return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);2733}27342735/* chunk type name must exist only out of alphabetic characters a-z or A-Z */2736static unsigned char lodepng_chunk_type_name_valid(const unsigned char* chunk) {2737unsigned i;2738for(i = 0; i != 4; ++i) {2739char c = (char)chunk[4 + i];2740if(!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {2741return 0; /* not valid */2742}2743}2744return 1; /* valid */2745}27462747unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) {2748return((chunk[4] & 32) != 0);2749}27502751unsigned char lodepng_chunk_private(const unsigned char* chunk) {2752return((chunk[5] & 32) != 0);2753}27542755/* this is an error if it is reserved: the third character must be uppercase in the PNG standard,2756lowercasing this character is reserved for possible future extension by the spec*/2757static unsigned char lodepng_chunk_reserved(const unsigned char* chunk) {2758return((chunk[6] & 32) != 0);2759}27602761unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) {2762return((chunk[7] & 32) != 0);2763}27642765unsigned char* lodepng_chunk_data(unsigned char* chunk) {2766return &chunk[8];2767}27682769const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) {2770return &chunk[8];2771}27722773unsigned lodepng_chunk_check_crc(const unsigned char* chunk) {2774unsigned length = lodepng_chunk_length(chunk);2775unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);2776/*the CRC is taken of the data and the 4 chunk type letters, not the length*/2777unsigned checksum = lodepng_crc32(&chunk[4], length + 4);2778if(CRC != checksum) return 1;2779else return 0;2780}27812782void lodepng_chunk_generate_crc(unsigned char* chunk) {2783unsigned length = lodepng_chunk_length(chunk);2784unsigned CRC = lodepng_crc32(&chunk[4], length + 4);2785lodepng_set32bitInt(chunk + 8 + length, CRC);2786}27872788unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end) {2789size_t available_size = (size_t)(end - chunk);2790if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/2791if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x472792&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {2793/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */2794return chunk + 8;2795} else {2796size_t total_chunk_length;2797if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;2798if(total_chunk_length > available_size) return end; /*outside of range*/2799return chunk + total_chunk_length;2800}2801}28022803const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end) {2804size_t available_size = (size_t)(end - chunk);2805if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/2806if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x472807&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {2808/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */2809return chunk + 8;2810} else {2811size_t total_chunk_length;2812if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;2813if(total_chunk_length > available_size) return end; /*outside of range*/2814return chunk + total_chunk_length;2815}2816}28172818unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]) {2819for(;;) {2820if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */2821if(lodepng_chunk_type_equals(chunk, type)) return chunk;2822chunk = lodepng_chunk_next(chunk, end);2823}2824}28252826const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) {2827for(;;) {2828if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */2829if(lodepng_chunk_type_equals(chunk, type)) return chunk;2830chunk = lodepng_chunk_next_const(chunk, end);2831}2832}28332834unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk) {2835unsigned i;2836size_t total_chunk_length, new_length;2837unsigned char *chunk_start, *new_buffer;28382839if(!lodepng_chunk_type_name_valid(chunk)) {2840return 121; /* invalid chunk type name */2841}2842if(lodepng_chunk_reserved(chunk)) {2843return 122; /* invalid third lowercase character */2844}28452846if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77;2847if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77;28482849new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);2850if(!new_buffer) return 83; /*alloc fail*/2851(*out) = new_buffer;2852(*outsize) = new_length;2853chunk_start = &(*out)[new_length - total_chunk_length];28542855for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];28562857return 0;2858}28592860/*Sets length and name and allocates the space for data and crc but does not2861set data or crc yet. Returns the start of the chunk in chunk. The start of2862the data is at chunk + 8. To finalize chunk, add the data, then use2863lodepng_chunk_generate_crc */2864static unsigned lodepng_chunk_init(unsigned char** chunk,2865ucvector* out,2866size_t length, const char* type) {2867size_t new_length = out->size;2868if(lodepng_addofl(new_length, length, &new_length)) return 77;2869if(lodepng_addofl(new_length, 12, &new_length)) return 77;2870if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/2871*chunk = out->data + new_length - length - 12u;28722873/*1: length*/2874lodepng_set32bitInt(*chunk, (unsigned)length);28752876/*2: chunk name (4 letters)*/2877lodepng_memcpy(*chunk + 4, type, 4);28782879return 0;2880}28812882/* like lodepng_chunk_create but with custom allocsize */2883static unsigned lodepng_chunk_createv(ucvector* out,2884size_t length, const char* type, const unsigned char* data) {2885unsigned char* chunk;2886CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type));28872888/*3: the data*/2889lodepng_memcpy(chunk + 8, data, length);28902891/*4: CRC (of the chunkname characters and the data)*/2892lodepng_chunk_generate_crc(chunk);28932894return 0;2895}28962897unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize,2898size_t length, const char* type, const unsigned char* data) {2899ucvector v = ucvector_init(*out, *outsize);2900unsigned error = lodepng_chunk_createv(&v, length, type, data);2901*out = v.data;2902*outsize = v.size;2903return error;2904}29052906/* ////////////////////////////////////////////////////////////////////////// */2907/* / Color types, channels, bits / */2908/* ////////////////////////////////////////////////////////////////////////// */29092910/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.2911Return value is a LodePNG error code.*/2912static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) {2913switch(colortype) {2914case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break;2915case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break;2916case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break;2917case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break;2918case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break;2919case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */2920default: return 31; /* invalid color type */2921}2922return 0; /*allowed color type / bits combination*/2923}29242925static unsigned getNumColorChannels(LodePNGColorType colortype) {2926switch(colortype) {2927case LCT_GREY: return 1;2928case LCT_RGB: return 3;2929case LCT_PALETTE: return 1;2930case LCT_GREY_ALPHA: return 2;2931case LCT_RGBA: return 4;2932case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */2933default: return 0; /*invalid color type*/2934}2935}29362937static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) {2938/*bits per pixel is amount of channels * bits per channel*/2939return getNumColorChannels(colortype) * bitdepth;2940}29412942/* ////////////////////////////////////////////////////////////////////////// */29432944void lodepng_color_mode_init(LodePNGColorMode* info) {2945info->key_defined = 0;2946info->key_r = info->key_g = info->key_b = 0;2947info->colortype = LCT_RGBA;2948info->bitdepth = 8;2949info->palette = 0;2950info->palettesize = 0;2951}29522953/*allocates palette memory if needed, and initializes all colors to black*/2954static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) {2955size_t i;2956/*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/2957/*the palette must have room for up to 256 colors with 4 bytes each.*/2958if(!info->palette) info->palette = (unsigned char*)lodepng_malloc(1024);2959if(!info->palette) return; /*alloc fail*/2960for(i = 0; i != 256; ++i) {2961/*Initialize all unused colors with black, the value used for invalid palette indices.2962This is an error according to the PNG spec, but common PNG decoders make it black instead.2963That makes color conversion slightly faster due to no error handling needed.*/2964info->palette[i * 4 + 0] = 0;2965info->palette[i * 4 + 1] = 0;2966info->palette[i * 4 + 2] = 0;2967info->palette[i * 4 + 3] = 255;2968}2969}29702971void lodepng_color_mode_cleanup(LodePNGColorMode* info) {2972lodepng_palette_clear(info);2973}29742975unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) {2976lodepng_color_mode_cleanup(dest);2977lodepng_memcpy(dest, source, sizeof(LodePNGColorMode));2978if(source->palette) {2979dest->palette = (unsigned char*)lodepng_malloc(1024);2980if(!dest->palette && source->palettesize) return 83; /*alloc fail*/2981lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4);2982}2983return 0;2984}29852986LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) {2987LodePNGColorMode result;2988lodepng_color_mode_init(&result);2989result.colortype = colortype;2990result.bitdepth = bitdepth;2991return result;2992}29932994static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) {2995size_t i;2996if(a->colortype != b->colortype) return 0;2997if(a->bitdepth != b->bitdepth) return 0;2998if(a->key_defined != b->key_defined) return 0;2999if(a->key_defined) {3000if(a->key_r != b->key_r) return 0;3001if(a->key_g != b->key_g) return 0;3002if(a->key_b != b->key_b) return 0;3003}3004if(a->palettesize != b->palettesize) return 0;3005for(i = 0; i != a->palettesize * 4; ++i) {3006if(a->palette[i] != b->palette[i]) return 0;3007}3008return 1;3009}30103011void lodepng_palette_clear(LodePNGColorMode* info) {3012if(info->palette) lodepng_free(info->palette);3013info->palette = 0;3014info->palettesize = 0;3015}30163017unsigned lodepng_palette_add(LodePNGColorMode* info,3018unsigned char r, unsigned char g, unsigned char b, unsigned char a) {3019if(!info->palette) /*allocate palette if empty*/ {3020lodepng_color_mode_alloc_palette(info);3021if(!info->palette) return 83; /*alloc fail*/3022}3023if(info->palettesize >= 256) {3024return 108; /*too many palette values*/3025}3026info->palette[4 * info->palettesize + 0] = r;3027info->palette[4 * info->palettesize + 1] = g;3028info->palette[4 * info->palettesize + 2] = b;3029info->palette[4 * info->palettesize + 3] = a;3030++info->palettesize;3031return 0;3032}30333034/*calculate bits per pixel out of colortype and bitdepth*/3035unsigned lodepng_get_bpp(const LodePNGColorMode* info) {3036return lodepng_get_bpp_lct(info->colortype, info->bitdepth);3037}30383039unsigned lodepng_get_channels(const LodePNGColorMode* info) {3040return getNumColorChannels(info->colortype);3041}30423043unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) {3044return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;3045}30463047unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) {3048return (info->colortype & 4) != 0; /*4 or 6*/3049}30503051unsigned lodepng_is_palette_type(const LodePNGColorMode* info) {3052return info->colortype == LCT_PALETTE;3053}30543055unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) {3056size_t i;3057for(i = 0; i != info->palettesize; ++i) {3058if(info->palette[i * 4 + 3] < 255) return 1;3059}3060return 0;3061}30623063unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) {3064return info->key_defined3065|| lodepng_is_alpha_type(info)3066|| lodepng_has_palette_alpha(info);3067}30683069static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {3070size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);3071size_t n = (size_t)w * (size_t)h;3072return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;3073}30743075size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) {3076return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);3077}307830793080#ifdef LODEPNG_COMPILE_PNG30813082/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,3083and in addition has one extra byte per line: the filter byte. So this gives a larger3084result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */3085static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp) {3086/* + 1 for the filter byte, and possibly plus padding bits per line. */3087/* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */3088size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;3089return (size_t)h * line;3090}30913092#ifdef LODEPNG_COMPILE_DECODER3093/*Safely checks whether size_t overflow can be caused due to amount of pixels.3094This check is overcautious rather than precise. If this check indicates no overflow,3095you can safely compute in a size_t (but not an unsigned):3096-(size_t)w * (size_t)h * 83097-amount of bytes in IDAT (including filter, padding and Adam7 bytes)3098-amount of bytes in raw color model3099Returns 1 if overflow possible, 0 if not.3100*/3101static int lodepng_pixel_overflow(unsigned w, unsigned h,3102const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) {3103size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));3104size_t numpixels, total;3105size_t line; /* bytes per line in worst case */31063107if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;3108if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */31093110/* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */3111if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;3112if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;31133114if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */3115if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */31163117return 0; /* no overflow */3118}3119#endif /*LODEPNG_COMPILE_DECODER*/3120#endif /*LODEPNG_COMPILE_PNG*/31213122#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS31233124static void LodePNGUnknownChunks_init(LodePNGInfo* info) {3125unsigned i;3126for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;3127for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;3128}31293130static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) {3131unsigned i;3132for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);3133}31343135static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) {3136unsigned i;31373138LodePNGUnknownChunks_cleanup(dest);31393140for(i = 0; i != 3; ++i) {3141size_t j;3142dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];3143dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);3144if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/3145for(j = 0; j < src->unknown_chunks_size[i]; ++j) {3146dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];3147}3148}31493150return 0;3151}31523153/******************************************************************************/31543155static void LodePNGText_init(LodePNGInfo* info) {3156info->text_num = 0;3157info->text_keys = NULL;3158info->text_strings = NULL;3159}31603161static void LodePNGText_cleanup(LodePNGInfo* info) {3162size_t i;3163for(i = 0; i != info->text_num; ++i) {3164string_cleanup(&info->text_keys[i]);3165string_cleanup(&info->text_strings[i]);3166}3167lodepng_free(info->text_keys);3168lodepng_free(info->text_strings);3169}31703171static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {3172size_t i = 0;3173dest->text_keys = NULL;3174dest->text_strings = NULL;3175dest->text_num = 0;3176for(i = 0; i != source->text_num; ++i) {3177CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));3178}3179return 0;3180}31813182static unsigned lodepng_add_text_sized(LodePNGInfo* info, const char* key, const char* str, size_t size) {3183char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));3184char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));31853186if(new_keys) info->text_keys = new_keys;3187if(new_strings) info->text_strings = new_strings;31883189if(!new_keys || !new_strings) return 83; /*alloc fail*/31903191++info->text_num;3192info->text_keys[info->text_num - 1] = alloc_string(key);3193info->text_strings[info->text_num - 1] = alloc_string_sized(str, size);3194if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/31953196return 0;3197}31983199unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) {3200return lodepng_add_text_sized(info, key, str, lodepng_strlen(str));3201}32023203void lodepng_clear_text(LodePNGInfo* info) {3204LodePNGText_cleanup(info);3205}32063207/******************************************************************************/32083209static void LodePNGIText_init(LodePNGInfo* info) {3210info->itext_num = 0;3211info->itext_keys = NULL;3212info->itext_langtags = NULL;3213info->itext_transkeys = NULL;3214info->itext_strings = NULL;3215}32163217static void LodePNGIText_cleanup(LodePNGInfo* info) {3218size_t i;3219for(i = 0; i != info->itext_num; ++i) {3220string_cleanup(&info->itext_keys[i]);3221string_cleanup(&info->itext_langtags[i]);3222string_cleanup(&info->itext_transkeys[i]);3223string_cleanup(&info->itext_strings[i]);3224}3225lodepng_free(info->itext_keys);3226lodepng_free(info->itext_langtags);3227lodepng_free(info->itext_transkeys);3228lodepng_free(info->itext_strings);3229}32303231static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {3232size_t i = 0;3233dest->itext_keys = NULL;3234dest->itext_langtags = NULL;3235dest->itext_transkeys = NULL;3236dest->itext_strings = NULL;3237dest->itext_num = 0;3238for(i = 0; i != source->itext_num; ++i) {3239CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],3240source->itext_transkeys[i], source->itext_strings[i]));3241}3242return 0;3243}32443245void lodepng_clear_itext(LodePNGInfo* info) {3246LodePNGIText_cleanup(info);3247}32483249static unsigned lodepng_add_itext_sized(LodePNGInfo* info, const char* key, const char* langtag,3250const char* transkey, const char* str, size_t size) {3251char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));3252char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));3253char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));3254char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));32553256if(new_keys) info->itext_keys = new_keys;3257if(new_langtags) info->itext_langtags = new_langtags;3258if(new_transkeys) info->itext_transkeys = new_transkeys;3259if(new_strings) info->itext_strings = new_strings;32603261if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/32623263++info->itext_num;32643265info->itext_keys[info->itext_num - 1] = alloc_string(key);3266info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);3267info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);3268info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size);32693270return 0;3271}32723273unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,3274const char* transkey, const char* str) {3275return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str));3276}32773278unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {3279if(info->iccp_defined) lodepng_clear_icc(info);32803281if(profile_size == 0) return 100; /*invalid ICC profile size*/32823283info->iccp_name = alloc_string(name);3284if(!info->iccp_name) return 83; /*alloc fail*/32853286info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size);3287if(!info->iccp_profile) {3288lodepng_free(info->iccp_name);3289return 83; /*alloc fail*/3290}32913292lodepng_memcpy(info->iccp_profile, profile, profile_size);3293info->iccp_profile_size = profile_size;3294info->iccp_defined = 1;32953296return 0; /*ok*/3297}32983299void lodepng_clear_icc(LodePNGInfo* info) {3300string_cleanup(&info->iccp_name);3301lodepng_free(info->iccp_profile);3302info->iccp_profile = NULL;3303info->iccp_profile_size = 0;3304info->iccp_defined = 0;3305}33063307unsigned lodepng_set_exif(LodePNGInfo* info, const unsigned char* exif, unsigned exif_size) {3308if(info->exif_defined) lodepng_clear_exif(info);3309info->exif = (unsigned char*)lodepng_malloc(exif_size);33103311if(!info->exif) return 83; /*alloc fail*/33123313lodepng_memcpy(info->exif, exif, exif_size);3314info->exif_size = exif_size;3315info->exif_defined = 1;33163317return 0; /*ok*/3318}33193320void lodepng_clear_exif(LodePNGInfo* info) {3321lodepng_free(info->exif);3322info->exif = NULL;3323info->exif_size = 0;3324info->exif_defined = 0;3325}3326#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/33273328void lodepng_info_init(LodePNGInfo* info) {3329lodepng_color_mode_init(&info->color);3330info->interlace_method = 0;3331info->compression_method = 0;3332info->filter_method = 0;3333#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS3334info->background_defined = 0;3335info->background_r = info->background_g = info->background_b = 0;33363337LodePNGText_init(info);3338LodePNGIText_init(info);33393340info->time_defined = 0;3341info->phys_defined = 0;33423343info->gama_defined = 0;3344info->chrm_defined = 0;3345info->srgb_defined = 0;3346info->iccp_defined = 0;3347info->iccp_name = NULL;3348info->iccp_profile = NULL;3349info->cicp_defined = 0;3350info->cicp_color_primaries = 0;3351info->cicp_transfer_function = 0;3352info->cicp_matrix_coefficients = 0;3353info->cicp_video_full_range_flag = 0;3354info->mdcv_defined = 0;3355info->mdcv_red_x = 0;3356info->mdcv_red_y = 0;3357info->mdcv_green_x = 0;3358info->mdcv_green_y = 0;3359info->mdcv_blue_x = 0;3360info->mdcv_blue_y = 0;3361info->mdcv_white_x = 0;3362info->mdcv_white_y = 0;3363info->mdcv_max_luminance = 0;3364info->mdcv_min_luminance = 0;3365info->clli_defined = 0;3366info->clli_max_cll = 0;3367info->clli_max_fall = 0;33683369info->exif_defined = 0;3370info->exif = NULL;3371info->exif_size = 0;33723373info->sbit_defined = 0;3374info->sbit_r = info->sbit_g = info->sbit_b = info->sbit_a = 0;33753376LodePNGUnknownChunks_init(info);3377#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/3378}33793380void lodepng_info_cleanup(LodePNGInfo* info) {3381lodepng_color_mode_cleanup(&info->color);3382#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS3383LodePNGText_cleanup(info);3384LodePNGIText_cleanup(info);33853386lodepng_clear_icc(info);3387lodepng_clear_exif(info);33883389LodePNGUnknownChunks_cleanup(info);3390#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/3391}33923393unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) {3394lodepng_info_cleanup(dest);3395lodepng_memcpy(dest, source, sizeof(LodePNGInfo));3396lodepng_color_mode_init(&dest->color);3397CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));33983399#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS3400CERROR_TRY_RETURN(LodePNGText_copy(dest, source));3401CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));3402if(source->iccp_defined) {3403dest->iccp_defined = 0; /*the memcpy above set this to 1 while it shouldn't*/3404CERROR_TRY_RETURN(lodepng_set_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));3405}3406if(source->exif_defined) {3407dest->exif_defined = 0; /*the memcpy above set this to 1 while it shouldn't*/3408CERROR_TRY_RETURN(lodepng_set_exif(dest, source->exif, source->exif_size));3409}34103411LodePNGUnknownChunks_init(dest);3412CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));3413#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/3414return 0;3415}34163417/* ////////////////////////////////////////////////////////////////////////// */34183419/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/3420static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) {3421unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/3422/*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/3423unsigned p = index & m;3424in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/3425in = in << (bits * (m - p));3426if(p == 0) out[index * bits / 8u] = in;3427else out[index * bits / 8u] |= in;3428}34293430typedef struct ColorTree ColorTree;34313432/*3433One node of a color tree3434This is the data structure used to count the number of unique colors and to get a palette3435index for a color. It's like an octree, but because the alpha channel is used too, each3436node has 16 instead of 8 children.3437*/3438struct ColorTree {3439ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/3440int index; /*the payload. Only has a meaningful value if this is in the last level*/3441};34423443static void color_tree_init(ColorTree* tree) {3444lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children));3445tree->index = -1;3446}34473448static void color_tree_cleanup(ColorTree* tree) {3449int i;3450for(i = 0; i != 16; ++i) {3451if(tree->children[i]) {3452color_tree_cleanup(tree->children[i]);3453lodepng_free(tree->children[i]);3454}3455}3456}34573458/*returns -1 if color not present, its index otherwise*/3459static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {3460int bit = 0;3461for(bit = 0; bit < 8; ++bit) {3462int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);3463if(!tree->children[i]) return -1;3464else tree = tree->children[i];3465}3466return tree ? tree->index : -1;3467}34683469#ifdef LODEPNG_COMPILE_ENCODER3470static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {3471return color_tree_get(tree, r, g, b, a) >= 0;3472}3473#endif /*LODEPNG_COMPILE_ENCODER*/34743475/*color is not allowed to already exist.3476Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")3477Returns error code, or 0 if ok*/3478static unsigned color_tree_add(ColorTree* tree,3479unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) {3480int bit;3481for(bit = 0; bit < 8; ++bit) {3482int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);3483if(!tree->children[i]) {3484tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));3485if(!tree->children[i]) return 83; /*alloc fail*/3486color_tree_init(tree->children[i]);3487}3488tree = tree->children[i];3489}3490tree->index = (int)index;3491return 0;3492}34933494/*put a pixel, given its RGBA color, into image of any color type*/3495static unsigned rgba8ToPixel(unsigned char* out, size_t i,3496const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,3497unsigned char r, unsigned char g, unsigned char b, unsigned char a) {3498if(mode->colortype == LCT_GREY) {3499unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/3500if(mode->bitdepth == 8) out[i] = gray;3501else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;3502else {3503/*take the most significant bits of gray*/3504gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u);3505addColorBits(out, i, mode->bitdepth, gray);3506}3507} else if(mode->colortype == LCT_RGB) {3508if(mode->bitdepth == 8) {3509out[i * 3 + 0] = r;3510out[i * 3 + 1] = g;3511out[i * 3 + 2] = b;3512} else {3513out[i * 6 + 0] = out[i * 6 + 1] = r;3514out[i * 6 + 2] = out[i * 6 + 3] = g;3515out[i * 6 + 4] = out[i * 6 + 5] = b;3516}3517} else if(mode->colortype == LCT_PALETTE) {3518int index = color_tree_get(tree, r, g, b, a);3519if(index < 0) return 82; /*color not in palette*/3520if(mode->bitdepth == 8) out[i] = index;3521else addColorBits(out, i, mode->bitdepth, (unsigned)index);3522} else if(mode->colortype == LCT_GREY_ALPHA) {3523unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/3524if(mode->bitdepth == 8) {3525out[i * 2 + 0] = gray;3526out[i * 2 + 1] = a;3527} else if(mode->bitdepth == 16) {3528out[i * 4 + 0] = out[i * 4 + 1] = gray;3529out[i * 4 + 2] = out[i * 4 + 3] = a;3530}3531} else if(mode->colortype == LCT_RGBA) {3532if(mode->bitdepth == 8) {3533out[i * 4 + 0] = r;3534out[i * 4 + 1] = g;3535out[i * 4 + 2] = b;3536out[i * 4 + 3] = a;3537} else {3538out[i * 8 + 0] = out[i * 8 + 1] = r;3539out[i * 8 + 2] = out[i * 8 + 3] = g;3540out[i * 8 + 4] = out[i * 8 + 5] = b;3541out[i * 8 + 6] = out[i * 8 + 7] = a;3542}3543}35443545return 0; /*no error*/3546}35473548/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/3549static void rgba16ToPixel(unsigned char* out, size_t i,3550const LodePNGColorMode* mode,3551unsigned short r, unsigned short g, unsigned short b, unsigned short a) {3552if(mode->colortype == LCT_GREY) {3553unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/3554out[i * 2 + 0] = (gray >> 8) & 255;3555out[i * 2 + 1] = gray & 255;3556} else if(mode->colortype == LCT_RGB) {3557out[i * 6 + 0] = (r >> 8) & 255;3558out[i * 6 + 1] = r & 255;3559out[i * 6 + 2] = (g >> 8) & 255;3560out[i * 6 + 3] = g & 255;3561out[i * 6 + 4] = (b >> 8) & 255;3562out[i * 6 + 5] = b & 255;3563} else if(mode->colortype == LCT_GREY_ALPHA) {3564unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/3565out[i * 4 + 0] = (gray >> 8) & 255;3566out[i * 4 + 1] = gray & 255;3567out[i * 4 + 2] = (a >> 8) & 255;3568out[i * 4 + 3] = a & 255;3569} else if(mode->colortype == LCT_RGBA) {3570out[i * 8 + 0] = (r >> 8) & 255;3571out[i * 8 + 1] = r & 255;3572out[i * 8 + 2] = (g >> 8) & 255;3573out[i * 8 + 3] = g & 255;3574out[i * 8 + 4] = (b >> 8) & 255;3575out[i * 8 + 5] = b & 255;3576out[i * 8 + 6] = (a >> 8) & 255;3577out[i * 8 + 7] = a & 255;3578}3579}35803581/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/3582static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,3583unsigned char* b, unsigned char* a,3584const unsigned char* in, size_t i,3585const LodePNGColorMode* mode) {3586if(mode->colortype == LCT_GREY) {3587if(mode->bitdepth == 8) {3588*r = *g = *b = in[i];3589if(mode->key_defined && *r == mode->key_r) *a = 0;3590else *a = 255;3591} else if(mode->bitdepth == 16) {3592*r = *g = *b = in[i * 2 + 0];3593if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;3594else *a = 255;3595} else {3596unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/3597size_t j = i * mode->bitdepth;3598unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);3599*r = *g = *b = (value * 255) / highest;3600if(mode->key_defined && value == mode->key_r) *a = 0;3601else *a = 255;3602}3603} else if(mode->colortype == LCT_RGB) {3604if(mode->bitdepth == 8) {3605*r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];3606if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;3607else *a = 255;3608} else {3609*r = in[i * 6 + 0];3610*g = in[i * 6 + 2];3611*b = in[i * 6 + 4];3612if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r3613&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g3614&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;3615else *a = 255;3616}3617} else if(mode->colortype == LCT_PALETTE) {3618unsigned index;3619if(mode->bitdepth == 8) index = in[i];3620else {3621size_t j = i * mode->bitdepth;3622index = readBitsFromReversedStream(&j, in, mode->bitdepth);3623}3624/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/3625*r = mode->palette[index * 4 + 0];3626*g = mode->palette[index * 4 + 1];3627*b = mode->palette[index * 4 + 2];3628*a = mode->palette[index * 4 + 3];3629} else if(mode->colortype == LCT_GREY_ALPHA) {3630if(mode->bitdepth == 8) {3631*r = *g = *b = in[i * 2 + 0];3632*a = in[i * 2 + 1];3633} else {3634*r = *g = *b = in[i * 4 + 0];3635*a = in[i * 4 + 2];3636}3637} else if(mode->colortype == LCT_RGBA) {3638if(mode->bitdepth == 8) {3639*r = in[i * 4 + 0];3640*g = in[i * 4 + 1];3641*b = in[i * 4 + 2];3642*a = in[i * 4 + 3];3643} else {3644*r = in[i * 8 + 0];3645*g = in[i * 8 + 2];3646*b = in[i * 8 + 4];3647*a = in[i * 8 + 6];3648}3649}3650}36513652/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color3653mode test cases, optimized to convert the colors much faster, when converting3654to the common case of RGBA with 8 bit per channel. buffer must be RGBA with3655enough memory.*/3656static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,3657const unsigned char* LODEPNG_RESTRICT in,3658const LodePNGColorMode* mode) {3659unsigned num_channels = 4;3660size_t i;3661if(mode->colortype == LCT_GREY) {3662if(mode->bitdepth == 8) {3663for(i = 0; i != numpixels; ++i, buffer += num_channels) {3664buffer[0] = buffer[1] = buffer[2] = in[i];3665buffer[3] = 255;3666}3667if(mode->key_defined) {3668buffer -= numpixels * num_channels;3669for(i = 0; i != numpixels; ++i, buffer += num_channels) {3670if(buffer[0] == mode->key_r) buffer[3] = 0;3671}3672}3673} else if(mode->bitdepth == 16) {3674for(i = 0; i != numpixels; ++i, buffer += num_channels) {3675buffer[0] = buffer[1] = buffer[2] = in[i * 2];3676buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;3677}3678} else {3679unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/3680size_t j = 0;3681for(i = 0; i != numpixels; ++i, buffer += num_channels) {3682unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);3683buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;3684buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;3685}3686}3687} else if(mode->colortype == LCT_RGB) {3688if(mode->bitdepth == 8) {3689for(i = 0; i != numpixels; ++i, buffer += num_channels) {3690lodepng_memcpy(buffer, &in[i * 3], 3);3691buffer[3] = 255;3692}3693if(mode->key_defined) {3694buffer -= numpixels * num_channels;3695for(i = 0; i != numpixels; ++i, buffer += num_channels) {3696if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;3697}3698}3699} else {3700for(i = 0; i != numpixels; ++i, buffer += num_channels) {3701buffer[0] = in[i * 6 + 0];3702buffer[1] = in[i * 6 + 2];3703buffer[2] = in[i * 6 + 4];3704buffer[3] = mode->key_defined3705&& 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r3706&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g3707&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;3708}3709}3710} else if(mode->colortype == LCT_PALETTE) {3711if(mode->bitdepth == 8) {3712for(i = 0; i != numpixels; ++i, buffer += num_channels) {3713unsigned index = in[i];3714/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/3715lodepng_memcpy(buffer, &mode->palette[index * 4], 4);3716}3717} else {3718size_t j = 0;3719for(i = 0; i != numpixels; ++i, buffer += num_channels) {3720unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);3721/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/3722lodepng_memcpy(buffer, &mode->palette[index * 4], 4);3723}3724}3725} else if(mode->colortype == LCT_GREY_ALPHA) {3726if(mode->bitdepth == 8) {3727for(i = 0; i != numpixels; ++i, buffer += num_channels) {3728buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];3729buffer[3] = in[i * 2 + 1];3730}3731} else {3732for(i = 0; i != numpixels; ++i, buffer += num_channels) {3733buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];3734buffer[3] = in[i * 4 + 2];3735}3736}3737} else if(mode->colortype == LCT_RGBA) {3738if(mode->bitdepth == 8) {3739lodepng_memcpy(buffer, in, numpixels * 4);3740} else {3741for(i = 0; i != numpixels; ++i, buffer += num_channels) {3742buffer[0] = in[i * 8 + 0];3743buffer[1] = in[i * 8 + 2];3744buffer[2] = in[i * 8 + 4];3745buffer[3] = in[i * 8 + 6];3746}3747}3748}3749}37503751/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/3752static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,3753const unsigned char* LODEPNG_RESTRICT in,3754const LodePNGColorMode* mode) {3755const unsigned num_channels = 3;3756size_t i;3757if(mode->colortype == LCT_GREY) {3758if(mode->bitdepth == 8) {3759for(i = 0; i != numpixels; ++i, buffer += num_channels) {3760buffer[0] = buffer[1] = buffer[2] = in[i];3761}3762} else if(mode->bitdepth == 16) {3763for(i = 0; i != numpixels; ++i, buffer += num_channels) {3764buffer[0] = buffer[1] = buffer[2] = in[i * 2];3765}3766} else {3767unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/3768size_t j = 0;3769for(i = 0; i != numpixels; ++i, buffer += num_channels) {3770unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);3771buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;3772}3773}3774} else if(mode->colortype == LCT_RGB) {3775if(mode->bitdepth == 8) {3776lodepng_memcpy(buffer, in, numpixels * 3);3777} else {3778for(i = 0; i != numpixels; ++i, buffer += num_channels) {3779buffer[0] = in[i * 6 + 0];3780buffer[1] = in[i * 6 + 2];3781buffer[2] = in[i * 6 + 4];3782}3783}3784} else if(mode->colortype == LCT_PALETTE) {3785if(mode->bitdepth == 8) {3786for(i = 0; i != numpixels; ++i, buffer += num_channels) {3787unsigned index = in[i];3788/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/3789lodepng_memcpy(buffer, &mode->palette[index * 4], 3);3790}3791} else {3792size_t j = 0;3793for(i = 0; i != numpixels; ++i, buffer += num_channels) {3794unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);3795/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/3796lodepng_memcpy(buffer, &mode->palette[index * 4], 3);3797}3798}3799} else if(mode->colortype == LCT_GREY_ALPHA) {3800if(mode->bitdepth == 8) {3801for(i = 0; i != numpixels; ++i, buffer += num_channels) {3802buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];3803}3804} else {3805for(i = 0; i != numpixels; ++i, buffer += num_channels) {3806buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];3807}3808}3809} else if(mode->colortype == LCT_RGBA) {3810if(mode->bitdepth == 8) {3811for(i = 0; i != numpixels; ++i, buffer += num_channels) {3812lodepng_memcpy(buffer, &in[i * 4], 3);3813}3814} else {3815for(i = 0; i != numpixels; ++i, buffer += num_channels) {3816buffer[0] = in[i * 8 + 0];3817buffer[1] = in[i * 8 + 2];3818buffer[2] = in[i * 8 + 4];3819}3820}3821}3822}38233824/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with3825given color type, but the given color type must be 16-bit itself.*/3826static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,3827const unsigned char* in, size_t i, const LodePNGColorMode* mode) {3828if(mode->colortype == LCT_GREY) {3829*r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];3830if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;3831else *a = 65535;3832} else if(mode->colortype == LCT_RGB) {3833*r = 256u * in[i * 6 + 0] + in[i * 6 + 1];3834*g = 256u * in[i * 6 + 2] + in[i * 6 + 3];3835*b = 256u * in[i * 6 + 4] + in[i * 6 + 5];3836if(mode->key_defined3837&& 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r3838&& 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g3839&& 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;3840else *a = 65535;3841} else if(mode->colortype == LCT_GREY_ALPHA) {3842*r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];3843*a = 256u * in[i * 4 + 2] + in[i * 4 + 3];3844} else if(mode->colortype == LCT_RGBA) {3845*r = 256u * in[i * 8 + 0] + in[i * 8 + 1];3846*g = 256u * in[i * 8 + 2] + in[i * 8 + 3];3847*b = 256u * in[i * 8 + 4] + in[i * 8 + 5];3848*a = 256u * in[i * 8 + 6] + in[i * 8 + 7];3849}3850}38513852unsigned lodepng_convert(unsigned char* out, const unsigned char* in,3853const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,3854unsigned w, unsigned h) {3855size_t i;3856ColorTree tree;3857size_t numpixels = (size_t)w * (size_t)h;3858unsigned error = 0;38593860if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) {3861return 107; /* error: must provide palette if input mode is palette */3862}38633864if(lodepng_color_mode_equal(mode_out, mode_in)) {3865size_t numbytes = lodepng_get_raw_size(w, h, mode_in);3866lodepng_memcpy(out, in, numbytes);3867return 0;3868}38693870if(mode_out->colortype == LCT_PALETTE) {3871size_t palettesize = mode_out->palettesize;3872const unsigned char* palette = mode_out->palette;3873size_t palsize = (size_t)1u << mode_out->bitdepth;3874/*if the user specified output palette but did not give the values, assume3875they want the values of the input color type (assuming that one is palette).3876Note that we never create a new palette ourselves.*/3877if(palettesize == 0) {3878palettesize = mode_in->palettesize;3879palette = mode_in->palette;3880/*if the input was also palette with same bitdepth, then the color types are also3881equal, so copy literally. This to preserve the exact indices that were in the PNG3882even in case there are duplicate colors in the palette.*/3883if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {3884size_t numbytes = lodepng_get_raw_size(w, h, mode_in);3885lodepng_memcpy(out, in, numbytes);3886return 0;3887}3888}3889if(palettesize < palsize) palsize = palettesize;3890color_tree_init(&tree);3891for(i = 0; i != palsize; ++i) {3892const unsigned char* p = &palette[i * 4];3893error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);3894if(error) break;3895}3896}38973898if(!error) {3899if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {3900for(i = 0; i != numpixels; ++i) {3901unsigned short r = 0, g = 0, b = 0, a = 0;3902getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);3903rgba16ToPixel(out, i, mode_out, r, g, b, a);3904}3905} else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {3906getPixelColorsRGBA8(out, numpixels, in, mode_in);3907} else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {3908getPixelColorsRGB8(out, numpixels, in, mode_in);3909} else {3910unsigned char r = 0, g = 0, b = 0, a = 0;3911for(i = 0; i != numpixels; ++i) {3912getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);3913error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);3914if(error) break;3915}3916}3917}39183919if(mode_out->colortype == LCT_PALETTE) {3920color_tree_cleanup(&tree);3921}39223923return error;3924}392539263927/* Converts a single rgb color without alpha from one type to another, color bits truncated to3928their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow3929function, do not use to process all pixels of an image. Alpha channel not supported on purpose:3930this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the3931specification it looks like bKGD should ignore the alpha values of the palette since it can use3932any palette index but doesn't have an alpha channel. Idem with ignoring color key. */3933unsigned lodepng_convert_rgb(3934unsigned* r_out, unsigned* g_out, unsigned* b_out,3935unsigned r_in, unsigned g_in, unsigned b_in,3936const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) {3937unsigned r = 0, g = 0, b = 0;3938unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/3939unsigned shift = 16 - mode_out->bitdepth;39403941if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {3942r = g = b = r_in * mul;3943} else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {3944r = r_in * mul;3945g = g_in * mul;3946b = b_in * mul;3947} else if(mode_in->colortype == LCT_PALETTE) {3948if(r_in >= mode_in->palettesize) return 82;3949r = mode_in->palette[r_in * 4 + 0] * 257u;3950g = mode_in->palette[r_in * 4 + 1] * 257u;3951b = mode_in->palette[r_in * 4 + 2] * 257u;3952} else {3953return 31;3954}39553956/* now convert to output format */3957if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {3958*r_out = r >> shift ;3959} else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {3960*r_out = r >> shift ;3961*g_out = g >> shift ;3962*b_out = b >> shift ;3963} else if(mode_out->colortype == LCT_PALETTE) {3964unsigned i;3965/* a 16-bit color cannot be in the palette */3966if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;3967for(i = 0; i < mode_out->palettesize; i++) {3968unsigned j = i * 4;3969if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&3970(b >> 8) == mode_out->palette[j + 2]) {3971*r_out = i;3972return 0;3973}3974}3975return 82;3976} else {3977return 31;3978}39793980return 0;3981}39823983#ifdef LODEPNG_COMPILE_ENCODER39843985void lodepng_color_stats_init(LodePNGColorStats* stats) {3986/*stats*/3987stats->colored = 0;3988stats->key = 0;3989stats->key_r = stats->key_g = stats->key_b = 0;3990stats->alpha = 0;3991stats->numcolors = 0;3992stats->bits = 1;3993stats->numpixels = 0;3994/*settings*/3995stats->allow_palette = 1;3996stats->allow_greyscale = 1;3997}39983999/*function used for debug purposes with C++*/4000/*void printColorStats(LodePNGColorStats* p) {4001std::cout << "colored: " << (int)p->colored << ", ";4002std::cout << "key: " << (int)p->key << ", ";4003std::cout << "key_r: " << (int)p->key_r << ", ";4004std::cout << "key_g: " << (int)p->key_g << ", ";4005std::cout << "key_b: " << (int)p->key_b << ", ";4006std::cout << "alpha: " << (int)p->alpha << ", ";4007std::cout << "numcolors: " << (int)p->numcolors << ", ";4008std::cout << "bits: " << (int)p->bits << std::endl;4009}*/40104011/*Returns how many bits needed to represent given value (max 8 bit)*/4012static unsigned getValueRequiredBits(unsigned char value) {4013if(value == 0 || value == 255) return 1;4014/*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/4015if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;4016return 8;4017}40184019/*stats must already have been inited. */4020unsigned lodepng_compute_color_stats(LodePNGColorStats* stats,4021const unsigned char* in, unsigned w, unsigned h,4022const LodePNGColorMode* mode_in) {4023size_t i;4024ColorTree tree;4025size_t numpixels = (size_t)w * (size_t)h;4026unsigned error = 0;40274028/* mark things as done already if it would be impossible to have a more expensive case */4029unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;4030unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;4031unsigned numcolors_done = 0;4032unsigned bpp = lodepng_get_bpp(mode_in);4033unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0;4034unsigned sixteen = 0; /* whether the input image is 16 bit */4035unsigned maxnumcolors = 257;4036if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp));40374038stats->numpixels += numpixels;40394040/*if palette not allowed, no need to compute numcolors*/4041if(!stats->allow_palette) numcolors_done = 1;40424043color_tree_init(&tree);40444045/*If the stats was already filled in from previous data, fill its palette in tree4046and mark things as done already if we know they are the most expensive case already*/4047if(stats->alpha) alpha_done = 1;4048if(stats->colored) colored_done = 1;4049if(stats->bits == 16) numcolors_done = 1;4050if(stats->bits >= bpp) bits_done = 1;4051if(stats->numcolors >= maxnumcolors) numcolors_done = 1;40524053if(!numcolors_done) {4054for(i = 0; i < stats->numcolors; i++) {4055const unsigned char* color = &stats->palette[i * 4];4056error = color_tree_add(&tree, color[0], color[1], color[2], color[3], (unsigned)i);4057if(error) goto cleanup;4058}4059}40604061/*Check if the 16-bit input is truly 16-bit*/4062if(mode_in->bitdepth == 16 && !sixteen) {4063unsigned short r = 0, g = 0, b = 0, a = 0;4064for(i = 0; i != numpixels; ++i) {4065getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);4066if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||4067(b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ {4068stats->bits = 16;4069sixteen = 1;4070bits_done = 1;4071numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/4072break;4073}4074}4075}40764077if(sixteen) {4078unsigned short r = 0, g = 0, b = 0, a = 0;40794080for(i = 0; i != numpixels; ++i) {4081getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);40824083if(!colored_done && (r != g || r != b)) {4084stats->colored = 1;4085colored_done = 1;4086}40874088if(!alpha_done) {4089unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);4090if(a != 65535 && (a != 0 || (stats->key && !matchkey))) {4091stats->alpha = 1;4092stats->key = 0;4093alpha_done = 1;4094} else if(a == 0 && !stats->alpha && !stats->key) {4095stats->key = 1;4096stats->key_r = r;4097stats->key_g = g;4098stats->key_b = b;4099} else if(a == 65535 && stats->key && matchkey) {4100/* Color key cannot be used if an opaque pixel also has that RGB color. */4101stats->alpha = 1;4102stats->key = 0;4103alpha_done = 1;4104}4105}4106if(alpha_done && numcolors_done && colored_done && bits_done) break;4107}41084109if(stats->key && !stats->alpha) {4110for(i = 0; i != numpixels; ++i) {4111getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);4112if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {4113/* Color key cannot be used if an opaque pixel also has that RGB color. */4114stats->alpha = 1;4115stats->key = 0;4116alpha_done = 1;4117}4118}4119}4120} else /* < 16-bit */ {4121unsigned char r = 0, g = 0, b = 0, a = 0;4122unsigned char pr = 0, pg = 0, pb = 0, pa = 0;4123for(i = 0; i != numpixels; ++i) {4124getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);41254126/*skip if color same as before, this speeds up large non-photographic4127images with many same colors by avoiding 'color_tree_has' below */4128if(i != 0 && r == pr && g == pg && b == pb && a == pa) continue;4129pr = r;4130pg = g;4131pb = b;4132pa = a;41334134if(!bits_done && stats->bits < 8) {4135/*only r is checked, < 8 bits is only relevant for grayscale*/4136unsigned bits = getValueRequiredBits(r);4137if(bits > stats->bits) stats->bits = bits;4138}4139bits_done = (stats->bits >= bpp);41404141if(!colored_done && (r != g || r != b)) {4142stats->colored = 1;4143colored_done = 1;4144if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/4145}41464147if(!alpha_done) {4148unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);4149if(a != 255 && (a != 0 || (stats->key && !matchkey))) {4150stats->alpha = 1;4151stats->key = 0;4152alpha_done = 1;4153if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/4154} else if(a == 0 && !stats->alpha && !stats->key) {4155stats->key = 1;4156stats->key_r = r;4157stats->key_g = g;4158stats->key_b = b;4159} else if(a == 255 && stats->key && matchkey) {4160/* Color key cannot be used if an opaque pixel also has that RGB color. */4161stats->alpha = 1;4162stats->key = 0;4163alpha_done = 1;4164if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/4165}4166}41674168if(!numcolors_done) {4169if(!color_tree_has(&tree, r, g, b, a)) {4170error = color_tree_add(&tree, r, g, b, a, stats->numcolors);4171if(error) goto cleanup;4172if(stats->numcolors < 256) {4173unsigned char* p = stats->palette;4174unsigned n = stats->numcolors;4175p[n * 4 + 0] = r;4176p[n * 4 + 1] = g;4177p[n * 4 + 2] = b;4178p[n * 4 + 3] = a;4179}4180++stats->numcolors;4181numcolors_done = stats->numcolors >= maxnumcolors;4182}4183}41844185if(alpha_done && numcolors_done && colored_done && bits_done) break;4186}41874188if(stats->key && !stats->alpha) {4189for(i = 0; i != numpixels; ++i) {4190getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);4191if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {4192/* Color key cannot be used if an opaque pixel also has that RGB color. */4193stats->alpha = 1;4194stats->key = 0;4195alpha_done = 1;4196if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/4197}4198}4199}42004201/*make the stats's key always 16-bit for consistency - repeat each byte twice*/4202stats->key_r += (stats->key_r << 8);4203stats->key_g += (stats->key_g << 8);4204stats->key_b += (stats->key_b << 8);4205}42064207cleanup:4208color_tree_cleanup(&tree);4209return error;4210}42114212#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS4213/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit4214(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for4215all pixels of an image but only for a few additional values. */4216static unsigned lodepng_color_stats_add(LodePNGColorStats* stats,4217unsigned r, unsigned g, unsigned b, unsigned a) {4218unsigned error = 0;4219unsigned char image[8];4220LodePNGColorMode mode;4221lodepng_color_mode_init(&mode);4222image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g;4223image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a;4224mode.bitdepth = 16;4225mode.colortype = LCT_RGBA;4226error = lodepng_compute_color_stats(stats, image, 1, 1, &mode);4227lodepng_color_mode_cleanup(&mode);4228return error;4229}4230#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/42314232/*Computes a minimal PNG color model that can contain all colors as indicated by the stats.4233The stats should be computed with lodepng_compute_color_stats.4234mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant.4235Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image,4236e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ...4237This is used if auto_convert is enabled (it is by default).4238*/4239static unsigned auto_choose_color(LodePNGColorMode* mode_out,4240const LodePNGColorMode* mode_in,4241const LodePNGColorStats* stats) {4242unsigned error = 0;4243unsigned palettebits;4244size_t i, n;4245size_t numpixels = stats->numpixels;4246unsigned palette_ok, gray_ok;42474248unsigned alpha = stats->alpha;4249unsigned key = stats->key;4250unsigned bits = stats->bits;42514252mode_out->key_defined = 0;42534254if(key && numpixels <= 16) {4255alpha = 1; /*too few pixels to justify tRNS chunk overhead*/4256key = 0;4257if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/4258}42594260gray_ok = !stats->colored;4261if(!stats->allow_greyscale) gray_ok = 0;4262if(!gray_ok && bits < 8) bits = 8;42634264n = stats->numcolors;4265palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));4266palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/4267if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/4268if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/4269if(!stats->allow_palette) palette_ok = 0;42704271if(palette_ok) {4272const unsigned char* p = stats->palette;4273lodepng_palette_clear(mode_out); /*remove potential earlier palette*/4274for(i = 0; i != stats->numcolors; ++i) {4275error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);4276if(error) break;4277}42784279mode_out->colortype = LCT_PALETTE;4280mode_out->bitdepth = palettebits;42814282if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize4283&& mode_in->bitdepth == mode_out->bitdepth) {4284/*If input should have same palette colors, keep original to preserve its order and prevent conversion*/4285lodepng_color_mode_cleanup(mode_out); /*clears palette, keeps the above set colortype and bitdepth fields as-is*/4286lodepng_color_mode_copy(mode_out, mode_in);4287}4288} else /*8-bit or 16-bit per channel*/ {4289mode_out->bitdepth = bits;4290mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA)4291: (gray_ok ? LCT_GREY : LCT_RGB);4292if(key) {4293unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/4294mode_out->key_r = stats->key_r & mask;4295mode_out->key_g = stats->key_g & mask;4296mode_out->key_b = stats->key_b & mask;4297mode_out->key_defined = 1;4298}4299}43004301return error;4302}43034304#endif /* #ifdef LODEPNG_COMPILE_ENCODER */43054306/*Paeth predictor, used by PNG filter type 4*/4307static unsigned char paethPredictor(unsigned char a, unsigned char b, unsigned char c) {4308/* the subtractions of unsigned char cast it to a signed type.4309With gcc, short is faster than int, with clang int is as fast (as of april 2023)*/4310short pa = (b - c) < 0 ? -(b - c) : (b - c);4311short pb = (a - c) < 0 ? -(a - c) : (a - c);4312/* writing it out like this compiles to something faster than introducing a temp variable*/4313short pc = (a + b - c - c) < 0 ? -(a + b - c - c) : (a + b - c - c);4314/* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */4315if(pb < pa) { a = b; pa = pb; }4316return (pc < pa) ? c : a;4317}43184319/*shared values used by multiple Adam7 related functions*/43204321static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/4322static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/4323static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/4324static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/43254326/*4327Outputs various dimensions and positions in the image related to the Adam7 reduced images.4328passw: output containing the width of the 7 passes4329passh: output containing the height of the 7 passes4330filter_passstart: output containing the index of the start and end of each4331reduced image with filter bytes4332padded_passstart output containing the index of the start and end of each4333reduced image when without filter bytes but with padded scanlines4334passstart: output containing the index of the start and end of each reduced4335image without padding between scanlines, but still padding between the images4336w, h: width and height of non-interlaced image4337bpp: bits per pixel4338"padded" is only relevant if bpp is less than 8 and a scanline or image does not4339end at a full byte4340*/4341static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],4342size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) {4343/*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/4344unsigned i;43454346/*calculate width and height in pixels of each pass*/4347for(i = 0; i != 7; ++i) {4348passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];4349passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];4350if(passw[i] == 0) passh[i] = 0;4351if(passh[i] == 0) passw[i] = 0;4352}43534354filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;4355for(i = 0; i != 7; ++i) {4356/*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/4357filter_passstart[i + 1] = filter_passstart[i]4358+ ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);4359/*bits padded if needed to fill full byte at end of each scanline*/4360padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);4361/*only padded at end of reduced image*/4362passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;4363}4364}43654366#ifdef LODEPNG_COMPILE_DECODER43674368/* ////////////////////////////////////////////////////////////////////////// */4369/* / PNG Decoder / */4370/* ////////////////////////////////////////////////////////////////////////// */43714372/*read the information from the header and store it in the LodePNGInfo. return value is error*/4373unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,4374const unsigned char* in, size_t insize) {4375unsigned width, height;4376LodePNGInfo* info = &state->info_png;4377if(insize == 0 || in == 0) {4378CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/4379}4380if(insize < 33) {4381CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/4382}43834384/*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/4385/* TODO: remove this. One should use a new LodePNGState for new sessions */4386lodepng_info_cleanup(info);4387lodepng_info_init(info);43884389if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 714390|| in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {4391CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/4392}4393if(lodepng_chunk_length(in + 8) != 13) {4394CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/4395}4396if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {4397CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/4398}43994400/*read the values given in the header*/4401width = lodepng_read32bitInt(&in[16]);4402height = lodepng_read32bitInt(&in[20]);4403/*TODO: remove the undocumented feature that allows to give null pointers to width or height*/4404if(w) *w = width;4405if(h) *h = height;4406info->color.bitdepth = in[24];4407info->color.colortype = (LodePNGColorType)in[25];4408info->compression_method = in[26];4409info->filter_method = in[27];4410info->interlace_method = in[28];44114412/*errors returned only after the parsing so other values are still output*/44134414/*error: invalid image size*/4415if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);4416/*error: invalid colortype or bitdepth combination*/4417state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);4418if(state->error) return state->error;4419/*error: only compression method 0 is allowed in the specification*/4420if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);4421/*error: only filter method 0 is allowed in the specification*/4422if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);4423/*error: only interlace methods 0 and 1 exist in the specification*/4424if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);44254426if(!state->decoder.ignore_crc) {4427unsigned CRC = lodepng_read32bitInt(&in[29]);4428unsigned checksum = lodepng_crc32(&in[12], 17);4429if(CRC != checksum) {4430CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/4431}4432}44334434return state->error;4435}44364437static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,4438size_t bytewidth, unsigned char filterType, size_t length) {4439/*4440For PNG filter method 04441unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,4442the filter works byte per byte (bytewidth = 1)4443precon is the previous unfiltered scanline, recon the result, scanline the current one4444the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead4445recon and scanline MAY be the same memory address! precon must be disjoint.4446*/44474448size_t i;4449switch(filterType) {4450case 0:4451for(i = 0; i != length; ++i) recon[i] = scanline[i];4452break;4453case 1: {4454size_t j = 0;4455for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];4456for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + recon[j];4457break;4458}4459case 2:4460if(precon) {4461for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];4462} else {4463for(i = 0; i != length; ++i) recon[i] = scanline[i];4464}4465break;4466case 3:4467if(precon) {4468size_t j = 0;4469for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);4470/* Unroll independent paths of this predictor. A 6x and 8x version is also possible but that adds4471too much code. Whether this speeds up anything depends on compiler and settings. */4472if(bytewidth >= 4) {4473for(; i + 3 < length; i += 4, j += 4) {4474unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];4475unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];4476unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];4477recon[i + 0] = s0 + ((r0 + p0) >> 1u);4478recon[i + 1] = s1 + ((r1 + p1) >> 1u);4479recon[i + 2] = s2 + ((r2 + p2) >> 1u);4480recon[i + 3] = s3 + ((r3 + p3) >> 1u);4481}4482} else if(bytewidth >= 3) {4483for(; i + 2 < length; i += 3, j += 3) {4484unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];4485unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];4486unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];4487recon[i + 0] = s0 + ((r0 + p0) >> 1u);4488recon[i + 1] = s1 + ((r1 + p1) >> 1u);4489recon[i + 2] = s2 + ((r2 + p2) >> 1u);4490}4491} else if(bytewidth >= 2) {4492for(; i + 1 < length; i += 2, j += 2) {4493unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];4494unsigned char r0 = recon[j + 0], r1 = recon[j + 1];4495unsigned char p0 = precon[i + 0], p1 = precon[i + 1];4496recon[i + 0] = s0 + ((r0 + p0) >> 1u);4497recon[i + 1] = s1 + ((r1 + p1) >> 1u);4498}4499}4500for(; i != length; ++i, ++j) recon[i] = scanline[i] + ((recon[j] + precon[i]) >> 1u);4501} else {4502size_t j = 0;4503for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];4504for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + (recon[j] >> 1u);4505}4506break;4507case 4:4508if(precon) {4509/* Unroll independent paths of this predictor. Whether this speeds up4510anything depends on compiler and settings. */4511if(bytewidth == 8) {4512unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;4513unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;4514unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0;4515unsigned char a6, b6 = 0, c6, d6 = 0, a7, b7 = 0, c7, d7 = 0;4516for(i = 0; i + 7 < length; i += 8) {4517c0 = b0; c1 = b1; c2 = b2; c3 = b3;4518c4 = b4; c5 = b5; c6 = b6; c7 = b7;4519b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3];4520b4 = precon[i + 4]; b5 = precon[i + 5]; b6 = precon[i + 6]; b7 = precon[i + 7];4521a0 = d0; a1 = d1; a2 = d2; a3 = d3;4522a4 = d4; a5 = d5; a6 = d6; a7 = d7;4523d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);4524d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);4525d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);4526d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);4527d4 = scanline[i + 4] + paethPredictor(a4, b4, c4);4528d5 = scanline[i + 5] + paethPredictor(a5, b5, c5);4529d6 = scanline[i + 6] + paethPredictor(a6, b6, c6);4530d7 = scanline[i + 7] + paethPredictor(a7, b7, c7);4531recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3;4532recon[i + 4] = d4; recon[i + 5] = d5; recon[i + 6] = d6; recon[i + 7] = d7;4533}4534} else if(bytewidth == 6) {4535unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;4536unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;4537unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0;4538for(i = 0; i + 5 < length; i += 6) {4539c0 = b0; c1 = b1; c2 = b2;4540c3 = b3; c4 = b4; c5 = b5;4541b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2];4542b3 = precon[i + 3]; b4 = precon[i + 4]; b5 = precon[i + 5];4543a0 = d0; a1 = d1; a2 = d2;4544a3 = d3; a4 = d4; a5 = d5;4545d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);4546d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);4547d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);4548d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);4549d4 = scanline[i + 4] + paethPredictor(a4, b4, c4);4550d5 = scanline[i + 5] + paethPredictor(a5, b5, c5);4551recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2;4552recon[i + 3] = d3; recon[i + 4] = d4; recon[i + 5] = d5;4553}4554} else if(bytewidth == 4) {4555unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;4556unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;4557for(i = 0; i + 3 < length; i += 4) {4558c0 = b0; c1 = b1; c2 = b2; c3 = b3;4559b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3];4560a0 = d0; a1 = d1; a2 = d2; a3 = d3;4561d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);4562d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);4563d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);4564d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);4565recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3;4566}4567} else if(bytewidth == 3) {4568unsigned char a0, b0 = 0, c0, d0 = 0;4569unsigned char a1, b1 = 0, c1, d1 = 0;4570unsigned char a2, b2 = 0, c2, d2 = 0;4571for(i = 0; i + 2 < length; i += 3) {4572c0 = b0; c1 = b1; c2 = b2;4573b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2];4574a0 = d0; a1 = d1; a2 = d2;4575d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);4576d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);4577d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);4578recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2;4579}4580} else if(bytewidth == 2) {4581unsigned char a0, b0 = 0, c0, d0 = 0;4582unsigned char a1, b1 = 0, c1, d1 = 0;4583for(i = 0; i + 1 < length; i += 2) {4584c0 = b0; c1 = b1;4585b0 = precon[i + 0];4586b1 = precon[i + 1];4587a0 = d0; a1 = d1;4588d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);4589d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);4590recon[i + 0] = d0;4591recon[i + 1] = d1;4592}4593} else if(bytewidth == 1) {4594unsigned char a, b = 0, c, d = 0;4595for(i = 0; i != length; ++i) {4596c = b;4597b = precon[i];4598a = d;4599d = scanline[i] + paethPredictor(a, b, c);4600recon[i] = d;4601}4602} else {4603/* Normally not a possible case, but this would handle it correctly */4604for(i = 0; i != bytewidth; ++i) {4605recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/4606}4607}4608/* finish any remaining bytes */4609for(; i != length; ++i) {4610recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));4611}4612} else {4613size_t j = 0;4614for(i = 0; i != bytewidth; ++i) {4615recon[i] = scanline[i];4616}4617for(i = bytewidth; i != length; ++i, ++j) {4618/*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/4619recon[i] = (scanline[i] + recon[j]);4620}4621}4622break;4623default: return 36; /*error: invalid filter type given*/4624}4625return 0;4626}46274628static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {4629/*4630For PNG filter method 04631this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)4632out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline4633w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel4634in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)4635*/46364637unsigned y;4638unsigned char* prevline = 0;46394640/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/4641size_t bytewidth = (bpp + 7u) / 8u;4642/*the width of a scanline in bytes, not including the filter type*/4643size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;46444645for(y = 0; y < h; ++y) {4646size_t outindex = linebytes * y;4647size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/4648unsigned char filterType = in[inindex];46494650CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));46514652prevline = &out[outindex];4653}46544655return 0;4656}46574658/*4659in: Adam7 interlaced image, with no padding bits between scanlines, but between4660reduced images so that each reduced image starts at a byte.4661out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h4662bpp: bits per pixel4663out has the following size in bits: w * h * bpp.4664in is possibly bigger due to padding bits between reduced images.4665out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation4666(because that's likely a little bit faster)4667NOTE: comments about padding bits are only relevant if bpp < 84668*/4669static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {4670unsigned passw[7], passh[7];4671size_t filter_passstart[8], padded_passstart[8], passstart[8];4672unsigned i;46734674Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);46754676if(bpp >= 8) {4677for(i = 0; i != 7; ++i) {4678unsigned x, y, b;4679size_t bytewidth = bpp / 8u;4680for(y = 0; y < passh[i]; ++y)4681for(x = 0; x < passw[i]; ++x) {4682size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;4683size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w4684+ ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth;4685for(b = 0; b < bytewidth; ++b) {4686out[pixeloutstart + b] = in[pixelinstart + b];4687}4688}4689}4690} else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {4691for(i = 0; i != 7; ++i) {4692unsigned x, y, b;4693unsigned ilinebits = bpp * passw[i];4694unsigned olinebits = bpp * w;4695size_t obp, ibp; /*bit pointers (for out and in buffer)*/4696for(y = 0; y < passh[i]; ++y)4697for(x = 0; x < passw[i]; ++x) {4698ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);4699obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp;4700for(b = 0; b < bpp; ++b) {4701unsigned char bit = readBitFromReversedStream(&ibp, in);4702setBitOfReversedStream(&obp, out, bit);4703}4704}4705}4706}4707}47084709static void removePaddingBits(unsigned char* out, const unsigned char* in,4710size_t olinebits, size_t ilinebits, unsigned h) {4711/*4712After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need4713to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers4714for the Adam7 code, the color convert code and the output to the user.4715in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must4716have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits4717also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam74718only useful if (ilinebits - olinebits) is a value in the range 1..74719*/4720unsigned y;4721size_t diff = ilinebits - olinebits;4722size_t ibp = 0, obp = 0; /*input and output bit pointers*/4723for(y = 0; y < h; ++y) {4724size_t x;4725for(x = 0; x < olinebits; ++x) {4726unsigned char bit = readBitFromReversedStream(&ibp, in);4727setBitOfReversedStream(&obp, out, bit);4728}4729ibp += diff;4730}4731}47324733/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from4734the IDAT chunks (with filter index bytes and possible padding bits)4735return value is error*/4736static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,4737unsigned w, unsigned h, const LodePNGInfo* info_png) {4738/*4739This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.4740Steps:4741*) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)4742*) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace4743NOTE: the in buffer will be overwritten with intermediate data!4744*/4745unsigned bpp = lodepng_get_bpp(&info_png->color);4746if(bpp == 0) return 31; /*error: invalid colortype*/47474748if(info_png->interlace_method == 0) {4749if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {4750CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));4751removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);4752}4753/*we can immediately filter into the out buffer, no other steps needed*/4754else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));4755} else /*interlace_method is 1 (Adam7)*/ {4756unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];4757unsigned i;47584759Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);47604761for(i = 0; i != 7; ++i) {4762CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));4763/*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,4764move bytes instead of bits or move not at all*/4765if(bpp < 8) {4766/*remove padding bits in scanlines; after this there still may be padding4767bits between the different reduced images: each reduced image still starts nicely at a byte*/4768removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,4769((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);4770}4771}47724773Adam7_deinterlace(out, in, w, h, bpp);4774}47754776return 0;4777}47784779static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {4780unsigned pos = 0, i;4781color->palettesize = chunkLength / 3u;4782if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/4783lodepng_color_mode_alloc_palette(color);4784if(!color->palette && color->palettesize) {4785color->palettesize = 0;4786return 83; /*alloc fail*/4787}47884789for(i = 0; i != color->palettesize; ++i) {4790color->palette[4 * i + 0] = data[pos++]; /*R*/4791color->palette[4 * i + 1] = data[pos++]; /*G*/4792color->palette[4 * i + 2] = data[pos++]; /*B*/4793color->palette[4 * i + 3] = 255; /*alpha*/4794}47954796return 0; /* OK */4797}47984799static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {4800unsigned i;4801if(color->colortype == LCT_PALETTE) {4802/*error: more alpha values given than there are palette entries*/4803if(chunkLength > color->palettesize) return 39;48044805for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];4806} else if(color->colortype == LCT_GREY) {4807/*error: this chunk must be 2 bytes for grayscale image*/4808if(chunkLength != 2) return 30;48094810color->key_defined = 1;4811color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];4812} else if(color->colortype == LCT_RGB) {4813/*error: this chunk must be 6 bytes for RGB image*/4814if(chunkLength != 6) return 41;48154816color->key_defined = 1;4817color->key_r = 256u * data[0] + data[1];4818color->key_g = 256u * data[2] + data[3];4819color->key_b = 256u * data[4] + data[5];4820}4821else return 42; /*error: tRNS chunk not allowed for other color models*/48224823return 0; /* OK */4824}482548264827#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS4828/*background color chunk (bKGD)*/4829static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {4830if(info->color.colortype == LCT_PALETTE) {4831/*error: this chunk must be 1 byte for indexed color image*/4832if(chunkLength != 1) return 43;48334834/*error: invalid palette index, or maybe this chunk appeared before PLTE*/4835if(data[0] >= info->color.palettesize) return 103;48364837info->background_defined = 1;4838info->background_r = info->background_g = info->background_b = data[0];4839} else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {4840/*error: this chunk must be 2 bytes for grayscale image*/4841if(chunkLength != 2) return 44;48424843/*the values are truncated to bitdepth in the PNG file*/4844info->background_defined = 1;4845info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];4846} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {4847/*error: this chunk must be 6 bytes for grayscale image*/4848if(chunkLength != 6) return 45;48494850/*the values are truncated to bitdepth in the PNG file*/4851info->background_defined = 1;4852info->background_r = 256u * data[0] + data[1];4853info->background_g = 256u * data[2] + data[3];4854info->background_b = 256u * data[4] + data[5];4855}48564857return 0; /* OK */4858}48594860/*text chunk (tEXt)*/4861static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {4862unsigned error = 0;4863char *key = 0, *str = 0;48644865while(!error) /*not really a while loop, only used to break on error*/ {4866unsigned length, string2_begin;48674868length = 0;4869while(length < chunkLength && data[length] != 0) ++length;4870/*even though it's not allowed by the standard, no error is thrown if4871there's no null termination char, if the text is empty*/4872if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/48734874key = (char*)lodepng_malloc(length + 1);4875if(!key) CERROR_BREAK(error, 83); /*alloc fail*/48764877lodepng_memcpy(key, data, length);4878key[length] = 0;48794880string2_begin = length + 1; /*skip keyword null terminator*/48814882length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);4883str = (char*)lodepng_malloc(length + 1);4884if(!str) CERROR_BREAK(error, 83); /*alloc fail*/48854886lodepng_memcpy(str, data + string2_begin, length);4887str[length] = 0;48884889error = lodepng_add_text(info, key, str);48904891break;4892}48934894lodepng_free(key);4895lodepng_free(str);48964897return error;4898}48994900/*compressed text chunk (zTXt)*/4901static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,4902const unsigned char* data, size_t chunkLength) {4903unsigned error = 0;49044905/*copy the object to change parameters in it*/4906LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;49074908unsigned length, string2_begin;4909char *key = 0;4910unsigned char* str = 0;4911size_t size = 0;49124913while(!error) /*not really a while loop, only used to break on error*/ {4914for(length = 0; length < chunkLength && data[length] != 0; ++length) ;4915if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/4916if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/49174918key = (char*)lodepng_malloc(length + 1);4919if(!key) CERROR_BREAK(error, 83); /*alloc fail*/49204921lodepng_memcpy(key, data, length);4922key[length] = 0;49234924if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/49254926string2_begin = length + 2;4927if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/49284929length = (unsigned)chunkLength - string2_begin;4930zlibsettings.max_output_size = decoder->max_text_size;4931/*will fail if zlib error, e.g. if length is too small*/4932error = zlib_decompress(&str, &size, 0, &data[string2_begin],4933length, &zlibsettings);4934/*error: compressed text larger than decoder->max_text_size*/4935if(error && size > zlibsettings.max_output_size) error = 112;4936if(error) break;4937error = lodepng_add_text_sized(info, key, (char*)str, size);4938break;4939}49404941lodepng_free(key);4942lodepng_free(str);49434944return error;4945}49464947/*international text chunk (iTXt)*/4948static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,4949const unsigned char* data, size_t chunkLength) {4950unsigned error = 0;4951unsigned i;49524953/*copy the object to change parameters in it*/4954LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;49554956unsigned length, begin, compressed;4957char *key = 0, *langtag = 0, *transkey = 0;49584959while(!error) /*not really a while loop, only used to break on error*/ {4960/*Quick check if the chunk length isn't too small. Even without check4961it'd still fail with other error checks below if it's too short. This just gives a different error code.*/4962if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/49634964/*read the key*/4965for(length = 0; length < chunkLength && data[length] != 0; ++length) ;4966if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/4967if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/49684969key = (char*)lodepng_malloc(length + 1);4970if(!key) CERROR_BREAK(error, 83); /*alloc fail*/49714972lodepng_memcpy(key, data, length);4973key[length] = 0;49744975/*read the compression method*/4976compressed = data[length + 1];4977if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/49784979/*even though it's not allowed by the standard, no error is thrown if4980there's no null termination char, if the text is empty for the next 3 texts*/49814982/*read the langtag*/4983begin = length + 3;4984length = 0;4985for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;49864987langtag = (char*)lodepng_malloc(length + 1);4988if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/49894990lodepng_memcpy(langtag, data + begin, length);4991langtag[length] = 0;49924993/*read the transkey*/4994begin += length + 1;4995length = 0;4996for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;49974998transkey = (char*)lodepng_malloc(length + 1);4999if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/50005001lodepng_memcpy(transkey, data + begin, length);5002transkey[length] = 0;50035004/*read the actual text*/5005begin += length + 1;50065007length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;50085009if(compressed) {5010unsigned char* str = 0;5011size_t size = 0;5012zlibsettings.max_output_size = decoder->max_text_size;5013/*will fail if zlib error, e.g. if length is too small*/5014error = zlib_decompress(&str, &size, 0, &data[begin],5015length, &zlibsettings);5016/*error: compressed text larger than decoder->max_text_size*/5017if(error && size > zlibsettings.max_output_size) error = 112;5018if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)str, size);5019lodepng_free(str);5020} else {5021error = lodepng_add_itext_sized(info, key, langtag, transkey, (const char*)(data + begin), length);5022}50235024break;5025}50265027lodepng_free(key);5028lodepng_free(langtag);5029lodepng_free(transkey);50305031return error;5032}50335034static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5035if(chunkLength != 7) return 73; /*invalid tIME chunk size*/50365037info->time_defined = 1;5038info->time.year = 256u * data[0] + data[1];5039info->time.month = data[2];5040info->time.day = data[3];5041info->time.hour = data[4];5042info->time.minute = data[5];5043info->time.second = data[6];50445045return 0; /* OK */5046}50475048static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5049if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/50505051info->phys_defined = 1;5052info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];5053info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];5054info->phys_unit = data[8];50555056return 0; /* OK */5057}50585059static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5060if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/50615062info->gama_defined = 1;5063info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];50645065return 0; /* OK */5066}50675068static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5069if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/50705071info->chrm_defined = 1;5072info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];5073info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];5074info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];5075info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];5076info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];5077info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];5078info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];5079info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];50805081return 0; /* OK */5082}50835084static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5085if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/50865087info->srgb_defined = 1;5088info->srgb_intent = data[0];50895090return 0; /* OK */5091}50925093static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,5094const unsigned char* data, size_t chunkLength) {5095unsigned error = 0;5096unsigned i;5097size_t size = 0;5098/*copy the object to change parameters in it*/5099LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;51005101unsigned length, string2_begin;51025103if(info->iccp_defined) lodepng_clear_icc(info);5104info->iccp_defined = 1;51055106for(length = 0; length < chunkLength && data[length] != 0; ++length) ;5107if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/5108if(length < 1 || length > 79) return 89; /*keyword too short or long*/51095110info->iccp_name = (char*)lodepng_malloc(length + 1);5111if(!info->iccp_name) return 83; /*alloc fail*/51125113info->iccp_name[length] = 0;5114for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];51155116if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/51175118string2_begin = length + 2;5119if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/51205121length = (unsigned)chunkLength - string2_begin;5122zlibsettings.max_output_size = decoder->max_icc_size;5123error = zlib_decompress(&info->iccp_profile, &size, 0,5124&data[string2_begin],5125length, &zlibsettings);5126/*error: ICC profile larger than decoder->max_icc_size*/5127if(error && size > zlibsettings.max_output_size) error = 113;5128info->iccp_profile_size = (unsigned)size;5129if(!error && !info->iccp_profile_size) error = 100; /*invalid ICC profile size*/5130return error;5131}51325133static unsigned readChunk_cICP(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5134if(chunkLength != 4) return 117; /*invalid cICP chunk size*/51355136info->cicp_defined = 1;5137/* No error checking for value ranges is done here, that is up to a CICP5138handling library, not the PNG decoding. Just pass on the metadata. */5139info->cicp_color_primaries = data[0];5140info->cicp_transfer_function = data[1];5141info->cicp_matrix_coefficients = data[2];5142info->cicp_video_full_range_flag = data[3];51435144return 0; /* OK */5145}51465147static unsigned readChunk_mDCV(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5148if(chunkLength != 24) return 119; /*invalid mDCV chunk size*/51495150info->mdcv_defined = 1;5151info->mdcv_red_x = 256u * data[0] + data[1];5152info->mdcv_red_y = 256u * data[2] + data[3];5153info->mdcv_green_x = 256u * data[4] + data[5];5154info->mdcv_green_y = 256u * data[6] + data[7];5155info->mdcv_blue_x = 256u * data[8] + data[9];5156info->mdcv_blue_y = 256u * data[10] + data[11];5157info->mdcv_white_x = 256u * data[12] + data[13];5158info->mdcv_white_y = 256u * data[14] + data[15];5159info->mdcv_max_luminance = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];5160info->mdcv_min_luminance = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];51615162return 0; /* OK */5163}51645165static unsigned readChunk_cLLI(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5166if(chunkLength != 8) return 120; /*invalid cLLI chunk size*/51675168info->clli_defined = 1;5169info->clli_max_cll = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];5170info->clli_max_fall = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];51715172return 0; /* OK */5173}51745175static unsigned readChunk_eXIf(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5176return lodepng_set_exif(info, data, (unsigned)chunkLength);5177}51785179/*significant bits chunk (sBIT)*/5180static unsigned readChunk_sBIT(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {5181unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth;5182if(info->color.colortype == LCT_GREY) {5183/*error: this chunk must be 1 bytes for grayscale image*/5184if(chunkLength != 1) return 114;5185if(data[0] == 0 || data[0] > bitdepth) return 115;5186info->sbit_defined = 1;5187info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/5188} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) {5189/*error: this chunk must be 3 bytes for RGB and palette image*/5190if(chunkLength != 3) return 114;5191if(data[0] == 0 || data[1] == 0 || data[2] == 0) return 115;5192if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth) return 115;5193info->sbit_defined = 1;5194info->sbit_r = data[0];5195info->sbit_g = data[1];5196info->sbit_b = data[2];5197} else if(info->color.colortype == LCT_GREY_ALPHA) {5198/*error: this chunk must be 2 byte for grayscale with alpha image*/5199if(chunkLength != 2) return 114;5200if(data[0] == 0 || data[1] == 0) return 115;5201if(data[0] > bitdepth || data[1] > bitdepth) return 115;5202info->sbit_defined = 1;5203info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/5204info->sbit_a = data[1];5205} else if(info->color.colortype == LCT_RGBA) {5206/*error: this chunk must be 4 bytes for grayscale image*/5207if(chunkLength != 4) return 114;5208if(data[0] == 0 || data[1] == 0 || data[2] == 0 || data[3] == 0) return 115;5209if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth || data[3] > bitdepth) return 115;5210info->sbit_defined = 1;5211info->sbit_r = data[0];5212info->sbit_g = data[1];5213info->sbit_b = data[2];5214info->sbit_a = data[3];5215}52165217return 0; /* OK */5218}5219#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/52205221unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,5222const unsigned char* in, size_t insize) {5223const unsigned char* chunk = in + pos;5224unsigned chunkLength;5225const unsigned char* data;5226unsigned unhandled = 0;5227unsigned error = 0;52285229if(pos + 4 > insize) return 30;5230chunkLength = lodepng_chunk_length(chunk);5231if(chunkLength > 2147483647) return 63;5232data = lodepng_chunk_data_const(chunk);5233if(chunkLength + 12 > insize - pos) return 30;52345235if(lodepng_chunk_type_equals(chunk, "PLTE")) {5236error = readChunk_PLTE(&state->info_png.color, data, chunkLength);5237} else if(lodepng_chunk_type_equals(chunk, "tRNS")) {5238error = readChunk_tRNS(&state->info_png.color, data, chunkLength);5239#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5240} else if(lodepng_chunk_type_equals(chunk, "bKGD")) {5241error = readChunk_bKGD(&state->info_png, data, chunkLength);5242} else if(lodepng_chunk_type_equals(chunk, "tEXt")) {5243error = readChunk_tEXt(&state->info_png, data, chunkLength);5244} else if(lodepng_chunk_type_equals(chunk, "zTXt")) {5245error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);5246} else if(lodepng_chunk_type_equals(chunk, "iTXt")) {5247error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);5248} else if(lodepng_chunk_type_equals(chunk, "tIME")) {5249error = readChunk_tIME(&state->info_png, data, chunkLength);5250} else if(lodepng_chunk_type_equals(chunk, "pHYs")) {5251error = readChunk_pHYs(&state->info_png, data, chunkLength);5252} else if(lodepng_chunk_type_equals(chunk, "gAMA")) {5253error = readChunk_gAMA(&state->info_png, data, chunkLength);5254} else if(lodepng_chunk_type_equals(chunk, "cHRM")) {5255error = readChunk_cHRM(&state->info_png, data, chunkLength);5256} else if(lodepng_chunk_type_equals(chunk, "sRGB")) {5257error = readChunk_sRGB(&state->info_png, data, chunkLength);5258} else if(lodepng_chunk_type_equals(chunk, "iCCP")) {5259error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);5260} else if(lodepng_chunk_type_equals(chunk, "cICP")) {5261error = readChunk_cICP(&state->info_png, data, chunkLength);5262} else if(lodepng_chunk_type_equals(chunk, "mDCV")) {5263error = readChunk_mDCV(&state->info_png, data, chunkLength);5264} else if(lodepng_chunk_type_equals(chunk, "cLLI")) {5265error = readChunk_cLLI(&state->info_png, data, chunkLength);5266} else if(lodepng_chunk_type_equals(chunk, "eXIf")) {5267error = readChunk_eXIf(&state->info_png, data, chunkLength);5268} else if(lodepng_chunk_type_equals(chunk, "sBIT")) {5269error = readChunk_sBIT(&state->info_png, data, chunkLength);5270#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5271} else {5272/* unhandled chunk is ok (is not an error) */5273unhandled = 1;5274}52755276if(!error && !unhandled && !state->decoder.ignore_crc) {5277if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/5278}52795280return error;5281}52825283/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/5284static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,5285LodePNGState* state,5286const unsigned char* in, size_t insize) {5287unsigned char IEND = 0;5288const unsigned char* chunk; /*points to beginning of next chunk*/5289unsigned char* idat; /*the data from idat chunks, zlib compressed*/5290size_t idatsize = 0;5291unsigned char* scanlines = 0;5292size_t scanlines_size = 0, expected_size = 0;5293size_t outsize = 0;52945295/*for unknown chunk order*/5296unsigned unknown = 0;5297#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5298unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/5299#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/530053015302/* safe output values in case error happens */5303*out = 0;5304*w = *h = 0;53055306state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/5307if(state->error) return;53085309if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {5310CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/5311}53125313/*the input filesize is a safe upper bound for the sum of idat chunks size*/5314idat = (unsigned char*)lodepng_malloc(insize);5315if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/53165317chunk = &in[33]; /*first byte of the first chunk after the header*/53185319/*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.5320IDAT data is put at the start of the in buffer*/5321while(!IEND && !state->error) {5322unsigned chunkLength;5323const unsigned char* data; /*the data in the chunk*/5324size_t pos = (size_t)(chunk - in);53255326/*error: next chunk out of bounds of the in buffer*/5327if(chunk < in || pos + 12 > insize) {5328if(state->decoder.ignore_end) break; /*other errors may still happen though*/5329CERROR_BREAK(state->error, 30);5330}53315332/*length of the data of the chunk, excluding the 12 bytes for length, chunk type and CRC*/5333chunkLength = lodepng_chunk_length(chunk);5334/*error: chunk length larger than the max PNG chunk size*/5335if(chunkLength > 2147483647) {5336if(state->decoder.ignore_end) break; /*other errors may still happen though*/5337CERROR_BREAK(state->error, 63);5338}53395340if(pos + (size_t)chunkLength + 12 > insize || pos + (size_t)chunkLength + 12 < pos) {5341CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk (or int overflow)*/5342}53435344data = lodepng_chunk_data_const(chunk);53455346unknown = 0;53475348/*IDAT chunk, containing compressed image data*/5349if(lodepng_chunk_type_equals(chunk, "IDAT")) {5350size_t newsize;5351if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);5352if(newsize > insize) CERROR_BREAK(state->error, 95);5353lodepng_memcpy(idat + idatsize, data, chunkLength);5354idatsize += chunkLength;5355#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5356critical_pos = 3;5357#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5358} else if(lodepng_chunk_type_equals(chunk, "IEND")) {5359/*IEND chunk*/5360IEND = 1;5361} else if(lodepng_chunk_type_equals(chunk, "PLTE")) {5362/*palette chunk (PLTE)*/5363state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);5364if(state->error) break;5365#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5366critical_pos = 2;5367#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5368} else if(lodepng_chunk_type_equals(chunk, "tRNS")) {5369/*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled5370in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that5371affects the alpha channel of pixels. */5372state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);5373if(state->error) break;5374#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5375/*background color chunk (bKGD)*/5376} else if(lodepng_chunk_type_equals(chunk, "bKGD")) {5377state->error = readChunk_bKGD(&state->info_png, data, chunkLength);5378if(state->error) break;5379} else if(lodepng_chunk_type_equals(chunk, "tEXt")) {5380/*text chunk (tEXt)*/5381if(state->decoder.read_text_chunks) {5382state->error = readChunk_tEXt(&state->info_png, data, chunkLength);5383if(state->error) break;5384}5385} else if(lodepng_chunk_type_equals(chunk, "zTXt")) {5386/*compressed text chunk (zTXt)*/5387if(state->decoder.read_text_chunks) {5388state->error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);5389if(state->error) break;5390}5391} else if(lodepng_chunk_type_equals(chunk, "iTXt")) {5392/*international text chunk (iTXt)*/5393if(state->decoder.read_text_chunks) {5394state->error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);5395if(state->error) break;5396}5397} else if(lodepng_chunk_type_equals(chunk, "tIME")) {5398state->error = readChunk_tIME(&state->info_png, data, chunkLength);5399if(state->error) break;5400} else if(lodepng_chunk_type_equals(chunk, "pHYs")) {5401state->error = readChunk_pHYs(&state->info_png, data, chunkLength);5402if(state->error) break;5403} else if(lodepng_chunk_type_equals(chunk, "gAMA")) {5404state->error = readChunk_gAMA(&state->info_png, data, chunkLength);5405if(state->error) break;5406} else if(lodepng_chunk_type_equals(chunk, "cHRM")) {5407state->error = readChunk_cHRM(&state->info_png, data, chunkLength);5408if(state->error) break;5409} else if(lodepng_chunk_type_equals(chunk, "sRGB")) {5410state->error = readChunk_sRGB(&state->info_png, data, chunkLength);5411if(state->error) break;5412} else if(lodepng_chunk_type_equals(chunk, "iCCP")) {5413state->error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);5414if(state->error) break;5415} else if(lodepng_chunk_type_equals(chunk, "cICP")) {5416state->error = readChunk_cICP(&state->info_png, data, chunkLength);5417if(state->error) break;5418} else if(lodepng_chunk_type_equals(chunk, "mDCV")) {5419state->error = readChunk_mDCV(&state->info_png, data, chunkLength);5420if(state->error) break;5421} else if(lodepng_chunk_type_equals(chunk, "cLLI")) {5422state->error = readChunk_cLLI(&state->info_png, data, chunkLength);5423if(state->error) break;5424} else if(lodepng_chunk_type_equals(chunk, "eXIf")) {5425state->error = readChunk_eXIf(&state->info_png, data, chunkLength);5426if(state->error) break;5427} else if(lodepng_chunk_type_equals(chunk, "sBIT")) {5428state->error = readChunk_sBIT(&state->info_png, data, chunkLength);5429if(state->error) break;5430#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5431} else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {5432if(!lodepng_chunk_type_name_valid(chunk)) {5433CERROR_BREAK(state->error, 121); /* invalid chunk type name */5434}5435if(lodepng_chunk_reserved(chunk)) {5436CERROR_BREAK(state->error, 122); /* invalid third lowercase character */5437}54385439/*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/5440if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {5441CERROR_BREAK(state->error, 69);5442}54435444unknown = 1;5445#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5446if(state->decoder.remember_unknown_chunks) {5447state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],5448&state->info_png.unknown_chunks_size[critical_pos - 1], chunk);5449if(state->error) break;5450}5451#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5452}54535454if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {5455if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/5456}54575458if(!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize);5459}54605461if(!state->error && state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) {5462state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */5463}54645465if(!state->error) {5466/*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.5467If the decompressed size does not match the prediction, the image must be corrupt.*/5468if(state->info_png.interlace_method == 0) {5469unsigned bpp = lodepng_get_bpp(&state->info_png.color);5470expected_size = lodepng_get_raw_size_idat(*w, *h, bpp);5471} else {5472unsigned bpp = lodepng_get_bpp(&state->info_png.color);5473/*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/5474expected_size = 0;5475expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp);5476if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp);5477expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp);5478if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp);5479expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp);5480if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp);5481expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp);5482}54835484state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings);5485}5486if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/5487lodepng_free(idat);54885489if(!state->error) {5490outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);5491*out = (unsigned char*)lodepng_malloc(outsize);5492if(!*out) state->error = 83; /*alloc fail*/5493}5494if(!state->error) {5495lodepng_memset(*out, 0, outsize);5496state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);5497}5498lodepng_free(scanlines);5499}55005501unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,5502LodePNGState* state,5503const unsigned char* in, size_t insize) {5504*out = 0;5505decodeGeneric(out, w, h, state, in, insize);5506if(state->error) return state->error;5507if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {5508/*same color type, no copying or converting of data needed*/5509/*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype5510the raw image has to the end user*/5511if(!state->decoder.color_convert) {5512state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);5513if(state->error) return state->error;5514}5515} else { /*color conversion needed*/5516unsigned char* data = *out;5517size_t outsize;55185519/*TODO: check if this works according to the statement in the documentation: "The converter can convert5520from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/5521if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)5522&& !(state->info_raw.bitdepth == 8)) {5523return 56; /*unsupported color mode conversion*/5524}55255526outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);5527*out = (unsigned char*)lodepng_malloc(outsize);5528if(!(*out)) {5529state->error = 83; /*alloc fail*/5530}5531else state->error = lodepng_convert(*out, data, &state->info_raw,5532&state->info_png.color, *w, *h);5533lodepng_free(data);5534}5535return state->error;5536}55375538unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,5539size_t insize, LodePNGColorType colortype, unsigned bitdepth) {5540unsigned error;5541LodePNGState state;5542lodepng_state_init(&state);5543state.info_raw.colortype = colortype;5544state.info_raw.bitdepth = bitdepth;5545#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5546/*disable reading things that this function doesn't output*/5547state.decoder.read_text_chunks = 0;5548state.decoder.remember_unknown_chunks = 0;5549#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5550error = lodepng_decode(out, w, h, &state, in, insize);5551lodepng_state_cleanup(&state);5552return error;5553}55545555unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {5556return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);5557}55585559unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {5560return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);5561}55625563#ifdef LODEPNG_COMPILE_DISK5564unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,5565LodePNGColorType colortype, unsigned bitdepth) {5566unsigned char* buffer = 0;5567size_t buffersize;5568unsigned error;5569/* safe output values in case error happens */5570*out = 0;5571*w = *h = 0;5572error = lodepng_load_file(&buffer, &buffersize, filename);5573if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);5574lodepng_free(buffer);5575return error;5576}55775578unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {5579return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);5580}55815582unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {5583return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);5584}5585#endif /*LODEPNG_COMPILE_DISK*/55865587void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) {5588settings->color_convert = 1;5589#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS5590settings->read_text_chunks = 1;5591settings->remember_unknown_chunks = 0;5592settings->max_text_size = 16777216;5593settings->max_icc_size = 16777216; /* 16MB is much more than enough for any reasonable ICC profile */5594#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/5595settings->ignore_crc = 0;5596settings->ignore_critical = 0;5597settings->ignore_end = 0;5598lodepng_decompress_settings_init(&settings->zlibsettings);5599}56005601#endif /*LODEPNG_COMPILE_DECODER*/56025603#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)56045605void lodepng_state_init(LodePNGState* state) {5606#ifdef LODEPNG_COMPILE_DECODER5607lodepng_decoder_settings_init(&state->decoder);5608#endif /*LODEPNG_COMPILE_DECODER*/5609#ifdef LODEPNG_COMPILE_ENCODER5610lodepng_encoder_settings_init(&state->encoder);5611#endif /*LODEPNG_COMPILE_ENCODER*/5612lodepng_color_mode_init(&state->info_raw);5613lodepng_info_init(&state->info_png);5614state->error = 1;5615}56165617void lodepng_state_cleanup(LodePNGState* state) {5618lodepng_color_mode_cleanup(&state->info_raw);5619lodepng_info_cleanup(&state->info_png);5620}56215622void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) {5623lodepng_state_cleanup(dest);5624*dest = *source;5625lodepng_color_mode_init(&dest->info_raw);5626lodepng_info_init(&dest->info_png);5627dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;5628dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;5629}56305631#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */56325633#ifdef LODEPNG_COMPILE_ENCODER56345635/* ////////////////////////////////////////////////////////////////////////// */5636/* / PNG Encoder / */5637/* ////////////////////////////////////////////////////////////////////////// */563856395640static unsigned writeSignature(ucvector* out) {5641size_t pos = out->size;5642const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10};5643/*8 bytes PNG signature, aka the magic bytes*/5644if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/5645lodepng_memcpy(out->data + pos, signature, 8);5646return 0;5647}56485649static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,5650LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) {5651unsigned char *chunk, *data;5652CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR"));5653data = chunk + 8;56545655lodepng_set32bitInt(data + 0, w); /*width*/5656lodepng_set32bitInt(data + 4, h); /*height*/5657data[8] = (unsigned char)bitdepth; /*bit depth*/5658data[9] = (unsigned char)colortype; /*color type*/5659data[10] = 0; /*compression method*/5660data[11] = 0; /*filter method*/5661data[12] = interlace_method; /*interlace method*/56625663lodepng_chunk_generate_crc(chunk);5664return 0;5665}56665667/* only adds the chunk if needed (there is a key or palette with alpha) */5668static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) {5669unsigned char* chunk;5670size_t i, j = 8;56715672if(info->palettesize == 0 || info->palettesize > 256) {5673return 68; /*invalid palette size, it is only allowed to be 1-256*/5674}56755676CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE"));56775678for(i = 0; i != info->palettesize; ++i) {5679/*add all channels except alpha channel*/5680chunk[j++] = info->palette[i * 4 + 0];5681chunk[j++] = info->palette[i * 4 + 1];5682chunk[j++] = info->palette[i * 4 + 2];5683}56845685lodepng_chunk_generate_crc(chunk);5686return 0;5687}56885689static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) {5690unsigned char* chunk = 0;56915692if(info->colortype == LCT_PALETTE) {5693size_t i, amount = info->palettesize;5694/*the tail of palette values that all have 255 as alpha, does not have to be encoded*/5695for(i = info->palettesize; i != 0; --i) {5696if(info->palette[4 * (i - 1) + 3] != 255) break;5697--amount;5698}5699if(amount) {5700CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS"));5701/*add the alpha channel values from the palette*/5702for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3];5703}5704} else if(info->colortype == LCT_GREY) {5705if(info->key_defined) {5706CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS"));5707chunk[8] = (unsigned char)(info->key_r >> 8);5708chunk[9] = (unsigned char)(info->key_r & 255);5709}5710} else if(info->colortype == LCT_RGB) {5711if(info->key_defined) {5712CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS"));5713chunk[8] = (unsigned char)(info->key_r >> 8);5714chunk[9] = (unsigned char)(info->key_r & 255);5715chunk[10] = (unsigned char)(info->key_g >> 8);5716chunk[11] = (unsigned char)(info->key_g & 255);5717chunk[12] = (unsigned char)(info->key_b >> 8);5718chunk[13] = (unsigned char)(info->key_b & 255);5719}5720}57215722if(chunk) lodepng_chunk_generate_crc(chunk);5723return 0;5724}57255726static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,5727LodePNGCompressSettings* zlibsettings) {5728unsigned error = 0;5729unsigned char* zlib = 0;5730size_t pos = 0;5731size_t zlibsize = 0;5732/* max chunk length allowed by the specification is 2147483647 bytes */5733const size_t max_chunk_length = 2147483647u;57345735error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings);5736while(!error) {5737if(zlibsize - pos > max_chunk_length) {5738error = lodepng_chunk_createv(out, max_chunk_length, "IDAT", zlib + pos);5739pos += max_chunk_length;5740} else {5741error = lodepng_chunk_createv(out, zlibsize - pos, "IDAT", zlib + pos);5742break;5743}5744}5745lodepng_free(zlib);5746return error;5747}57485749static unsigned addChunk_IEND(ucvector* out) {5750return lodepng_chunk_createv(out, 0, "IEND", 0);5751}57525753#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS57545755static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) {5756unsigned char* chunk = 0;5757size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring);5758size_t size = keysize + 1 + textsize;5759if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/5760CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt"));5761lodepng_memcpy(chunk + 8, keyword, keysize);5762chunk[8 + keysize] = 0; /*null termination char*/5763lodepng_memcpy(chunk + 9 + keysize, textstring, textsize);5764lodepng_chunk_generate_crc(chunk);5765return 0;5766}57675768static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,5769LodePNGCompressSettings* zlibsettings) {5770unsigned error = 0;5771unsigned char* chunk = 0;5772unsigned char* compressed = 0;5773size_t compressedsize = 0;5774size_t textsize = lodepng_strlen(textstring);5775size_t keysize = lodepng_strlen(keyword);5776if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/57775778error = zlib_compress(&compressed, &compressedsize,5779(const unsigned char*)textstring, textsize, zlibsettings);5780if(!error) {5781size_t size = keysize + 2 + compressedsize;5782error = lodepng_chunk_init(&chunk, out, size, "zTXt");5783}5784if(!error) {5785lodepng_memcpy(chunk + 8, keyword, keysize);5786chunk[8 + keysize] = 0; /*null termination char*/5787chunk[9 + keysize] = 0; /*compression method: 0*/5788lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);5789lodepng_chunk_generate_crc(chunk);5790}57915792lodepng_free(compressed);5793return error;5794}57955796static unsigned addChunk_iTXt(ucvector* out, unsigned compress, const char* keyword, const char* langtag,5797const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) {5798unsigned error = 0;5799unsigned char* chunk = 0;5800unsigned char* compressed = 0;5801size_t compressedsize = 0;5802size_t textsize = lodepng_strlen(textstring);5803size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey);58045805if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/58065807if(compress) {5808error = zlib_compress(&compressed, &compressedsize,5809(const unsigned char*)textstring, textsize, zlibsettings);5810}5811if(!error) {5812size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize);5813error = lodepng_chunk_init(&chunk, out, size, "iTXt");5814}5815if(!error) {5816size_t pos = 8;5817lodepng_memcpy(chunk + pos, keyword, keysize);5818pos += keysize;5819chunk[pos++] = 0; /*null termination char*/5820chunk[pos++] = (compress ? 1 : 0); /*compression flag*/5821chunk[pos++] = 0; /*compression method: 0*/5822lodepng_memcpy(chunk + pos, langtag, langsize);5823pos += langsize;5824chunk[pos++] = 0; /*null termination char*/5825lodepng_memcpy(chunk + pos, transkey, transsize);5826pos += transsize;5827chunk[pos++] = 0; /*null termination char*/5828if(compress) {5829lodepng_memcpy(chunk + pos, compressed, compressedsize);5830} else {5831lodepng_memcpy(chunk + pos, textstring, textsize);5832}5833lodepng_chunk_generate_crc(chunk);5834}58355836lodepng_free(compressed);5837return error;5838}58395840static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) {5841unsigned char* chunk = 0;5842if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {5843CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD"));5844chunk[8] = (unsigned char)(info->background_r >> 8);5845chunk[9] = (unsigned char)(info->background_r & 255);5846} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {5847CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD"));5848chunk[8] = (unsigned char)(info->background_r >> 8);5849chunk[9] = (unsigned char)(info->background_r & 255);5850chunk[10] = (unsigned char)(info->background_g >> 8);5851chunk[11] = (unsigned char)(info->background_g & 255);5852chunk[12] = (unsigned char)(info->background_b >> 8);5853chunk[13] = (unsigned char)(info->background_b & 255);5854} else if(info->color.colortype == LCT_PALETTE) {5855CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD"));5856chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/5857}5858if(chunk) lodepng_chunk_generate_crc(chunk);5859return 0;5860}58615862static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) {5863unsigned char* chunk;5864CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME"));5865chunk[8] = (unsigned char)(time->year >> 8);5866chunk[9] = (unsigned char)(time->year & 255);5867chunk[10] = (unsigned char)time->month;5868chunk[11] = (unsigned char)time->day;5869chunk[12] = (unsigned char)time->hour;5870chunk[13] = (unsigned char)time->minute;5871chunk[14] = (unsigned char)time->second;5872lodepng_chunk_generate_crc(chunk);5873return 0;5874}58755876static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) {5877unsigned char* chunk;5878CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs"));5879lodepng_set32bitInt(chunk + 8, info->phys_x);5880lodepng_set32bitInt(chunk + 12, info->phys_y);5881chunk[16] = info->phys_unit;5882lodepng_chunk_generate_crc(chunk);5883return 0;5884}58855886static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) {5887unsigned char* chunk;5888CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA"));5889lodepng_set32bitInt(chunk + 8, info->gama_gamma);5890lodepng_chunk_generate_crc(chunk);5891return 0;5892}58935894static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) {5895unsigned char* chunk;5896CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM"));5897lodepng_set32bitInt(chunk + 8, info->chrm_white_x);5898lodepng_set32bitInt(chunk + 12, info->chrm_white_y);5899lodepng_set32bitInt(chunk + 16, info->chrm_red_x);5900lodepng_set32bitInt(chunk + 20, info->chrm_red_y);5901lodepng_set32bitInt(chunk + 24, info->chrm_green_x);5902lodepng_set32bitInt(chunk + 28, info->chrm_green_y);5903lodepng_set32bitInt(chunk + 32, info->chrm_blue_x);5904lodepng_set32bitInt(chunk + 36, info->chrm_blue_y);5905lodepng_chunk_generate_crc(chunk);5906return 0;5907}59085909static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) {5910unsigned char data = info->srgb_intent;5911return lodepng_chunk_createv(out, 1, "sRGB", &data);5912}59135914static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) {5915unsigned error = 0;5916unsigned char* chunk = 0;5917unsigned char* compressed = 0;5918size_t compressedsize = 0;5919size_t keysize = lodepng_strlen(info->iccp_name);59205921if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/5922error = zlib_compress(&compressed, &compressedsize,5923info->iccp_profile, info->iccp_profile_size, zlibsettings);5924if(!error) {5925size_t size = keysize + 2 + compressedsize;5926error = lodepng_chunk_init(&chunk, out, size, "iCCP");5927}5928if(!error) {5929lodepng_memcpy(chunk + 8, info->iccp_name, keysize);5930chunk[8 + keysize] = 0; /*null termination char*/5931chunk[9 + keysize] = 0; /*compression method: 0*/5932lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);5933lodepng_chunk_generate_crc(chunk);5934}59355936lodepng_free(compressed);5937return error;5938}59395940static unsigned addChunk_cICP(ucvector* out, const LodePNGInfo* info) {5941unsigned char* chunk;5942/* Allow up to 255 since they are bytes. The ITU-R-BT.709 spec has a more5943restricted set of valid values for each field, but that's up to the error5944handling of a CICP library, not the PNG encoding/decoding, to manage. */5945if(info->cicp_color_primaries > 255) return 116;5946if(info->cicp_transfer_function > 255) return 116;5947if(info->cicp_matrix_coefficients > 255) return 116;5948if(info->cicp_video_full_range_flag > 255) return 116;5949CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "cICP"));5950chunk[8 + 0] = (unsigned char)info->cicp_color_primaries;5951chunk[8 + 1] = (unsigned char)info->cicp_transfer_function;5952chunk[8 + 2] = (unsigned char)info->cicp_matrix_coefficients;5953chunk[8 + 3] = (unsigned char)info->cicp_video_full_range_flag;5954lodepng_chunk_generate_crc(chunk);5955return 0;5956}59575958static unsigned addChunk_mDCV(ucvector* out, const LodePNGInfo* info) {5959unsigned char* chunk;5960/* Allow up to 65535 since they are 16-bit ints. */5961if(info->mdcv_red_x > 65535) return 118;5962if(info->mdcv_red_y > 65535) return 118;5963if(info->mdcv_green_x > 65535) return 118;5964if(info->mdcv_green_y > 65535) return 118;5965if(info->mdcv_blue_x > 65535) return 118;5966if(info->mdcv_blue_y > 65535) return 118;5967if(info->mdcv_white_x > 65535) return 118;5968if(info->mdcv_white_y > 65535) return 118;5969CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 24, "mDCV"));5970chunk[8 + 0] = (unsigned char)((info->mdcv_red_x) >> 8u);5971chunk[8 + 1] = (unsigned char)(info->mdcv_red_x);5972chunk[8 + 2] = (unsigned char)((info->mdcv_red_y) >> 8u);5973chunk[8 + 3] = (unsigned char)(info->mdcv_red_y);5974chunk[8 + 4] = (unsigned char)((info->mdcv_green_x) >> 8u);5975chunk[8 + 5] = (unsigned char)(info->mdcv_green_x);5976chunk[8 + 6] = (unsigned char)((info->mdcv_green_y) >> 8u);5977chunk[8 + 7] = (unsigned char)(info->mdcv_green_y);5978chunk[8 + 8] = (unsigned char)((info->mdcv_blue_x) >> 8u);5979chunk[8 + 9] = (unsigned char)(info->mdcv_blue_x);5980chunk[8 + 10] = (unsigned char)((info->mdcv_blue_y) >> 8u);5981chunk[8 + 11] = (unsigned char)(info->mdcv_blue_y);5982chunk[8 + 12] = (unsigned char)((info->mdcv_white_x) >> 8u);5983chunk[8 + 13] = (unsigned char)(info->mdcv_white_x);5984chunk[8 + 14] = (unsigned char)((info->mdcv_white_y) >> 8u);5985chunk[8 + 15] = (unsigned char)(info->mdcv_white_y);5986lodepng_set32bitInt(chunk + 8 + 16, info->mdcv_max_luminance);5987lodepng_set32bitInt(chunk + 8 + 20, info->mdcv_min_luminance);5988lodepng_chunk_generate_crc(chunk);5989return 0;5990}59915992static unsigned addChunk_cLLI(ucvector* out, const LodePNGInfo* info) {5993unsigned char* chunk;5994CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 8, "cLLI"));5995lodepng_set32bitInt(chunk + 8 + 0, info->clli_max_cll);5996lodepng_set32bitInt(chunk + 8 + 4, info->clli_max_fall);5997lodepng_chunk_generate_crc(chunk);5998return 0;5999}60006001static unsigned addChunk_eXIf(ucvector* out, const LodePNGInfo* info) {6002return lodepng_chunk_createv(out, info->exif_size, "eXIf", info->exif);6003}60046005static unsigned addChunk_sBIT(ucvector* out, const LodePNGInfo* info) {6006unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth;6007unsigned char* chunk = 0;6008if(info->color.colortype == LCT_GREY) {6009if(info->sbit_r == 0 || info->sbit_r > bitdepth) return 115;6010CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "sBIT"));6011chunk[8] = info->sbit_r;6012} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) {6013if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0) return 115;6014if(info->sbit_r > bitdepth || info->sbit_g > bitdepth || info->sbit_b > bitdepth) return 115;6015CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 3, "sBIT"));6016chunk[8] = info->sbit_r;6017chunk[9] = info->sbit_g;6018chunk[10] = info->sbit_b;6019} else if(info->color.colortype == LCT_GREY_ALPHA) {6020if(info->sbit_r == 0 || info->sbit_a == 0) return 115;6021if(info->sbit_r > bitdepth || info->sbit_a > bitdepth) return 115;6022CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "sBIT"));6023chunk[8] = info->sbit_r;6024chunk[9] = info->sbit_a;6025} else if(info->color.colortype == LCT_RGBA) {6026if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0 || info->sbit_a == 0 ||6027info->sbit_r > bitdepth || info->sbit_g > bitdepth ||6028info->sbit_b > bitdepth || info->sbit_a > bitdepth) {6029return 115;6030}6031CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "sBIT"));6032chunk[8] = info->sbit_r;6033chunk[9] = info->sbit_g;6034chunk[10] = info->sbit_b;6035chunk[11] = info->sbit_a;6036}6037if(chunk) lodepng_chunk_generate_crc(chunk);6038return 0;6039}60406041#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/60426043static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,6044size_t length, size_t bytewidth, unsigned char filterType) {6045size_t i;6046switch(filterType) {6047case 0: /*None*/6048for(i = 0; i != length; ++i) out[i] = scanline[i];6049break;6050case 1: /*Sub*/6051for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];6052for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];6053break;6054case 2: /*Up*/6055if(prevline) {6056for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];6057} else {6058for(i = 0; i != length; ++i) out[i] = scanline[i];6059}6060break;6061case 3: /*Average*/6062if(prevline) {6063for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);6064for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);6065} else {6066for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];6067for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);6068}6069break;6070case 4: /*Paeth*/6071if(prevline) {6072/*paethPredictor(0, prevline[i], 0) is always prevline[i]*/6073for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);6074for(i = bytewidth; i < length; ++i) {6075out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));6076}6077} else {6078for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];6079/*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/6080for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);6081}6082break;6083default: return; /*invalid filter type given*/6084}6085}60866087/* integer binary logarithm, max return value is 31 */6088static size_t ilog2(size_t i) {6089size_t result = 0;6090if(i >= 65536) { result += 16; i >>= 16; }6091if(i >= 256) { result += 8; i >>= 8; }6092if(i >= 16) { result += 4; i >>= 4; }6093if(i >= 4) { result += 2; i >>= 2; }6094if(i >= 2) { result += 1; /*i >>= 1;*/ }6095return result;6096}60976098/* integer approximation for i * log2(i), helper function for LFS_ENTROPY */6099static size_t ilog2i(size_t i) {6100size_t l;6101if(i == 0) return 0;6102l = ilog2(i);6103/* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u)6104linearly approximates the missing fractional part multiplied by i */6105return i * l + ((i - (((size_t)1) << l)) << 1u);6106}61076108static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,6109const LodePNGColorMode* color, const LodePNGEncoderSettings* settings) {6110/*6111For PNG filter method 06112out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are6113the scanlines with 1 extra byte per scanline6114*/61156116unsigned bpp = lodepng_get_bpp(color);6117/*the width of a scanline in bytes, not including the filter type*/6118size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;61196120/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/6121size_t bytewidth = (bpp + 7u) / 8u;6122const unsigned char* prevline = 0;6123unsigned x, y;6124unsigned error = 0;6125LodePNGFilterStrategy strategy = settings->filter_strategy;61266127if(settings->filter_palette_zero && (color->colortype == LCT_PALETTE || color->bitdepth < 8)) {6128/*if the filter_palette_zero setting is enabled, override the filter strategy with6129zero for all scanlines for palette and less-than-8-bitdepth images*/6130strategy = LFS_ZERO;6131}61326133if(bpp == 0) return 31; /*error: invalid color type*/61346135if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) {6136unsigned char type = (unsigned char)strategy;6137for(y = 0; y != h; ++y) {6138size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/6139size_t inindex = linebytes * y;6140out[outindex] = type; /*filter type byte*/6141filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);6142prevline = &in[inindex];6143}6144} else if(strategy == LFS_MINSUM) {6145/*adaptive filtering: independently for each row, try all five filter types and select the one that produces the6146smallest sum of absolute values per row.*/6147unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/6148size_t smallest = 0;6149unsigned char type, bestType = 0;61506151for(type = 0; type != 5; ++type) {6152attempt[type] = (unsigned char*)lodepng_malloc(linebytes);6153if(!attempt[type]) error = 83; /*alloc fail*/6154}61556156if(!error) {6157for(y = 0; y != h; ++y) {6158/*try the 5 filter types*/6159for(type = 0; type != 5; ++type) {6160size_t sum = 0;6161filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);61626163/*calculate the sum of the result*/6164if(type == 0) {6165for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]);6166} else {6167for(x = 0; x != linebytes; ++x) {6168/*For differences, each byte should be treated as signed, values above 127 are negative6169(converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.6170This means filtertype 0 is almost never chosen, but that is justified.*/6171unsigned char s = attempt[type][x];6172sum += s < 128 ? s : (255U - s);6173}6174}61756176/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/6177if(type == 0 || sum < smallest) {6178bestType = type;6179smallest = sum;6180}6181}61826183prevline = &in[y * linebytes];61846185/*now fill the out values*/6186out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/6187for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];6188}6189}61906191for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);6192} else if(strategy == LFS_ENTROPY) {6193unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/6194size_t bestSum = 0;6195unsigned type, bestType = 0;6196unsigned count[256];61976198for(type = 0; type != 5; ++type) {6199attempt[type] = (unsigned char*)lodepng_malloc(linebytes);6200if(!attempt[type]) error = 83; /*alloc fail*/6201}62026203if(!error) {6204for(y = 0; y != h; ++y) {6205/*try the 5 filter types*/6206for(type = 0; type != 5; ++type) {6207size_t sum = 0;6208filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);6209lodepng_memset(count, 0, 256 * sizeof(*count));6210for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];6211++count[type]; /*the filter type itself is part of the scanline*/6212for(x = 0; x != 256; ++x) {6213sum += ilog2i(count[x]);6214}6215/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/6216if(type == 0 || sum > bestSum) {6217bestType = type;6218bestSum = sum;6219}6220}62216222prevline = &in[y * linebytes];62236224/*now fill the out values*/6225out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/6226for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];6227}6228}62296230for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);6231} else if(strategy == LFS_PREDEFINED) {6232for(y = 0; y != h; ++y) {6233size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/6234size_t inindex = linebytes * y;6235unsigned char type = settings->predefined_filters[y];6236out[outindex] = type; /*filter type byte*/6237filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);6238prevline = &in[inindex];6239}6240} else if(strategy == LFS_BRUTE_FORCE) {6241/*brute force filter chooser.6242deflate the scanline after every filter attempt to see which one deflates best.6243This is very slow and gives only slightly smaller, sometimes even larger, result*/6244size_t size[5];6245unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/6246size_t smallest = 0;6247unsigned type = 0, bestType = 0;6248unsigned char* dummy;6249LodePNGCompressSettings zlibsettings;6250lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings));6251/*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,6252to simulate the true case where the tree is the same for the whole image. Sometimes it gives6253better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare6254cases better compression. It does make this a bit less slow, so it's worth doing this.*/6255zlibsettings.btype = 1;6256/*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG6257images only, so disable it*/6258zlibsettings.custom_zlib = 0;6259zlibsettings.custom_deflate = 0;6260for(type = 0; type != 5; ++type) {6261attempt[type] = (unsigned char*)lodepng_malloc(linebytes);6262if(!attempt[type]) error = 83; /*alloc fail*/6263}6264if(!error) {6265for(y = 0; y != h; ++y) /*try the 5 filter types*/ {6266for(type = 0; type != 5; ++type) {6267unsigned testsize = (unsigned)linebytes;6268/*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/62696270filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);6271size[type] = 0;6272dummy = 0;6273zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);6274lodepng_free(dummy);6275/*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/6276if(type == 0 || size[type] < smallest) {6277bestType = type;6278smallest = size[type];6279}6280}6281prevline = &in[y * linebytes];6282out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/6283for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];6284}6285}6286for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);6287}6288else return 88; /* unknown filter strategy */62896290return error;6291}62926293static void addPaddingBits(unsigned char* out, const unsigned char* in,6294size_t olinebits, size_t ilinebits, unsigned h) {6295/*The opposite of the removePaddingBits function6296olinebits must be >= ilinebits*/6297unsigned y;6298size_t diff = olinebits - ilinebits;6299size_t obp = 0, ibp = 0; /*bit pointers*/6300for(y = 0; y != h; ++y) {6301size_t x;6302for(x = 0; x < ilinebits; ++x) {6303unsigned char bit = readBitFromReversedStream(&ibp, in);6304setBitOfReversedStream(&obp, out, bit);6305}6306/*obp += diff; --> no, fill in some value in the padding bits too, to avoid6307"Use of uninitialised value of size ###" warning from valgrind*/6308for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);6309}6310}63116312/*6313in: non-interlaced image with size w*h6314out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with6315no padding bits between scanlines, but between reduced images so that each6316reduced image starts at a byte.6317bpp: bits per pixel6318there are no padding bits, not between scanlines, not between reduced images6319in has the following size in bits: w * h * bpp.6320out is possibly bigger due to padding bits between reduced images6321NOTE: comments about padding bits are only relevant if bpp < 86322*/6323static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {6324unsigned passw[7], passh[7];6325size_t filter_passstart[8], padded_passstart[8], passstart[8];6326unsigned i;63276328Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);63296330if(bpp >= 8) {6331for(i = 0; i != 7; ++i) {6332unsigned x, y, b;6333size_t bytewidth = bpp / 8u;6334for(y = 0; y < passh[i]; ++y)6335for(x = 0; x < passw[i]; ++x) {6336size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;6337size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;6338for(b = 0; b < bytewidth; ++b) {6339out[pixeloutstart + b] = in[pixelinstart + b];6340}6341}6342}6343} else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {6344for(i = 0; i != 7; ++i) {6345unsigned x, y, b;6346unsigned ilinebits = bpp * passw[i];6347unsigned olinebits = bpp * w;6348size_t obp, ibp; /*bit pointers (for out and in buffer)*/6349for(y = 0; y < passh[i]; ++y)6350for(x = 0; x < passw[i]; ++x) {6351ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;6352obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);6353for(b = 0; b < bpp; ++b) {6354unsigned char bit = readBitFromReversedStream(&ibp, in);6355setBitOfReversedStream(&obp, out, bit);6356}6357}6358}6359}6360}63616362/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.6363return value is error**/6364static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,6365unsigned w, unsigned h,6366const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) {6367/*6368This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:6369*) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter6370*) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter6371*/6372size_t bpp = lodepng_get_bpp(&info_png->color);6373unsigned error = 0;6374if(info_png->interlace_method == 0) {6375/*image size plus an extra byte per scanline + possible padding bits*/6376*outsize = (size_t)h + ((size_t)h * (((size_t)w * bpp + 7u) / 8u));6377*out = (unsigned char*)lodepng_malloc(*outsize);6378if(!(*out) && (*outsize)) error = 83; /*alloc fail*/63796380if(!error) {6381/*non multiple of 8 bits per scanline, padding bits needed per scanline*/6382if(bpp < 8 && (size_t)w * bpp != (((size_t)w * bpp + 7u) / 8u) * 8u) {6383unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u));6384if(!padded) error = 83; /*alloc fail*/6385if(!error) {6386addPaddingBits(padded, in, (((size_t)w * bpp + 7u) / 8u) * 8u, (size_t)w * bpp, h);6387error = filter(*out, padded, w, h, &info_png->color, settings);6388}6389lodepng_free(padded);6390} else {6391/*we can immediately filter into the out buffer, no other steps needed*/6392error = filter(*out, in, w, h, &info_png->color, settings);6393}6394}6395} else /*interlace_method is 1 (Adam7)*/ {6396unsigned passw[7], passh[7];6397size_t filter_passstart[8], padded_passstart[8], passstart[8];6398unsigned char* adam7;63996400Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, (unsigned)bpp);64016402*outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/6403*out = (unsigned char*)lodepng_malloc(*outsize);6404if(!(*out)) error = 83; /*alloc fail*/64056406adam7 = (unsigned char*)lodepng_malloc(passstart[7]);6407if(!adam7 && passstart[7]) error = 83; /*alloc fail*/64086409if(!error) {6410unsigned i;64116412Adam7_interlace(adam7, in, w, h, (unsigned)bpp);6413for(i = 0; i != 7; ++i) {6414if(bpp < 8) {6415unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);6416if(!padded) ERROR_BREAK(83); /*alloc fail*/6417addPaddingBits(padded, &adam7[passstart[i]],6418(((size_t)passw[i] * bpp + 7u) / 8u) * 8u, (size_t)passw[i] * bpp, passh[i]);6419error = filter(&(*out)[filter_passstart[i]], padded,6420passw[i], passh[i], &info_png->color, settings);6421lodepng_free(padded);6422} else {6423error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],6424passw[i], passh[i], &info_png->color, settings);6425}64266427if(error) break;6428}6429}64306431lodepng_free(adam7);6432}64336434return error;6435}64366437#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6438static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) {6439unsigned char* inchunk = data;6440while((size_t)(inchunk - data) < datasize) {6441CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));6442out->allocsize = out->size; /*fix the allocsize again*/6443inchunk = lodepng_chunk_next(inchunk, data + datasize);6444}6445return 0;6446}64476448static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) {6449/*6450It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-196451are "RGB ". We do not perform any full parsing of the ICC profile here, other6452than check those 4 bytes to grayscale profile. Other than that, validity of6453the profile is not checked. This is needed only because the PNG specification6454requires using a non-gray color model if there is an ICC profile with "RGB "6455(sadly limiting compression opportunities if the input data is grayscale RGB6456data), and requires using a gray color model if it is "GRAY".6457*/6458if(size < 20) return 0;6459return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y';6460}64616462static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) {6463/* See comment in isGrayICCProfile*/6464if(size < 20) return 0;6465return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' ';6466}6467#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/64686469unsigned lodepng_encode(unsigned char** out, size_t* outsize,6470const unsigned char* image, unsigned w, unsigned h,6471LodePNGState* state) {6472unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/6473size_t datasize = 0;6474ucvector outv = ucvector_init(NULL, 0);6475LodePNGInfo info;6476const LodePNGInfo* info_png = &state->info_png;6477LodePNGColorMode auto_color;64786479lodepng_info_init(&info);6480lodepng_color_mode_init(&auto_color);64816482/*provide some proper output values if error will happen*/6483*out = 0;6484*outsize = 0;6485state->error = 0;64866487/*check input values validity*/6488if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette)6489&& (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) {6490/*this error is returned even if auto_convert is enabled and thus encoder could6491generate the palette by itself: while allowing this could be possible in theory,6492it may complicate the code or edge cases, and always requiring to give a palette6493when setting this color type is a simpler contract*/6494state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/6495goto cleanup;6496}6497if(state->encoder.zlibsettings.btype > 2) {6498state->error = 61; /*error: invalid btype*/6499goto cleanup;6500}6501if(info_png->interlace_method > 1) {6502state->error = 71; /*error: invalid interlace mode*/6503goto cleanup;6504}6505state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth);6506if(state->error) goto cleanup; /*error: invalid color type given*/6507state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);6508if(state->error) goto cleanup; /*error: invalid color type given*/65096510/* color convert and compute scanline filter types */6511lodepng_info_copy(&info, &state->info_png);6512if(state->encoder.auto_convert) {6513LodePNGColorStats stats;6514unsigned allow_convert = 1;6515lodepng_color_stats_init(&stats);6516#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6517if(info_png->iccp_defined &&6518isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {6519/*the PNG specification does not allow to use palette with a GRAY ICC profile, even6520if the palette has only gray colors, so disallow it.*/6521stats.allow_palette = 0;6522}6523if(info_png->iccp_defined &&6524isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {6525/*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/6526stats.allow_greyscale = 0;6527}6528#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */6529state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw);6530if(state->error) goto cleanup;6531#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6532if(info_png->background_defined) {6533/*the background chunk's color must be taken into account as well*/6534unsigned r = 0, g = 0, b = 0;6535LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);6536lodepng_convert_rgb(&r, &g, &b,6537info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color);6538state->error = lodepng_color_stats_add(&stats, r, g, b, 65535);6539if(state->error) goto cleanup;6540}6541#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */6542state->error = auto_choose_color(&auto_color, &state->info_raw, &stats);6543if(state->error) goto cleanup;6544#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6545if(info_png->sbit_defined) {6546/*if sbit is defined, due to strict requirements of which sbit values can be present for which color modes,6547auto_convert can't be done in many cases. However, do support a few cases here.6548TODO: more conversions may be possible, and it may also be possible to get a more appropriate color type out of6549auto_choose_color if knowledge about sbit is used beforehand6550*/6551unsigned sbit_max = LODEPNG_MAX(LODEPNG_MAX(LODEPNG_MAX(info_png->sbit_r, info_png->sbit_g),6552info_png->sbit_b), info_png->sbit_a);6553unsigned equal = (!info_png->sbit_g || info_png->sbit_g == info_png->sbit_r)6554&& (!info_png->sbit_b || info_png->sbit_b == info_png->sbit_r)6555&& (!info_png->sbit_a || info_png->sbit_a == info_png->sbit_r);6556allow_convert = 0;6557if(info.color.colortype == LCT_PALETTE &&6558auto_color.colortype == LCT_PALETTE) {6559/* input and output are palette, and in this case it may happen that palette data is6560expected to be copied from info_raw into the info_png */6561allow_convert = 1;6562}6563/*going from 8-bit RGB to palette (or 16-bit as long as sbit_max <= 8) is possible6564since both are 8-bit RGB for sBIT's purposes*/6565if(info.color.colortype == LCT_RGB &&6566auto_color.colortype == LCT_PALETTE && sbit_max <= 8) {6567allow_convert = 1;6568}6569/*going from 8-bit RGBA to palette is also ok but only if sbit_a is exactly 8*/6570if(info.color.colortype == LCT_RGBA && auto_color.colortype == LCT_PALETTE &&6571info_png->sbit_a == 8 && sbit_max <= 8) {6572allow_convert = 1;6573}6574/*going from 16-bit RGB(A) to 8-bit RGB(A) is ok if all sbit values are <= 8*/6575if((info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA) && info.color.bitdepth == 16 &&6576auto_color.colortype == info.color.colortype && auto_color.bitdepth == 8 &&6577sbit_max <= 8) {6578allow_convert = 1;6579}6580/*going to less channels is ok if all bit values are equal (all possible values in sbit,6581as well as the chosen bitdepth of the result). Due to how auto_convert works,6582we already know that auto_color.colortype has less than or equal amount of channels than6583info.colortype. Palette is not used here. This conversion is not allowed if6584info_png->sbit_r < auto_color.bitdepth, because specifically for alpha, non-presence of6585an sbit value heavily implies that alpha's bit depth is equal to the PNG bit depth (rather6586than the bit depths set in the r, g and b sbit values, by how the PNG specification describes6587handling tRNS chunk case with sBIT), so be conservative here about ignoring user input.*/6588if(info.color.colortype != LCT_PALETTE && auto_color.colortype != LCT_PALETTE &&6589equal && info_png->sbit_r == auto_color.bitdepth) {6590allow_convert = 1;6591}6592}6593#endif6594if(state->encoder.force_palette) {6595if(info.color.colortype != LCT_GREY && info.color.colortype != LCT_GREY_ALPHA &&6596(auto_color.colortype == LCT_GREY || auto_color.colortype == LCT_GREY_ALPHA)) {6597/*user speficially forced a PLTE palette, so cannot convert to grayscale types because6598the PNG specification only allows writing a suggested palette in PLTE for truecolor types*/6599allow_convert = 0;6600}6601}6602if(allow_convert) {6603lodepng_color_mode_copy(&info.color, &auto_color);6604#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6605/*also convert the background chunk*/6606if(info_png->background_defined) {6607if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,6608info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) {6609state->error = 104;6610goto cleanup;6611}6612}6613#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */6614}6615}6616#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6617if(info_png->iccp_defined) {6618unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);6619unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);6620unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;6621if(!gray_icc && !rgb_icc) {6622state->error = 100; /* Disallowed profile color type for PNG */6623goto cleanup;6624}6625if(gray_icc != gray_png) {6626/*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa,6627or in case of auto_convert, it wasn't possible to find appropriate model*/6628state->error = state->encoder.auto_convert ? 102 : 101;6629goto cleanup;6630}6631}6632#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6633if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {6634unsigned char* converted;6635size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u;66366637converted = (unsigned char*)lodepng_malloc(size);6638if(!converted && size) state->error = 83; /*alloc fail*/6639if(!state->error) {6640state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);6641}6642if(!state->error) {6643state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);6644}6645lodepng_free(converted);6646if(state->error) goto cleanup;6647} else {6648state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);6649if(state->error) goto cleanup;6650}66516652/* output all PNG chunks */ {6653#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6654size_t i;6655#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6656/*write signature and chunks*/6657state->error = writeSignature(&outv);6658if(state->error) goto cleanup;6659/*IHDR*/6660state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);6661if(state->error) goto cleanup;6662#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6663/*unknown chunks between IHDR and PLTE*/6664if(info.unknown_chunks_data[0]) {6665state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);6666if(state->error) goto cleanup;6667}6668/*color profile chunks must come before PLTE */6669if(info.cicp_defined) {6670state->error = addChunk_cICP(&outv, &info);6671if(state->error) goto cleanup;6672}6673if(info.mdcv_defined) {6674state->error = addChunk_mDCV(&outv, &info);6675if(state->error) goto cleanup;6676}6677if(info.clli_defined) {6678state->error = addChunk_cLLI(&outv, &info);6679if(state->error) goto cleanup;6680}6681if(info.iccp_defined) {6682state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);6683if(state->error) goto cleanup;6684}6685if(info.srgb_defined) {6686state->error = addChunk_sRGB(&outv, &info);6687if(state->error) goto cleanup;6688}6689if(info.gama_defined) {6690state->error = addChunk_gAMA(&outv, &info);6691if(state->error) goto cleanup;6692}6693if(info.chrm_defined) {6694state->error = addChunk_cHRM(&outv, &info);6695if(state->error) goto cleanup;6696}6697if(info_png->sbit_defined) {6698state->error = addChunk_sBIT(&outv, &info);6699if(state->error) goto cleanup;6700}6701if(info.exif_defined) {6702state->error = addChunk_eXIf(&outv, &info);6703if(state->error) goto cleanup;6704}6705#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6706/*PLTE*/6707if(info.color.colortype == LCT_PALETTE) {6708state->error = addChunk_PLTE(&outv, &info.color);6709if(state->error) goto cleanup;6710}6711if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {6712/*force_palette means: write suggested palette for truecolor in PLTE chunk*/6713state->error = addChunk_PLTE(&outv, &info.color);6714if(state->error) goto cleanup;6715}6716/*tRNS (this will only add if when necessary) */6717state->error = addChunk_tRNS(&outv, &info.color);6718if(state->error) goto cleanup;6719#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6720/*bKGD (must come between PLTE and the IDAt chunks*/6721if(info.background_defined) {6722state->error = addChunk_bKGD(&outv, &info);6723if(state->error) goto cleanup;6724}6725/*pHYs (must come before the IDAT chunks)*/6726if(info.phys_defined) {6727state->error = addChunk_pHYs(&outv, &info);6728if(state->error) goto cleanup;6729}67306731/*unknown chunks between PLTE and IDAT*/6732if(info.unknown_chunks_data[1]) {6733state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);6734if(state->error) goto cleanup;6735}6736#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6737/*IDAT (multiple IDAT chunks must be consecutive)*/6738state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);6739if(state->error) goto cleanup;6740#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6741/*tIME*/6742if(info.time_defined) {6743state->error = addChunk_tIME(&outv, &info.time);6744if(state->error) goto cleanup;6745}6746/*tEXt and/or zTXt*/6747for(i = 0; i != info.text_num; ++i) {6748if(lodepng_strlen(info.text_keys[i]) > 79) {6749state->error = 66; /*text chunk too large*/6750goto cleanup;6751}6752if(lodepng_strlen(info.text_keys[i]) < 1) {6753state->error = 67; /*text chunk too small*/6754goto cleanup;6755}6756if(state->encoder.text_compression) {6757state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);6758if(state->error) goto cleanup;6759} else {6760state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);6761if(state->error) goto cleanup;6762}6763}6764/*LodePNG version id in text chunk*/6765if(state->encoder.add_id) {6766unsigned already_added_id_text = 0;6767for(i = 0; i != info.text_num; ++i) {6768const char* k = info.text_keys[i];6769/* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */6770if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' &&6771k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') {6772already_added_id_text = 1;6773break;6774}6775}6776if(already_added_id_text == 0) {6777state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/6778if(state->error) goto cleanup;6779}6780}6781/*iTXt*/6782for(i = 0; i != info.itext_num; ++i) {6783if(lodepng_strlen(info.itext_keys[i]) > 79) {6784state->error = 66; /*text chunk too large*/6785goto cleanup;6786}6787if(lodepng_strlen(info.itext_keys[i]) < 1) {6788state->error = 67; /*text chunk too small*/6789goto cleanup;6790}6791state->error = addChunk_iTXt(6792&outv, state->encoder.text_compression,6793info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],6794&state->encoder.zlibsettings);6795if(state->error) goto cleanup;6796}67976798/*unknown chunks between IDAT and IEND*/6799if(info.unknown_chunks_data[2]) {6800state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);6801if(state->error) goto cleanup;6802}6803#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6804state->error = addChunk_IEND(&outv);6805if(state->error) goto cleanup;6806}68076808cleanup:6809lodepng_info_cleanup(&info);6810lodepng_free(data);6811lodepng_color_mode_cleanup(&auto_color);68126813/*instead of cleaning the vector up, give it to the output*/6814*out = outv.data;6815*outsize = outv.size;68166817return state->error;6818}68196820unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,6821unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {6822unsigned error;6823LodePNGState state;6824lodepng_state_init(&state);6825state.info_raw.colortype = colortype;6826state.info_raw.bitdepth = bitdepth;6827state.info_png.color.colortype = colortype;6828state.info_png.color.bitdepth = bitdepth;6829lodepng_encode(out, outsize, image, w, h, &state);6830error = state.error;6831lodepng_state_cleanup(&state);6832return error;6833}68346835unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {6836return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);6837}68386839unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {6840return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);6841}68426843#ifdef LODEPNG_COMPILE_DISK6844unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,6845LodePNGColorType colortype, unsigned bitdepth) {6846unsigned char* buffer;6847size_t buffersize;6848unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);6849if(!error) error = lodepng_save_file(buffer, buffersize, filename);6850lodepng_free(buffer);6851return error;6852}68536854unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {6855return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);6856}68576858unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {6859return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);6860}6861#endif /*LODEPNG_COMPILE_DISK*/68626863void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) {6864lodepng_compress_settings_init(&settings->zlibsettings);6865settings->filter_palette_zero = 1;6866settings->filter_strategy = LFS_MINSUM;6867settings->auto_convert = 1;6868settings->force_palette = 0;6869settings->predefined_filters = 0;6870#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS6871settings->add_id = 0;6872settings->text_compression = 1;6873#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/6874}68756876#endif /*LODEPNG_COMPILE_ENCODER*/6877#endif /*LODEPNG_COMPILE_PNG*/68786879#ifdef LODEPNG_COMPILE_ERROR_TEXT6880/*6881This returns the description of a numerical error code in English. This is also6882the documentation of all the error codes.6883*/6884const char* lodepng_error_text(unsigned code) {6885switch(code) {6886case 0: return "no error, everything went ok";6887case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/6888case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/6889case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/6890case 13: return "problem while processing dynamic deflate block";6891case 14: return "problem while processing dynamic deflate block";6892case 15: return "problem while processing dynamic deflate block";6893/*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/6894case 16: return "invalid code while processing dynamic deflate block";6895case 17: return "end of out buffer memory reached while inflating";6896case 18: return "invalid distance code while inflating";6897case 19: return "end of out buffer memory reached while inflating";6898case 20: return "invalid deflate block BTYPE encountered while decoding";6899case 21: return "NLEN is not ones complement of LEN in a deflate block";69006901/*end of out buffer memory reached while inflating:6902This can happen if the inflated deflate data is longer than the amount of bytes required to fill up6903all the pixels of the image, given the color depth and image dimensions. Something that doesn't6904happen in a normal, well encoded, PNG image.*/6905case 22: return "end of out buffer memory reached while inflating";6906case 23: return "end of in buffer memory reached while inflating";6907case 24: return "invalid FCHECK in zlib header";6908case 25: return "invalid compression method in zlib header";6909case 26: return "FDICT encountered in zlib header while it's not used for PNG";6910case 27: return "PNG file is smaller than a PNG header";6911/*Checks the magic file header, the first 8 bytes of the PNG file*/6912case 28: return "incorrect PNG signature, it's no PNG or corrupted";6913case 29: return "first chunk is not the header chunk";6914case 30: return "chunk length too large, chunk broken off at end of file";6915case 31: return "illegal PNG color type or bpp";6916case 32: return "illegal PNG compression method";6917case 33: return "illegal PNG filter method";6918case 34: return "illegal PNG interlace method";6919case 35: return "chunk length of a chunk is too large or the chunk too small";6920case 36: return "illegal PNG filter type encountered";6921case 37: return "illegal bit depth for this color type given";6922case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/6923case 39: return "tRNS chunk before PLTE or has more entries than palette size";6924case 40: return "tRNS chunk has wrong size for grayscale image";6925case 41: return "tRNS chunk has wrong size for RGB image";6926case 42: return "tRNS chunk appeared while it was not allowed for this color type";6927case 43: return "bKGD chunk has wrong size for palette image";6928case 44: return "bKGD chunk has wrong size for grayscale image";6929case 45: return "bKGD chunk has wrong size for RGB image";6930case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";6931case 49: return "jumped past memory while generating dynamic huffman tree";6932case 50: return "jumped past memory while generating dynamic huffman tree";6933case 51: return "jumped past memory while inflating huffman block";6934case 52: return "jumped past memory while inflating";6935case 53: return "size of zlib data too small";6936case 54: return "repeat symbol in tree while there was no value symbol yet";6937/*jumped past tree while generating huffman tree, this could be when the6938tree will have more leaves than symbols after generating it out of the6939given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/6940case 55: return "jumped past tree while generating huffman tree";6941case 56: return "given output image colortype or bitdepth not supported for color conversion";6942case 57: return "invalid CRC encountered (checking CRC can be disabled)";6943case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";6944case 59: return "requested color conversion not supported";6945case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";6946case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";6947/*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/6948case 62: return "conversion from color to grayscale not supported";6949/*(2^31-1)*/6950case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";6951/*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/6952case 64: return "the length of the END symbol 256 in the Huffman tree is 0";6953case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";6954case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";6955case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";6956case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";6957case 71: return "invalid interlace mode given to encoder (must be 0 or 1)";6958case 72: return "while decoding, invalid compression method encountering in zTXt or iTXt chunk (it must be 0)";6959case 73: return "invalid tIME chunk size";6960case 74: return "invalid pHYs chunk size";6961/*length could be wrong, or data chopped off*/6962case 75: return "no null termination char found while decoding text chunk";6963case 76: return "iTXt chunk too short to contain required bytes";6964case 77: return "integer overflow in buffer size";6965case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/6966case 79: return "failed to open file for writing";6967case 80: return "tried creating a tree of 0 symbols";6968case 81: return "lazy matching at pos 0 is impossible";6969case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds";6970case 83: return "memory allocation failed";6971case 84: return "given image too small to contain all pixels to be encoded";6972case 86: return "impossible offset in lz77 encoding (internal bug)";6973case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";6974case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";6975case 89: return "text chunk keyword too short or long: must have size 1-79";6976/*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/6977case 90: return "windowsize must be a power of two";6978case 91: return "invalid decompressed idat size";6979case 92: return "integer overflow due to too many pixels";6980case 93: return "zero width or height is invalid";6981case 94: return "header chunk must have a size of 13 bytes";6982case 95: return "integer overflow with combined idat chunk size";6983case 96: return "invalid gAMA chunk size";6984case 97: return "invalid cHRM chunk size";6985case 98: return "invalid sRGB chunk size";6986case 99: return "invalid sRGB rendering intent";6987case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";6988case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";6989case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";6990case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";6991case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)";6992case 105: return "integer overflow of bitsize";6993case 106: return "PNG file must have PLTE chunk if color type is palette";6994case 107: return "color convert from palette mode requested without setting the palette data in it";6995case 108: return "tried to add more than 256 values to a palette";6996/*this limit can be configured in LodePNGDecompressSettings*/6997case 109: return "tried to decompress zlib or deflate data larger than desired max_output_size";6998case 110: return "custom zlib or inflate decompression failed";6999case 111: return "custom zlib or deflate compression failed";7000/*max text size limit can be configured in LodePNGDecoderSettings. This error prevents7001unreasonable memory consumption when decoding due to impossibly large text sizes.*/7002case 112: return "compressed text unreasonably large";7003/*max ICC size limit can be configured in LodePNGDecoderSettings. This error prevents7004unreasonable memory consumption when decoding due to impossibly large ICC profile*/7005case 113: return "ICC profile unreasonably large";7006case 114: return "sBIT chunk has wrong size for the color type of the image";7007case 115: return "sBIT value out of range";7008case 116: return "cICP value out of range";7009case 117: return "invalid cICP chunk size";7010case 118: return "mDCV value out of range";7011case 119: return "invalid mDCV chunk size";7012case 120: return "invalid cLLI chunk size";7013case 121: return "invalid chunk type name: may only contain [a-zA-Z]";7014case 122: return "invalid chunk type name: third character must be uppercase";7015}7016return "unknown error code";7017}7018#endif /*LODEPNG_COMPILE_ERROR_TEXT*/70197020/* ////////////////////////////////////////////////////////////////////////// */7021/* ////////////////////////////////////////////////////////////////////////// */7022/* // C++ Wrapper // */7023/* ////////////////////////////////////////////////////////////////////////// */7024/* ////////////////////////////////////////////////////////////////////////// */70257026#ifdef LODEPNG_COMPILE_CPP7027namespace lodepng {70287029#ifdef LODEPNG_COMPILE_DISK7030/* Resizes the vector to the file size and reads the file into it. Returns error code.*/7031static unsigned load_file_(std::vector<unsigned char>& buffer, FILE* file) {7032long size = lodepng_filesize(file);7033if(size < 0) return 78;7034buffer.resize((size_t)size);7035if(size == 0) return 0; /*ok*/7036if(fread(&buffer[0], 1, buffer.size(), file) != buffer.size()) return 78;7037return 0; /*ok*/7038}70397040unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename) {7041unsigned error;7042FILE* file = fopen(filename.c_str(), "rb");7043if(!file) return 78;7044error = load_file_(buffer, file);7045fclose(file);7046return error;7047}70487049/*write given buffer to the file, overwriting the file, it doesn't append to it.*/7050unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename) {7051return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());7052}7053#endif /* LODEPNG_COMPILE_DISK */70547055#ifdef LODEPNG_COMPILE_ZLIB7056#ifdef LODEPNG_COMPILE_DECODER7057unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,7058const LodePNGDecompressSettings& settings) {7059unsigned char* buffer = 0;7060size_t buffersize = 0;7061unsigned error = zlib_decompress(&buffer, &buffersize, 0, in, insize, &settings);7062if(buffer) {7063out.insert(out.end(), buffer, &buffer[buffersize]);7064lodepng_free(buffer);7065}7066return error;7067}70687069unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,7070const LodePNGDecompressSettings& settings) {7071return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);7072}7073#endif /* LODEPNG_COMPILE_DECODER */70747075#ifdef LODEPNG_COMPILE_ENCODER7076unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,7077const LodePNGCompressSettings& settings) {7078unsigned char* buffer = 0;7079size_t buffersize = 0;7080unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);7081if(buffer) {7082out.insert(out.end(), buffer, &buffer[buffersize]);7083lodepng_free(buffer);7084}7085return error;7086}70877088unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,7089const LodePNGCompressSettings& settings) {7090return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);7091}7092#endif /* LODEPNG_COMPILE_ENCODER */7093#endif /* LODEPNG_COMPILE_ZLIB */709470957096#ifdef LODEPNG_COMPILE_PNG70977098State::State() {7099lodepng_state_init(this);7100}71017102State::State(const State& other) {7103lodepng_state_init(this);7104lodepng_state_copy(this, &other);7105}71067107State::~State() {7108lodepng_state_cleanup(this);7109}71107111State& State::operator=(const State& other) {7112lodepng_state_copy(this, &other);7113return *this;7114}71157116#ifdef LODEPNG_COMPILE_DECODER71177118unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,7119size_t insize, LodePNGColorType colortype, unsigned bitdepth) {7120unsigned char* buffer = 0;7121unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);7122if(buffer && !error) {7123State state;7124state.info_raw.colortype = colortype;7125state.info_raw.bitdepth = bitdepth;7126size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);7127out.insert(out.end(), buffer, &buffer[buffersize]);7128}7129lodepng_free(buffer);7130return error;7131}71327133unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,7134const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth) {7135return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);7136}71377138unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,7139State& state,7140const unsigned char* in, size_t insize) {7141unsigned char* buffer = NULL;7142unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);7143if(buffer && !error) {7144size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);7145out.insert(out.end(), buffer, &buffer[buffersize]);7146}7147lodepng_free(buffer);7148return error;7149}71507151unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,7152State& state,7153const std::vector<unsigned char>& in) {7154return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());7155}71567157#ifdef LODEPNG_COMPILE_DISK7158unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,7159LodePNGColorType colortype, unsigned bitdepth) {7160std::vector<unsigned char> buffer;7161/* safe output values in case error happens */7162w = h = 0;7163unsigned error = load_file(buffer, filename);7164if(error) return error;7165return decode(out, w, h, buffer, colortype, bitdepth);7166}7167#endif /* LODEPNG_COMPILE_DECODER */7168#endif /* LODEPNG_COMPILE_DISK */71697170#ifdef LODEPNG_COMPILE_ENCODER7171unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,7172LodePNGColorType colortype, unsigned bitdepth) {7173unsigned char* buffer;7174size_t buffersize;7175unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);7176if(buffer) {7177out.insert(out.end(), buffer, &buffer[buffersize]);7178lodepng_free(buffer);7179}7180return error;7181}71827183unsigned encode(std::vector<unsigned char>& out,7184const std::vector<unsigned char>& in, unsigned w, unsigned h,7185LodePNGColorType colortype, unsigned bitdepth) {7186if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;7187return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);7188}71897190unsigned encode(std::vector<unsigned char>& out,7191const unsigned char* in, unsigned w, unsigned h,7192State& state) {7193unsigned char* buffer;7194size_t buffersize;7195unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);7196if(buffer) {7197out.insert(out.end(), buffer, &buffer[buffersize]);7198lodepng_free(buffer);7199}7200return error;7201}72027203unsigned encode(std::vector<unsigned char>& out,7204const std::vector<unsigned char>& in, unsigned w, unsigned h,7205State& state) {7206if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;7207return encode(out, in.empty() ? 0 : &in[0], w, h, state);7208}72097210#ifdef LODEPNG_COMPILE_DISK7211unsigned encode(const std::string& filename,7212const unsigned char* in, unsigned w, unsigned h,7213LodePNGColorType colortype, unsigned bitdepth) {7214std::vector<unsigned char> buffer;7215unsigned error = encode(buffer, in, w, h, colortype, bitdepth);7216if(!error) error = save_file(buffer, filename);7217return error;7218}72197220unsigned encode(const std::string& filename,7221const std::vector<unsigned char>& in, unsigned w, unsigned h,7222LodePNGColorType colortype, unsigned bitdepth) {7223if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;7224return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);7225}7226#endif /* LODEPNG_COMPILE_DISK */7227#endif /* LODEPNG_COMPILE_ENCODER */7228#endif /* LODEPNG_COMPILE_PNG */7229} /* namespace lodepng */7230#endif /*LODEPNG_COMPILE_CPP*/723172327233