2
LodePNG version 20150418
4
Copyright (c) 2005-2015 Lode Vandevenne
6
!! Xep128 WARNING: this is not the original distribution of LodePNG,
7
!! some lighter modifications have been done!
9
This software is provided 'as-is', without any express or implied
10
warranty. In no event will the authors be held liable for any damages
11
arising from the use of this software.
13
Permission is granted to anyone to use this software for any purpose,
14
including commercial applications, and to alter it and redistribute it
15
freely, subject to the following restrictions:
17
1. The origin of this software must not be misrepresented; you must not
18
claim that you wrote the original software. If you use this software
19
in a product, an acknowledgment in the product documentation would be
20
appreciated but is not required.
22
2. Altered source versions must be plainly marked as such, and must not be
23
misrepresented as being the original software.
25
3. This notice may not be removed or altered from any source
30
The manual and changelog are in the header file "lodepng.h"
34
//#ifdef NO_SCREENSHOT
35
//#warning "Screenshot with LodePNG is disabled by configuration."
38
#ifdef CONFIG_USE_LODEPNG
40
#include "xemu/lodepng.h"
45
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
46
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
47
#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
50
const char* LODEPNG_VERSION_STRING = "20150418";
53
This source file is built up in the following large parts. The code sections
54
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
55
-Tools for C and common code for PNG and Zlib
56
-C Code for Zlib (huffman, deflate, ...)
57
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
58
-The C++ wrapper around all of the above
61
/*The malloc, realloc and free functions defined here with "lodepng_" in front
62
of the name, so that you can easily change them to others related to your
63
platform if needed. Everything else in the code calls these. Pass
64
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
65
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
66
define them in your own project's source files without needing to change
67
lodepng source code. Don't forget to remove "static" if you copypaste them
70
#ifdef LODEPNG_COMPILE_ALLOCATORS
71
static void* lodepng_malloc(size_t size)
76
static void* lodepng_realloc(void* ptr, size_t new_size)
78
return realloc(ptr, new_size);
81
static void lodepng_free(void* ptr)
85
#else /*LODEPNG_COMPILE_ALLOCATORS*/
86
void* lodepng_malloc(size_t size);
87
void* lodepng_realloc(void* ptr, size_t new_size);
88
void lodepng_free(void* ptr);
89
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
91
/* ////////////////////////////////////////////////////////////////////////// */
92
/* ////////////////////////////////////////////////////////////////////////// */
93
/* // Tools for C, and common code for PNG and Zlib. // */
94
/* ////////////////////////////////////////////////////////////////////////// */
95
/* ////////////////////////////////////////////////////////////////////////// */
98
Often in case of an error a value is assigned to a variable and then it breaks
99
out of a loop (to go to the cleanup phase of a function). This macro does that.
100
It makes the error handling code shorter and more readable.
102
Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
104
#define CERROR_BREAK(errorvar, code)\
110
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
111
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
113
/*Set error var to the error code, and return it.*/
114
#define CERROR_RETURN_ERROR(errorvar, code)\
120
/*Try the code, if it returns error, also return the error.*/
121
#define CERROR_TRY_RETURN(call)\
123
unsigned error = call;\
124
if(error) return error;\
127
/*Set error var to the error code, and return from the void function.*/
128
#define CERROR_RETURN(errorvar, code)\
135
About uivector, ucvector and string:
136
-All of them wrap dynamic arrays or text strings in a similar way.
137
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
138
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
139
-They're not used in the interface, only internally in this file as static functions.
140
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
143
#ifdef LODEPNG_COMPILE_ZLIB
144
/*dynamic vector of unsigned ints*/
145
typedef struct uivector
148
size_t size; /*size in number of unsigned longs*/
149
size_t allocsize; /*allocated size in bytes*/
152
static void uivector_cleanup(void* p)
154
((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
155
lodepng_free(((uivector*)p)->data);
156
((uivector*)p)->data = NULL;
159
/*returns 1 if success, 0 if failure ==> nothing done*/
160
static unsigned uivector_reserve(uivector* p, size_t allocsize)
162
if(allocsize > p->allocsize)
164
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
165
void* data = lodepng_realloc(p->data, newsize);
168
p->allocsize = newsize;
169
p->data = (unsigned*)data;
171
else return 0; /*error: not enough memory*/
176
/*returns 1 if success, 0 if failure ==> nothing done*/
177
static unsigned uivector_resize(uivector* p, size_t size)
179
if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
181
return 1; /*success*/
184
/*resize and give all new elements the value*/
185
static unsigned uivector_resizev(uivector* p, size_t size, unsigned value)
187
size_t oldsize = p->size, i;
188
if(!uivector_resize(p, size)) return 0;
189
for(i = oldsize; i < size; ++i) p->data[i] = value;
193
static void uivector_init(uivector* p)
196
p->size = p->allocsize = 0;
199
#ifdef LODEPNG_COMPILE_ENCODER
200
/*returns 1 if success, 0 if failure ==> nothing done*/
201
static unsigned uivector_push_back(uivector* p, unsigned c)
203
if(!uivector_resize(p, p->size + 1)) return 0;
204
p->data[p->size - 1] = c;
207
#endif /*LODEPNG_COMPILE_ENCODER*/
208
#endif /*LODEPNG_COMPILE_ZLIB*/
210
/* /////////////////////////////////////////////////////////////////////////// */
212
/*dynamic vector of unsigned chars*/
213
typedef struct ucvector
216
size_t size; /*used size*/
217
size_t allocsize; /*allocated size*/
220
/*returns 1 if success, 0 if failure ==> nothing done*/
221
static unsigned ucvector_reserve(ucvector* p, size_t allocsize)
223
if(allocsize > p->allocsize)
225
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
226
void* data = lodepng_realloc(p->data, newsize);
229
p->allocsize = newsize;
230
p->data = (unsigned char*)data;
232
else return 0; /*error: not enough memory*/
237
/*returns 1 if success, 0 if failure ==> nothing done*/
238
static unsigned ucvector_resize(ucvector* p, size_t size)
240
if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
242
return 1; /*success*/
245
#ifdef LODEPNG_COMPILE_PNG
247
static void ucvector_cleanup(void* p)
249
((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
250
lodepng_free(((ucvector*)p)->data);
251
((ucvector*)p)->data = NULL;
254
static void ucvector_init(ucvector* p)
257
p->size = p->allocsize = 0;
260
#ifdef LODEPNG_COMPILE_DECODER
261
/*resize and give all new elements the value*/
262
static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value)
264
size_t oldsize = p->size, i;
265
if(!ucvector_resize(p, size)) return 0;
266
for(i = oldsize; i < size; ++i) p->data[i] = value;
269
#endif /*LODEPNG_COMPILE_DECODER*/
270
#endif /*LODEPNG_COMPILE_PNG*/
272
#ifdef LODEPNG_COMPILE_ZLIB
273
/*you can both convert from vector to buffer&size and vica versa. If you use
274
init_buffer to take over a buffer and size, it is not needed to use cleanup*/
275
static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size)
278
p->allocsize = p->size = size;
280
#endif /*LODEPNG_COMPILE_ZLIB*/
282
#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
283
/*returns 1 if success, 0 if failure ==> nothing done*/
284
static unsigned ucvector_push_back(ucvector* p, unsigned char c)
286
if(!ucvector_resize(p, p->size + 1)) return 0;
287
p->data[p->size - 1] = c;
290
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
293
/* ////////////////////////////////////////////////////////////////////////// */
295
#ifdef LODEPNG_COMPILE_PNG
296
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
297
/*returns 1 if success, 0 if failure ==> nothing done*/
298
static unsigned string_resize(char** out, size_t size)
300
char* data = (char*)lodepng_realloc(*out, size + 1);
303
data[size] = 0; /*null termination char*/
309
/*init a {char*, size_t} pair for use as string*/
310
static void string_init(char** out)
313
string_resize(out, 0);
316
/*free the above pair again*/
317
static void string_cleanup(char** out)
323
static void string_set(char** out, const char* in)
325
size_t insize = strlen(in), i;
326
if(string_resize(out, insize))
328
for(i = 0; i != insize; ++i)
334
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
335
#endif /*LODEPNG_COMPILE_PNG*/
337
/* ////////////////////////////////////////////////////////////////////////// */
339
unsigned lodepng_read32bitInt(const unsigned char* buffer)
341
return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
344
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
345
/*buffer must have at least 4 allocated bytes available*/
346
static void lodepng_set32bitInt(unsigned char* buffer, unsigned value)
348
buffer[0] = (unsigned char)((value >> 24) & 0xff);
349
buffer[1] = (unsigned char)((value >> 16) & 0xff);
350
buffer[2] = (unsigned char)((value >> 8) & 0xff);
351
buffer[3] = (unsigned char)((value ) & 0xff);
353
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
355
#ifdef LODEPNG_COMPILE_ENCODER
356
static void lodepng_add32bitInt(ucvector* buffer, unsigned value)
358
ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
359
lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
361
#endif /*LODEPNG_COMPILE_ENCODER*/
363
/* ////////////////////////////////////////////////////////////////////////// */
365
/* ////////////////////////////////////////////////////////////////////////// */
367
#ifdef LODEPNG_COMPILE_DISK
369
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename)
374
/*provide some proper output values if error will happen*/
378
file = fopen(filename, "rb");
382
fseek(file , 0 , SEEK_END);
386
/*read contents of the file into the vector*/
388
*out = (unsigned char*)lodepng_malloc((size_t)size);
389
if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file);
392
if(!(*out) && size) return 83; /*the above malloc failed*/
396
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
397
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename)
400
file = fopen(filename, "wb" );
402
fwrite((char*)buffer , 1 , buffersize, file);
407
#endif /*LODEPNG_COMPILE_DISK*/
409
/* ////////////////////////////////////////////////////////////////////////// */
410
/* ////////////////////////////////////////////////////////////////////////// */
411
/* // End of common code and tools. Begin of Zlib related code. // */
412
/* ////////////////////////////////////////////////////////////////////////// */
413
/* ////////////////////////////////////////////////////////////////////////// */
415
#ifdef LODEPNG_COMPILE_ZLIB
416
#ifdef LODEPNG_COMPILE_ENCODER
417
/*TODO: this ignores potential out of memory errors*/
418
#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\
420
/*add a new byte at the end*/\
421
if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\
422
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\
423
(bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
427
static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
430
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
433
static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
436
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
438
#endif /*LODEPNG_COMPILE_ENCODER*/
440
#ifdef LODEPNG_COMPILE_DECODER
442
#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
444
static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream)
446
unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
451
static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
453
unsigned result = 0, i;
454
for(i = 0; i != nbits; ++i)
456
result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
461
#endif /*LODEPNG_COMPILE_DECODER*/
463
/* ////////////////////////////////////////////////////////////////////////// */
464
/* / Deflate - Huffman / */
465
/* ////////////////////////////////////////////////////////////////////////// */
467
#define FIRST_LENGTH_CODE_INDEX 257
468
#define LAST_LENGTH_CODE_INDEX 285
469
/*256 literals, the end code, some length codes, and 2 unused codes*/
470
#define NUM_DEFLATE_CODE_SYMBOLS 288
471
/*the distance codes have their own symbols, 30 used, 2 unused*/
472
#define NUM_DISTANCE_SYMBOLS 32
473
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
474
#define NUM_CODE_LENGTH_CODES 19
476
/*the base lengths represented by codes 257-285*/
477
static const unsigned LENGTHBASE[29]
478
= {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
479
67, 83, 99, 115, 131, 163, 195, 227, 258};
481
/*the extra bits used by codes 257-285 (added to base length)*/
482
static const unsigned LENGTHEXTRA[29]
483
= {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
484
4, 4, 4, 4, 5, 5, 5, 5, 0};
486
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
487
static const unsigned DISTANCEBASE[30]
488
= {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
489
769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
491
/*the extra bits of backwards distances (added to base)*/
492
static const unsigned DISTANCEEXTRA[30]
493
= {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
494
8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
496
/*the order in which "code length alphabet code lengths" are stored, out of this
497
the huffman tree of the dynamic huffman tree lengths is generated*/
498
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
499
= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
501
/* ////////////////////////////////////////////////////////////////////////// */
504
Huffman tree struct, containing multiple representations of the tree
506
typedef struct HuffmanTree
510
unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
511
unsigned maxbitlen; /*maximum number of bits a single code can get*/
512
unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
515
/*function used for debug purposes to draw the tree in ascii art with C++*/
517
static void HuffmanTree_draw(HuffmanTree* tree)
519
std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
520
for(size_t i = 0; i != tree->tree1d.size; ++i)
522
if(tree->lengths.data[i])
523
std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
525
std::cout << std::endl;
528
static void HuffmanTree_init(HuffmanTree* tree)
535
static void HuffmanTree_cleanup(HuffmanTree* tree)
537
lodepng_free(tree->tree2d);
538
lodepng_free(tree->tree1d);
539
lodepng_free(tree->lengths);
542
/*the tree representation used by the decoder. return value is error*/
543
static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
545
unsigned nodefilled = 0; /*up to which node it is filled*/
546
unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
549
tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
550
if(!tree->tree2d) return 83; /*alloc fail*/
553
convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
554
uninited, a value >= numcodes is an address to another bit, a value < numcodes
555
is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
556
many columns as codes - 1.
557
A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
558
Here, the internal nodes are stored (what their 0 and 1 option point to).
559
There is only memory for such good tree currently, if there are more nodes
560
(due to too long length codes), error 55 will happen
562
for(n = 0; n < tree->numcodes * 2; ++n)
564
tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
567
for(n = 0; n < tree->numcodes; ++n) /*the codes*/
569
for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/
571
unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
572
/*oversubscribed, see comment in lodepng_error_text*/
573
if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55;
574
if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
576
if(i + 1 == tree->lengths[n]) /*last bit*/
578
tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
583
/*put address of the next step in here, first that address has to be found of course
584
(it's just nodefilled + 1)...*/
586
/*addresses encoded with numcodes added to it*/
587
tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
588
treepos = nodefilled;
591
else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
595
for(n = 0; n < tree->numcodes * 2; ++n)
597
if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
604
Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
605
numcodes, lengths and maxbitlen must already be filled in correctly. return
608
static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
615
uivector_init(&blcount);
616
uivector_init(&nextcode);
618
tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
619
if(!tree->tree1d) error = 83; /*alloc fail*/
621
if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
622
|| !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
623
error = 83; /*alloc fail*/
627
/*step 1: count number of instances of each code length*/
628
for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]];
629
/*step 2: generate the nextcode values*/
630
for(bits = 1; bits <= tree->maxbitlen; ++bits)
632
nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
634
/*step 3: generate all the codes*/
635
for(n = 0; n != tree->numcodes; ++n)
637
if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
641
uivector_cleanup(&blcount);
642
uivector_cleanup(&nextcode);
644
if(!error) return HuffmanTree_make2DTree(tree);
649
given the code lengths (as stored in the PNG file), generate the tree as defined
650
by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
651
return value is error.
653
static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
654
size_t numcodes, unsigned maxbitlen)
657
tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
658
if(!tree->lengths) return 83; /*alloc fail*/
659
for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
660
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
661
tree->maxbitlen = maxbitlen;
662
return HuffmanTree_makeFromLengths2(tree);
665
#ifdef LODEPNG_COMPILE_ENCODER
667
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
668
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
670
/*chain node for boundary package merge*/
671
typedef struct BPMNode
673
int weight; /*the sum of all weights in this chain*/
674
unsigned index; /*index of this leaf node (called "count" in the paper)*/
675
struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
680
typedef struct BPMLists
688
/*two heads of lookahead chains per list*/
694
/*creates a new chain node with the given parameters, from the memory in the lists */
695
static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail)
700
/*memory full, so garbage collect*/
701
if(lists->nextfree >= lists->numfree)
703
/*mark only those that are in use*/
704
for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
705
for(i = 0; i != lists->listsize; ++i)
708
for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
709
for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
711
/*collect those that are free*/
713
for(i = 0; i != lists->memsize; ++i)
715
if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
720
result = lists->freelist[lists->nextfree++];
721
result->weight = weight;
722
result->index = index;
727
static int bpmnode_compare(const void* a, const void* b)
729
int wa = ((const BPMNode*)a)->weight;
730
int wb = ((const BPMNode*)b)->weight;
731
if(wa < wb) return -1;
732
if(wa > wb) return 1;
733
/*make the qsort a stable sort*/
734
return ((const BPMNode*)a)->index < ((const BPMNode*)b)->index ? 1 : -1;
737
/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
738
static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num)
740
unsigned lastindex = lists->chains1[c]->index;
744
if(lastindex >= numpresent) return;
745
lists->chains0[c] = lists->chains1[c];
746
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
750
/*sum of the weights of the head nodes of the previous lookahead chains.*/
751
int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
752
lists->chains0[c] = lists->chains1[c];
753
if(lastindex < numpresent && sum > leaves[lastindex].weight)
755
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
758
lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
759
/*in the end we are only interested in the chain of the last list, so no
760
need to recurse if we're at the last one (this gives measurable speedup)*/
761
if(num + 1 < (int)(2 * numpresent - 2))
763
boundaryPM(lists, leaves, numpresent, c - 1, num);
764
boundaryPM(lists, leaves, numpresent, c - 1, num);
769
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
770
size_t numcodes, unsigned maxbitlen)
774
size_t numpresent = 0; /*number of symbols with non-zero frequency*/
775
BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
777
if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
778
if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/
780
leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
781
if(!leaves) return 83; /*alloc fail*/
783
for(i = 0; i != numcodes; ++i)
785
if(frequencies[i] > 0)
787
leaves[numpresent].weight = frequencies[i];
788
leaves[numpresent].index = i;
793
for(i = 0; i != numcodes; ++i) lengths[i] = 0;
795
/*ensure at least two present symbols. There should be at least one symbol
796
according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
797
make these work as well ensure there are at least two symbols. The
798
Package-Merge code below also doesn't work correctly if there's only one
799
symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
802
lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
804
else if(numpresent == 1)
806
lengths[leaves[0].index] = 1;
807
lengths[leaves[0].index == 0 ? 1 : 0] = 1;
814
qsort(leaves, numpresent, sizeof(BPMNode), bpmnode_compare);
816
lists.listsize = maxbitlen;
817
lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
819
lists.numfree = lists.memsize;
820
lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
821
lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
822
lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
823
lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
824
if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
828
for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
830
bpmnode_create(&lists, leaves[0].weight, 1, 0);
831
bpmnode_create(&lists, leaves[1].weight, 2, 0);
833
for(i = 0; i != lists.listsize; ++i)
835
lists.chains0[i] = &lists.memory[0];
836
lists.chains1[i] = &lists.memory[1];
839
/*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
840
for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, maxbitlen - 1, i);
842
for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail)
844
for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
848
lodepng_free(lists.memory);
849
lodepng_free(lists.freelist);
850
lodepng_free(lists.chains0);
851
lodepng_free(lists.chains1);
854
lodepng_free(leaves);
858
/*Create the Huffman tree given the symbol frequencies*/
859
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
860
size_t mincodes, size_t numcodes, unsigned maxbitlen)
863
while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
864
tree->maxbitlen = maxbitlen;
865
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
866
tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
867
if(!tree->lengths) return 83; /*alloc fail*/
868
/*initialize all lengths to 0*/
869
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
871
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
872
if(!error) error = HuffmanTree_makeFromLengths2(tree);
876
static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
878
return tree->tree1d[index];
881
static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index)
883
return tree->lengths[index];
885
#endif /*LODEPNG_COMPILE_ENCODER*/
887
/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
888
static unsigned generateFixedLitLenTree(HuffmanTree* tree)
890
unsigned i, error = 0;
891
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
892
if(!bitlen) return 83; /*alloc fail*/
894
/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
895
for(i = 0; i <= 143; ++i) bitlen[i] = 8;
896
for(i = 144; i <= 255; ++i) bitlen[i] = 9;
897
for(i = 256; i <= 279; ++i) bitlen[i] = 7;
898
for(i = 280; i <= 287; ++i) bitlen[i] = 8;
900
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
902
lodepng_free(bitlen);
906
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
907
static unsigned generateFixedDistanceTree(HuffmanTree* tree)
909
unsigned i, error = 0;
910
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
911
if(!bitlen) return 83; /*alloc fail*/
913
/*there are 32 distance codes, but 30-31 are unused*/
914
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
915
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
917
lodepng_free(bitlen);
921
#ifdef LODEPNG_COMPILE_DECODER
924
returns the code, or (unsigned)(-1) if error happened
925
inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
927
static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
928
const HuffmanTree* codetree, size_t inbitlength)
930
unsigned treepos = 0, ct;
933
if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
935
decode the symbol from the tree. The "readBitFromStream" code is inlined in
936
the expression below because this is the biggest bottleneck while decoding
938
ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
940
if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
941
else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
943
if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
946
#endif /*LODEPNG_COMPILE_DECODER*/
948
#ifdef LODEPNG_COMPILE_DECODER
950
/* ////////////////////////////////////////////////////////////////////////// */
951
/* / Inflator (Decompressor) / */
952
/* ////////////////////////////////////////////////////////////////////////// */
954
/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
955
static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
957
/*TODO: check for out of memory errors*/
958
generateFixedLitLenTree(tree_ll);
959
generateFixedDistanceTree(tree_d);
962
/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
963
static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
964
const unsigned char* in, size_t* bp, size_t inlength)
966
/*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
968
unsigned n, HLIT, HDIST, HCLEN, i;
969
size_t inbitlength = inlength * 8;
971
/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
972
unsigned* bitlen_ll = 0; /*lit,len code lengths*/
973
unsigned* bitlen_d = 0; /*dist code lengths*/
974
/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
975
unsigned* bitlen_cl = 0;
976
HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
978
if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
980
/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
981
HLIT = readBitsFromStream(bp, in, 5) + 257;
982
/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
983
HDIST = readBitsFromStream(bp, in, 5) + 1;
984
/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
985
HCLEN = readBitsFromStream(bp, in, 4) + 4;
987
if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
989
HuffmanTree_init(&tree_cl);
993
/*read the code length codes out of 3 * (amount of code length codes) bits*/
995
bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
996
if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
998
for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i)
1000
if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
1001
else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
1004
error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
1007
/*now we can use this tree to read the lengths for the tree that this function will return*/
1008
bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
1009
bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
1010
if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
1011
for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
1012
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
1014
/*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1016
while(i < HLIT + HDIST)
1018
unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
1019
if(code <= 15) /*a length code*/
1021
if(i < HLIT) bitlen_ll[i] = code;
1022
else bitlen_d[i - HLIT] = code;
1025
else if(code == 16) /*repeat previous*/
1027
unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1028
unsigned value; /*set value to the previous code*/
1030
if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1032
if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1033
replength += readBitsFromStream(bp, in, 2);
1035
if(i < HLIT + 1) value = bitlen_ll[i - 1];
1036
else value = bitlen_d[i - HLIT - 1];
1037
/*repeat this value in the next lengths*/
1038
for(n = 0; n < replength; ++n)
1040
if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1041
if(i < HLIT) bitlen_ll[i] = value;
1042
else bitlen_d[i - HLIT] = value;
1046
else if(code == 17) /*repeat "0" 3-10 times*/
1048
unsigned replength = 3; /*read in the bits that indicate repeat length*/
1049
if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1050
replength += readBitsFromStream(bp, in, 3);
1052
/*repeat this value in the next lengths*/
1053
for(n = 0; n < replength; ++n)
1055
if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1057
if(i < HLIT) bitlen_ll[i] = 0;
1058
else bitlen_d[i - HLIT] = 0;
1062
else if(code == 18) /*repeat "0" 11-138 times*/
1064
unsigned replength = 11; /*read in the bits that indicate repeat length*/
1065
if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1066
replength += readBitsFromStream(bp, in, 7);
1068
/*repeat this value in the next lengths*/
1069
for(n = 0; n < replength; ++n)
1071
if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1073
if(i < HLIT) bitlen_ll[i] = 0;
1074
else bitlen_d[i - HLIT] = 0;
1078
else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1080
if(code == (unsigned)(-1))
1082
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1083
(10=no endcode, 11=wrong jump outside of tree)*/
1084
error = (*bp) > inbitlength ? 10 : 11;
1086
else error = 16; /*unexisting code, this can never happen*/
1092
if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1094
/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1095
error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
1097
error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
1099
break; /*end of error-while*/
1102
lodepng_free(bitlen_cl);
1103
lodepng_free(bitlen_ll);
1104
lodepng_free(bitlen_d);
1105
HuffmanTree_cleanup(&tree_cl);
1110
/*inflate a block with dynamic of fixed Huffman tree*/
1111
static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
1112
size_t* pos, size_t inlength, unsigned btype)
1115
HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
1116
HuffmanTree tree_d; /*the huffman tree for distance codes*/
1117
size_t inbitlength = inlength * 8;
1119
HuffmanTree_init(&tree_ll);
1120
HuffmanTree_init(&tree_d);
1122
if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
1123
else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
1125
while(!error) /*decode all symbols until end reached, breaks at end code*/
1127
/*code_ll is literal, length or end code*/
1128
unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
1129
if(code_ll <= 255) /*literal symbol*/
1131
/*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
1132
if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
1133
out->data[*pos] = (unsigned char)code_ll;
1136
else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
1138
unsigned code_d, distance;
1139
unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
1140
size_t start, forward, backward, length;
1142
/*part 1: get length base*/
1143
length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
1145
/*part 2: get extra bits and add the value of that to length*/
1146
numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
1147
if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1148
length += readBitsFromStream(bp, in, numextrabits_l);
1150
/*part 3: get distance code*/
1151
code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
1154
if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1156
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1157
(10=no endcode, 11=wrong jump outside of tree)*/
1158
error = (*bp) > inlength * 8 ? 10 : 11;
1160
else error = 18; /*error: invalid distance code (30-31 are never used)*/
1163
distance = DISTANCEBASE[code_d];
1165
/*part 4: get extra bits from distance*/
1166
numextrabits_d = DISTANCEEXTRA[code_d];
1167
if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1168
distance += readBitsFromStream(bp, in, numextrabits_d);
1170
/*part 5: fill in all the out[n] values based on the length and dist*/
1172
if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
1173
backward = start - distance;
1175
if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
1176
if (distance < length) {
1177
for(forward = 0; forward < length; ++forward)
1179
out->data[(*pos)++] = out->data[backward++];
1182
memcpy(out->data + *pos, out->data + backward, length);
1186
else if(code_ll == 256)
1188
break; /*end code, break the loop*/
1190
else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1192
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1193
(10=no endcode, 11=wrong jump outside of tree)*/
1194
error = ((*bp) > inlength * 8) ? 10 : 11;
1199
HuffmanTree_cleanup(&tree_ll);
1200
HuffmanTree_cleanup(&tree_d);
1205
static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength)
1208
unsigned LEN, NLEN, n, error = 0;
1210
/*go to first boundary of byte*/
1211
while(((*bp) & 0x7) != 0) ++(*bp);
1212
p = (*bp) / 8; /*byte position*/
1214
/*read LEN (2 bytes) and NLEN (2 bytes)*/
1215
if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/
1216
LEN = in[p] + 256u * in[p + 1]; p += 2;
1217
NLEN = in[p] + 256u * in[p + 1]; p += 2;
1219
/*check if 16-bit NLEN is really the one's complement of LEN*/
1220
if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
1222
if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
1224
/*read the literal data: LEN bytes are now stored in the out buffer*/
1225
if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
1226
for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++];
1233
static unsigned lodepng_inflatev(ucvector* out,
1234
const unsigned char* in, size_t insize,
1235
const LodePNGDecompressSettings* settings)
1237
/*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1239
unsigned BFINAL = 0;
1240
size_t pos = 0; /*byte position in the out buffer*/
1248
if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
1249
BFINAL = readBitFromStream(&bp, in);
1250
BTYPE = 1u * readBitFromStream(&bp, in);
1251
BTYPE += 2u * readBitFromStream(&bp, in);
1253
if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
1254
else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
1255
else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
1257
if(error) return error;
1263
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
1264
const unsigned char* in, size_t insize,
1265
const LodePNGDecompressSettings* settings)
1269
ucvector_init_buffer(&v, *out, *outsize);
1270
error = lodepng_inflatev(&v, in, insize, settings);
1276
static unsigned inflate(unsigned char** out, size_t* outsize,
1277
const unsigned char* in, size_t insize,
1278
const LodePNGDecompressSettings* settings)
1280
if(settings->custom_inflate)
1282
return settings->custom_inflate(out, outsize, in, insize, settings);
1286
return lodepng_inflate(out, outsize, in, insize, settings);
1290
#endif /*LODEPNG_COMPILE_DECODER*/
1292
#ifdef LODEPNG_COMPILE_ENCODER
1294
/* ////////////////////////////////////////////////////////////////////////// */
1295
/* / Deflator (Compressor) / */
1296
/* ////////////////////////////////////////////////////////////////////////// */
1298
static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
1300
/*bitlen is the size in bits of the code*/
1301
static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen)
1303
addBitsToStreamReversed(bp, compressed, code, bitlen);
1306
/*search the index in the array, that has the largest value smaller than or equal to the given value,
1307
given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1308
static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value)
1310
/*linear search implementation*/
1311
/*for(size_t i = 1; i < array_size; ++i) if(array[i] > value) return i - 1;
1312
return array_size - 1;*/
1314
/*binary search implementation (not that much faster) (precondition: array_size > 0)*/
1316
size_t right = array_size - 1;
1317
while(left <= right)
1319
size_t mid = (left + right) / 2;
1320
if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/
1321
else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/
1322
else return mid - 1;
1324
return array_size - 1;
1327
static void addLengthDistance(uivector* values, size_t length, size_t distance)
1329
/*values in encoded vector are those used by deflate:
1330
0-255: literal bytes
1332
257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1335
unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
1336
unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
1337
unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
1338
unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
1340
uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
1341
uivector_push_back(values, extra_length);
1342
uivector_push_back(values, dist_code);
1343
uivector_push_back(values, extra_distance);
1346
/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
1347
bytes as input because 3 is the minimum match length for deflate*/
1348
static const unsigned HASH_NUM_VALUES = 65536;
1349
static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
1353
int* head; /*hash value to head circular pos - can be outdated if went around window*/
1354
/*circular pos to prev circular pos*/
1355
unsigned short* chain;
1356
int* val; /*circular pos to hash value*/
1358
/*TODO: do this not only for zeros but for any repeated byte. However for PNG
1359
it's always going to be the zeros that dominate, so not important for PNG*/
1360
int* headz; /*similar to head, but for chainz*/
1361
unsigned short* chainz; /*those with same amount of zeros*/
1362
unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
1365
static unsigned hash_init(Hash* hash, unsigned windowsize)
1368
hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
1369
hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
1370
hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1372
hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1373
hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
1374
hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1376
if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros)
1378
return 83; /*alloc fail*/
1381
/*initialize hash table*/
1382
for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
1383
for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
1384
for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
1386
for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
1387
for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
1392
static void hash_cleanup(Hash* hash)
1394
lodepng_free(hash->head);
1395
lodepng_free(hash->val);
1396
lodepng_free(hash->chain);
1398
lodepng_free(hash->zeros);
1399
lodepng_free(hash->headz);
1400
lodepng_free(hash->chainz);
1405
static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
1407
unsigned result = 0;
1410
/*A simple shift and xor hash is used. Since the data of PNGs is dominated
1411
by zeroes due to the filters, a better hash does not have a significant
1412
effect on speed in traversing the chain, and causes more time spend on
1413
calculating the hash.*/
1414
result ^= (unsigned)(data[pos + 0] << 0u);
1415
result ^= (unsigned)(data[pos + 1] << 4u);
1416
result ^= (unsigned)(data[pos + 2] << 8u);
1419
if(pos >= size) return 0;
1420
amount = size - pos;
1421
for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
1423
return result & HASH_BIT_MASK;
1426
static unsigned countZeros(const unsigned char* data, size_t size, size_t pos)
1428
const unsigned char* start = data + pos;
1429
const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
1430
if(end > data + size) end = data + size;
1432
while(data != end && *data == 0) ++data;
1433
/*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1434
return (unsigned)(data - start);
1437
/*wpos = pos & (windowsize - 1)*/
1438
static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros)
1440
hash->val[wpos] = (int)hashval;
1441
if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
1442
hash->head[hashval] = wpos;
1444
hash->zeros[wpos] = numzeros;
1445
if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
1446
hash->headz[numzeros] = wpos;
1450
LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1451
is in the form of unsigned integers with codes representing for example literal bytes, or
1452
length/distance pairs.
1453
It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1454
sliding window (of windowsize) is used, and all past bytes in that window can be used as
1455
the "dictionary". A brute force search through all possible distances would be slow, and
1456
this hash technique is one out of several ways to speed this up.
1458
static unsigned encodeLZ77(uivector* out, Hash* hash,
1459
const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
1460
unsigned minmatch, unsigned nicematch, unsigned lazymatching)
1463
unsigned i, error = 0;
1464
/*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1465
unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
1466
unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
1468
unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
1469
unsigned numzeros = 0;
1471
unsigned offset; /*the offset represents the distance in LZ77 terminology*/
1474
unsigned lazylength = 0, lazyoffset = 0;
1476
unsigned current_offset, current_length;
1477
unsigned prev_offset;
1478
const unsigned char *lastptr, *foreptr, *backptr;
1481
if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
1482
if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
1484
if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
1486
for(pos = inpos; pos < insize; ++pos)
1488
size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
1489
unsigned chainlength = 0;
1491
hashval = getHash(in, insize, pos);
1493
if(usezeros && hashval == 0)
1495
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1496
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1503
updateHashChain(hash, wpos, hashval, numzeros);
1505
/*the length and offset found for the current position*/
1509
hashpos = hash->chain[wpos];
1511
lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
1513
/*search for the longest string*/
1517
if(chainlength++ >= maxchainlength) break;
1518
current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize;
1520
if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
1521
prev_offset = current_offset;
1522
if(current_offset > 0)
1524
/*test the next characters*/
1526
backptr = &in[pos - current_offset];
1528
/*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1531
unsigned skip = hash->zeros[hashpos];
1532
if(skip > numzeros) skip = numzeros;
1537
while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/
1542
current_length = (unsigned)(foreptr - &in[pos]);
1544
if(current_length > length)
1546
length = current_length; /*the longest length*/
1547
offset = current_offset; /*the offset that is related to this longest length*/
1548
/*jump out once a length of max length is found (speed gain). This also jumps
1549
out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
1550
if(current_length >= nicematch) break;
1554
if(hashpos == hash->chain[hashpos]) break;
1556
if(numzeros >= 3 && length > numzeros)
1558
hashpos = hash->chainz[hashpos];
1559
if(hash->zeros[hashpos] != numzeros) break;
1563
hashpos = hash->chain[hashpos];
1564
/*outdated hash value, happens if particular value was not encountered in whole last window*/
1565
if(hash->val[hashpos] != (int)hashval) break;
1571
if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH)
1574
lazylength = length;
1575
lazyoffset = offset;
1576
continue; /*try the next byte*/
1581
if(pos == 0) ERROR_BREAK(81);
1582
if(length > lazylength + 1)
1584
/*push the previous character as literal*/
1585
if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
1589
length = lazylength;
1590
offset = lazyoffset;
1591
hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1592
hash->headz[numzeros] = -1; /*idem*/
1597
if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1599
/*encode it as length/distance pair or literal value*/
1600
if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1602
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1604
else if(length < minmatch || (length == 3 && offset > 4096))
1606
/*compensate for the fact that longer offsets have more extra bits, a
1607
length of only 3 may be not worth it then*/
1608
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1612
addLengthDistance(out, length, offset);
1613
for(i = 1; i < length; ++i)
1616
wpos = pos & (windowsize - 1);
1617
hashval = getHash(in, insize, pos);
1618
if(usezeros && hashval == 0)
1620
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1621
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1627
updateHashChain(hash, wpos, hashval, numzeros);
1630
} /*end of the loop through each character of input*/
1635
/* /////////////////////////////////////////////////////////////////////////// */
1637
static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize)
1639
/*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1640
2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1642
size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
1643
unsigned datapos = 0;
1644
for(i = 0; i != numdeflateblocks; ++i)
1646
unsigned BFINAL, BTYPE, LEN, NLEN;
1647
unsigned char firstbyte;
1649
BFINAL = (i == numdeflateblocks - 1);
1652
firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
1653
ucvector_push_back(out, firstbyte);
1656
if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
1659
ucvector_push_back(out, (unsigned char)(LEN % 256));
1660
ucvector_push_back(out, (unsigned char)(LEN / 256));
1661
ucvector_push_back(out, (unsigned char)(NLEN % 256));
1662
ucvector_push_back(out, (unsigned char)(NLEN / 256));
1664
/*Decompressed data*/
1665
for(j = 0; j < 65535 && datapos < datasize; ++j)
1667
ucvector_push_back(out, data[datapos++]);
1675
write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1676
tree_ll: the tree for lit and len codes.
1677
tree_d: the tree for distance codes.
1679
static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
1680
const HuffmanTree* tree_ll, const HuffmanTree* tree_d)
1683
for(i = 0; i != lz77_encoded->size; ++i)
1685
unsigned val = lz77_encoded->data[i];
1686
addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
1687
if(val > 256) /*for a length code, 3 more things have to be added*/
1689
unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
1690
unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
1691
unsigned length_extra_bits = lz77_encoded->data[++i];
1693
unsigned distance_code = lz77_encoded->data[++i];
1695
unsigned distance_index = distance_code;
1696
unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
1697
unsigned distance_extra_bits = lz77_encoded->data[++i];
1699
addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
1700
addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
1701
HuffmanTree_getLength(tree_d, distance_code));
1702
addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
1707
/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1708
static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
1709
const unsigned char* data, size_t datapos, size_t dataend,
1710
const LodePNGCompressSettings* settings, unsigned final)
1715
A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1716
literal bytes and length/distance pairs. This is then huffman compressed with
1717
two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1718
another huffman tree is used for the dist values ("d"). These two trees are
1719
stored using their code lengths, and to compress even more these code lengths
1720
are also run-length encoded and huffman compressed. This gives a huffman tree
1721
of code lengths "cl". The code lenghts used to describe this third tree are
1722
the code length code lengths ("clcl").
1725
/*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1726
uivector lz77_encoded;
1727
HuffmanTree tree_ll; /*tree for lit,len values*/
1728
HuffmanTree tree_d; /*tree for distance codes*/
1729
HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1730
uivector frequencies_ll; /*frequency of lit,len codes*/
1731
uivector frequencies_d; /*frequency of dist codes*/
1732
uivector frequencies_cl; /*frequency of code length codes*/
1733
uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1734
uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1735
/*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1736
(these are written as is in the file, it would be crazy to compress these using yet another huffman
1737
tree that needs to be represented by yet another set of code lengths)*/
1739
size_t datasize = dataend - datapos;
1742
Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1743
bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1744
bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1745
bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1748
unsigned BFINAL = final;
1749
size_t numcodes_ll, numcodes_d, i;
1750
unsigned HLIT, HDIST, HCLEN;
1752
uivector_init(&lz77_encoded);
1753
HuffmanTree_init(&tree_ll);
1754
HuffmanTree_init(&tree_d);
1755
HuffmanTree_init(&tree_cl);
1756
uivector_init(&frequencies_ll);
1757
uivector_init(&frequencies_d);
1758
uivector_init(&frequencies_cl);
1759
uivector_init(&bitlen_lld);
1760
uivector_init(&bitlen_lld_e);
1761
uivector_init(&bitlen_cl);
1763
/*This while loop never loops due to a break at the end, it is here to
1764
allow breaking out of it to the cleanup phase on error conditions.*/
1767
if(settings->use_lz77)
1769
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1770
settings->minmatch, settings->nicematch, settings->lazymatching);
1775
if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
1776
for(i = datapos; i < dataend; ++i) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/
1779
if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
1780
if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
1782
/*Count the frequencies of lit, len and dist codes*/
1783
for(i = 0; i != lz77_encoded.size; ++i)
1785
unsigned symbol = lz77_encoded.data[i];
1786
++frequencies_ll.data[symbol];
1789
unsigned dist = lz77_encoded.data[i + 2];
1790
++frequencies_d.data[dist];
1794
frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1796
/*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1797
error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
1799
/*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1800
error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
1803
numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
1804
numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
1805
/*store the code lengths of both generated trees in bitlen_lld*/
1806
for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
1807
for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
1809
/*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1810
17 (3-10 zeroes), 18 (11-138 zeroes)*/
1811
for(i = 0; i != (unsigned)bitlen_lld.size; ++i)
1813
unsigned j = 0; /*amount of repititions*/
1814
while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
1816
if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/
1818
++j; /*include the first zero*/
1819
if(j <= 10) /*repeat code 17 supports max 10 zeroes*/
1821
uivector_push_back(&bitlen_lld_e, 17);
1822
uivector_push_back(&bitlen_lld_e, j - 3);
1824
else /*repeat code 18 supports max 138 zeroes*/
1826
if(j > 138) j = 138;
1827
uivector_push_back(&bitlen_lld_e, 18);
1828
uivector_push_back(&bitlen_lld_e, j - 11);
1832
else if(j >= 3) /*repeat code for value other than zero*/
1835
unsigned num = j / 6, rest = j % 6;
1836
uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1837
for(k = 0; k < num; ++k)
1839
uivector_push_back(&bitlen_lld_e, 16);
1840
uivector_push_back(&bitlen_lld_e, 6 - 3);
1844
uivector_push_back(&bitlen_lld_e, 16);
1845
uivector_push_back(&bitlen_lld_e, rest - 3);
1850
else /*too short to benefit from repeat code*/
1852
uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
1856
/*generate tree_cl, the huffmantree of huffmantrees*/
1858
if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
1859
for(i = 0; i != bitlen_lld_e.size; ++i)
1861
++frequencies_cl.data[bitlen_lld_e.data[i]];
1862
/*after a repeat code come the bits that specify the number of repetitions,
1863
those don't need to be in the frequencies_cl calculation*/
1864
if(bitlen_lld_e.data[i] >= 16) ++i;
1867
error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
1868
frequencies_cl.size, frequencies_cl.size, 7);
1871
if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
1872
for(i = 0; i != tree_cl.numcodes; ++i)
1874
/*lenghts of code length tree is in the order as specified by deflate*/
1875
bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
1877
while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4)
1879
/*remove zeros at the end, but minimum size must be 4*/
1880
if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
1885
Write everything into the output
1887
After the BFINAL and BTYPE, the dynamic block consists out of the following:
1888
- 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1889
- (HCLEN+4)*3 bits code lengths of code length alphabet
1890
- HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
1891
alphabet, + possible repetition codes 16, 17, 18)
1892
- HDIST + 1 code lengths of distance alphabet (encoded using the code length
1893
alphabet, + possible repetition codes 16, 17, 18)
1898
/*Write block type*/
1899
addBitToStream(bp, out, BFINAL);
1900
addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
1901
addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
1903
/*write the HLIT, HDIST and HCLEN values*/
1904
HLIT = (unsigned)(numcodes_ll - 257);
1905
HDIST = (unsigned)(numcodes_d - 1);
1906
HCLEN = (unsigned)bitlen_cl.size - 4;
1907
/*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
1908
while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
1909
addBitsToStream(bp, out, HLIT, 5);
1910
addBitsToStream(bp, out, HDIST, 5);
1911
addBitsToStream(bp, out, HCLEN, 4);
1913
/*write the code lenghts of the code length alphabet*/
1914
for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
1916
/*write the lenghts of the lit/len AND the dist alphabet*/
1917
for(i = 0; i != bitlen_lld_e.size; ++i)
1919
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
1920
HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
1921
/*extra bits of repeat codes*/
1922
if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
1923
else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
1924
else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
1927
/*write the compressed data symbols*/
1928
writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1929
/*error: the length of the end code 256 must be larger than 0*/
1930
if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
1932
/*write the end code*/
1933
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1935
break; /*end of error-while*/
1939
uivector_cleanup(&lz77_encoded);
1940
HuffmanTree_cleanup(&tree_ll);
1941
HuffmanTree_cleanup(&tree_d);
1942
HuffmanTree_cleanup(&tree_cl);
1943
uivector_cleanup(&frequencies_ll);
1944
uivector_cleanup(&frequencies_d);
1945
uivector_cleanup(&frequencies_cl);
1946
uivector_cleanup(&bitlen_lld_e);
1947
uivector_cleanup(&bitlen_lld);
1948
uivector_cleanup(&bitlen_cl);
1953
static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
1954
const unsigned char* data,
1955
size_t datapos, size_t dataend,
1956
const LodePNGCompressSettings* settings, unsigned final)
1958
HuffmanTree tree_ll; /*tree for literal values and length codes*/
1959
HuffmanTree tree_d; /*tree for distance codes*/
1961
unsigned BFINAL = final;
1965
HuffmanTree_init(&tree_ll);
1966
HuffmanTree_init(&tree_d);
1968
generateFixedLitLenTree(&tree_ll);
1969
generateFixedDistanceTree(&tree_d);
1971
addBitToStream(bp, out, BFINAL);
1972
addBitToStream(bp, out, 1); /*first bit of BTYPE*/
1973
addBitToStream(bp, out, 0); /*second bit of BTYPE*/
1975
if(settings->use_lz77) /*LZ77 encoded*/
1977
uivector lz77_encoded;
1978
uivector_init(&lz77_encoded);
1979
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1980
settings->minmatch, settings->nicematch, settings->lazymatching);
1981
if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
1982
uivector_cleanup(&lz77_encoded);
1984
else /*no LZ77, but still will be Huffman compressed*/
1986
for(i = datapos; i < dataend; ++i)
1988
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
1992
if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
1995
HuffmanTree_cleanup(&tree_ll);
1996
HuffmanTree_cleanup(&tree_d);
2001
static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
2002
const LodePNGCompressSettings* settings)
2005
size_t i, blocksize, numdeflateblocks;
2006
size_t bp = 0; /*the bit pointer*/
2009
if(settings->btype > 2) return 61;
2010
else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
2011
else if(settings->btype == 1) blocksize = insize;
2012
else /*if(settings->btype == 2)*/
2014
/*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
2015
blocksize = insize / 8 + 8;
2016
if(blocksize < 65536) blocksize = 65536;
2017
if(blocksize > 262144) blocksize = 262144;
2020
numdeflateblocks = (insize + blocksize - 1) / blocksize;
2021
if(numdeflateblocks == 0) numdeflateblocks = 1;
2023
error = hash_init(&hash, settings->windowsize);
2024
if(error) return error;
2026
for(i = 0; i != numdeflateblocks && !error; ++i)
2028
unsigned final = (i == numdeflateblocks - 1);
2029
size_t start = i * blocksize;
2030
size_t end = start + blocksize;
2031
if(end > insize) end = insize;
2033
if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
2034
else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
2037
hash_cleanup(&hash);
2042
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
2043
const unsigned char* in, size_t insize,
2044
const LodePNGCompressSettings* settings)
2048
ucvector_init_buffer(&v, *out, *outsize);
2049
error = lodepng_deflatev(&v, in, insize, settings);
2055
static unsigned deflate(unsigned char** out, size_t* outsize,
2056
const unsigned char* in, size_t insize,
2057
const LodePNGCompressSettings* settings)
2059
if(settings->custom_deflate)
2061
return settings->custom_deflate(out, outsize, in, insize, settings);
2065
return lodepng_deflate(out, outsize, in, insize, settings);
2069
#endif /*LODEPNG_COMPILE_DECODER*/
2071
/* ////////////////////////////////////////////////////////////////////////// */
2073
/* ////////////////////////////////////////////////////////////////////////// */
2075
static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
2077
unsigned s1 = adler & 0xffff;
2078
unsigned s2 = (adler >> 16) & 0xffff;
2082
/*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2083
unsigned amount = len > 5550 ? 5550 : len;
2095
return (s2 << 16) | s1;
2098
/*Return the adler32 of the bytes data[0..len-1]*/
2099
static unsigned adler32(const unsigned char* data, unsigned len)
2101
return update_adler32(1L, data, len);
2104
/* ////////////////////////////////////////////////////////////////////////// */
2106
/* ////////////////////////////////////////////////////////////////////////// */
2108
#ifdef LODEPNG_COMPILE_DECODER
2110
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2111
size_t insize, const LodePNGDecompressSettings* settings)
2114
unsigned CM, CINFO, FDICT;
2116
if(insize < 2) return 53; /*error, size of zlib data too small*/
2117
/*read information from zlib header*/
2118
if((in[0] * 256 + in[1]) % 31 != 0)
2120
/*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2125
CINFO = (in[0] >> 4) & 15;
2126
/*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2127
FDICT = (in[1] >> 5) & 1;
2128
/*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2130
if(CM != 8 || CINFO > 7)
2132
/*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2137
/*error: the specification of PNG says about the zlib stream:
2138
"The additional flags shall not specify a preset dictionary."*/
2142
error = inflate(out, outsize, in + 2, insize - 2, settings);
2143
if(error) return error;
2145
if(!settings->ignore_adler32)
2147
unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
2148
unsigned checksum = adler32(*out, (unsigned)(*outsize));
2149
if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
2152
return 0; /*no error*/
2155
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2156
size_t insize, const LodePNGDecompressSettings* settings)
2158
if(settings->custom_zlib)
2160
return settings->custom_zlib(out, outsize, in, insize, settings);
2164
return lodepng_zlib_decompress(out, outsize, in, insize, settings);
2168
#endif /*LODEPNG_COMPILE_DECODER*/
2170
#ifdef LODEPNG_COMPILE_ENCODER
2172
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2173
size_t insize, const LodePNGCompressSettings* settings)
2175
/*initially, *out must be NULL and outsize 0, if you just give some random *out
2176
that's pointing to a non allocated buffer, this'll crash*/
2180
unsigned char* deflatedata = 0;
2181
size_t deflatesize = 0;
2183
/*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2184
unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2185
unsigned FLEVEL = 0;
2187
unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
2188
unsigned FCHECK = 31 - CMFFLG % 31;
2191
/*ucvector-controlled version of the output buffer, for dynamic array*/
2192
ucvector_init_buffer(&outv, *out, *outsize);
2194
ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256));
2195
ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256));
2197
error = deflate(&deflatedata, &deflatesize, in, insize, settings);
2201
unsigned ADLER32 = adler32(in, (unsigned)insize);
2202
for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]);
2203
lodepng_free(deflatedata);
2204
lodepng_add32bitInt(&outv, ADLER32);
2208
*outsize = outv.size;
2213
/* compress using the default or custom zlib function */
2214
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2215
size_t insize, const LodePNGCompressSettings* settings)
2217
if(settings->custom_zlib)
2219
return settings->custom_zlib(out, outsize, in, insize, settings);
2223
return lodepng_zlib_compress(out, outsize, in, insize, settings);
2227
#endif /*LODEPNG_COMPILE_ENCODER*/
2229
#else /*no LODEPNG_COMPILE_ZLIB*/
2231
#ifdef LODEPNG_COMPILE_DECODER
2232
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2233
size_t insize, const LodePNGDecompressSettings* settings)
2235
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2236
return settings->custom_zlib(out, outsize, in, insize, settings);
2238
#endif /*LODEPNG_COMPILE_DECODER*/
2239
#ifdef LODEPNG_COMPILE_ENCODER
2240
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2241
size_t insize, const LodePNGCompressSettings* settings)
2243
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2244
return settings->custom_zlib(out, outsize, in, insize, settings);
2246
#endif /*LODEPNG_COMPILE_ENCODER*/
2248
#endif /*LODEPNG_COMPILE_ZLIB*/
2250
/* ////////////////////////////////////////////////////////////////////////// */
2252
#ifdef LODEPNG_COMPILE_ENCODER
2254
/*this is a good tradeoff between speed and compression ratio*/
2255
#define DEFAULT_WINDOWSIZE 2048
2257
void lodepng_compress_settings_init(LodePNGCompressSettings* settings)
2259
/*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2260
settings->btype = 2;
2261
settings->use_lz77 = 1;
2262
settings->windowsize = DEFAULT_WINDOWSIZE;
2263
settings->minmatch = 3;
2264
settings->nicematch = 128;
2265
settings->lazymatching = 1;
2267
settings->custom_zlib = 0;
2268
settings->custom_deflate = 0;
2269
settings->custom_context = 0;
2272
const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
2275
#endif /*LODEPNG_COMPILE_ENCODER*/
2277
#ifdef LODEPNG_COMPILE_DECODER
2279
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
2281
settings->ignore_adler32 = 0;
2283
settings->custom_zlib = 0;
2284
settings->custom_inflate = 0;
2285
settings->custom_context = 0;
2288
const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
2290
#endif /*LODEPNG_COMPILE_DECODER*/
2292
/* ////////////////////////////////////////////////////////////////////////// */
2293
/* ////////////////////////////////////////////////////////////////////////// */
2294
/* // End of Zlib related code. Begin of PNG related code. // */
2295
/* ////////////////////////////////////////////////////////////////////////// */
2296
/* ////////////////////////////////////////////////////////////////////////// */
2298
#ifdef LODEPNG_COMPILE_PNG
2300
/* ////////////////////////////////////////////////////////////////////////// */
2302
/* ////////////////////////////////////////////////////////////////////////// */
2304
/* CRC polynomial: 0xedb88320 */
2305
static unsigned lodepng_crc32_table[256] = {
2306
0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
2307
249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
2308
498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
2309
325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
2310
997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
2311
901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
2312
651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
2313
671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
2314
1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2315
2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
2316
1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
2317
1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
2318
1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
2319
1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
2320
1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
2321
1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
2322
3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
2323
3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
2324
4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
2325
4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
2326
3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
2327
3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
2328
3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
2329
3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2330
2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2331
2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2332
2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2333
2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2334
2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2335
2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
2336
3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
2337
3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
2340
/*Return the CRC of the bytes buf[0..len-1].*/
2341
unsigned lodepng_crc32(const unsigned char* buf, size_t len)
2343
unsigned c = 0xffffffffL;
2346
for(n = 0; n < len; ++n)
2348
c = lodepng_crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
2350
return c ^ 0xffffffffL;
2353
/* ////////////////////////////////////////////////////////////////////////// */
2354
/* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2355
/* ////////////////////////////////////////////////////////////////////////// */
2357
static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
2359
unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2364
static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
2366
unsigned result = 0;
2368
for(i = nbits - 1; i < nbits; --i)
2370
result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
2375
#ifdef LODEPNG_COMPILE_DECODER
2376
static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2378
/*the current bit in bitstream must be 0 for this to work*/
2381
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2382
bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
2386
#endif /*LODEPNG_COMPILE_DECODER*/
2388
static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2390
/*the current bit in bitstream may be 0 or 1 for this to work*/
2391
if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
2392
else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
2396
/* ////////////////////////////////////////////////////////////////////////// */
2397
/* / PNG chunks / */
2398
/* ////////////////////////////////////////////////////////////////////////// */
2400
unsigned lodepng_chunk_length(const unsigned char* chunk)
2402
return lodepng_read32bitInt(&chunk[0]);
2405
void lodepng_chunk_type(char type[5], const unsigned char* chunk)
2408
for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
2409
type[4] = 0; /*null termination char*/
2412
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
2414
if(strlen(type) != 4) return 0;
2415
return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2418
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
2420
return((chunk[4] & 32) != 0);
2423
unsigned char lodepng_chunk_private(const unsigned char* chunk)
2425
return((chunk[6] & 32) != 0);
2428
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
2430
return((chunk[7] & 32) != 0);
2433
unsigned char* lodepng_chunk_data(unsigned char* chunk)
2438
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
2443
unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
2445
unsigned length = lodepng_chunk_length(chunk);
2446
unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
2447
/*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2448
unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2449
if(CRC != checksum) return 1;
2453
void lodepng_chunk_generate_crc(unsigned char* chunk)
2455
unsigned length = lodepng_chunk_length(chunk);
2456
unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
2457
lodepng_set32bitInt(chunk + 8 + length, CRC);
2460
unsigned char* lodepng_chunk_next(unsigned char* chunk)
2462
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2463
return &chunk[total_chunk_length];
2466
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
2468
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2469
return &chunk[total_chunk_length];
2472
unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
2475
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2476
unsigned char *chunk_start, *new_buffer;
2477
size_t new_length = (*outlength) + total_chunk_length;
2478
if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
2480
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2481
if(!new_buffer) return 83; /*alloc fail*/
2482
(*out) = new_buffer;
2483
(*outlength) = new_length;
2484
chunk_start = &(*out)[new_length - total_chunk_length];
2486
for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
2491
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
2492
const char* type, const unsigned char* data)
2495
unsigned char *chunk, *new_buffer;
2496
size_t new_length = (*outlength) + length + 12;
2497
if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
2498
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2499
if(!new_buffer) return 83; /*alloc fail*/
2500
(*out) = new_buffer;
2501
(*outlength) = new_length;
2502
chunk = &(*out)[(*outlength) - length - 12];
2505
lodepng_set32bitInt(chunk, (unsigned)length);
2507
/*2: chunk name (4 letters)*/
2508
chunk[4] = (unsigned char)type[0];
2509
chunk[5] = (unsigned char)type[1];
2510
chunk[6] = (unsigned char)type[2];
2511
chunk[7] = (unsigned char)type[3];
2514
for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
2516
/*4: CRC (of the chunkname characters and the data)*/
2517
lodepng_chunk_generate_crc(chunk);
2522
/* ////////////////////////////////////////////////////////////////////////// */
2523
/* / Color types and such / */
2524
/* ////////////////////////////////////////////////////////////////////////// */
2526
/*return type is a LodePNG error code*/
2527
static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
2531
case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
2532
case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
2533
case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
2534
case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
2535
case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
2538
return 0; /*allowed color type / bits combination*/
2541
static unsigned getNumColorChannels(LodePNGColorType colortype)
2545
case 0: return 1; /*grey*/
2546
case 2: return 3; /*RGB*/
2547
case 3: return 1; /*palette*/
2548
case 4: return 2; /*grey + alpha*/
2549
case 6: return 4; /*RGBA*/
2551
return 0; /*unexisting color type*/
2554
static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
2556
/*bits per pixel is amount of channels * bits per channel*/
2557
return getNumColorChannels(colortype) * bitdepth;
2560
/* ////////////////////////////////////////////////////////////////////////// */
2562
void lodepng_color_mode_init(LodePNGColorMode* info)
2564
info->key_defined = 0;
2565
info->key_r = info->key_g = info->key_b = 0;
2566
info->colortype = LCT_RGBA;
2569
info->palettesize = 0;
2572
void lodepng_color_mode_cleanup(LodePNGColorMode* info)
2574
lodepng_palette_clear(info);
2577
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
2580
lodepng_color_mode_cleanup(dest);
2584
dest->palette = (unsigned char*)lodepng_malloc(1024);
2585
if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2586
for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
2591
static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
2594
if(a->colortype != b->colortype) return 0;
2595
if(a->bitdepth != b->bitdepth) return 0;
2596
if(a->key_defined != b->key_defined) return 0;
2599
if(a->key_r != b->key_r) return 0;
2600
if(a->key_g != b->key_g) return 0;
2601
if(a->key_b != b->key_b) return 0;
2603
if(a->palettesize != b->palettesize) return 0;
2604
for(i = 0; i != a->palettesize * 4; ++i)
2606
if(a->palette[i] != b->palette[i]) return 0;
2611
void lodepng_palette_clear(LodePNGColorMode* info)
2613
if(info->palette) lodepng_free(info->palette);
2615
info->palettesize = 0;
2618
unsigned lodepng_palette_add(LodePNGColorMode* info,
2619
unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2621
unsigned char* data;
2622
/*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2623
the max of 256 colors, it'll have the exact alloc size*/
2624
if(!info->palette) /*allocate palette if empty*/
2626
/*room for 256 colors with 4 bytes each*/
2627
data = (unsigned char*)lodepng_realloc(info->palette, 1024);
2628
if(!data) return 83; /*alloc fail*/
2629
else info->palette = data;
2631
info->palette[4 * info->palettesize + 0] = r;
2632
info->palette[4 * info->palettesize + 1] = g;
2633
info->palette[4 * info->palettesize + 2] = b;
2634
info->palette[4 * info->palettesize + 3] = a;
2635
++info->palettesize;
2639
unsigned lodepng_get_bpp(const LodePNGColorMode* info)
2641
/*calculate bits per pixel out of colortype and bitdepth*/
2642
return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
2645
unsigned lodepng_get_channels(const LodePNGColorMode* info)
2647
return getNumColorChannels(info->colortype);
2650
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
2652
return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
2655
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
2657
return (info->colortype & 4) != 0; /*4 or 6*/
2660
unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
2662
return info->colortype == LCT_PALETTE;
2665
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
2668
for(i = 0; i != info->palettesize; ++i)
2670
if(info->palette[i * 4 + 3] < 255) return 1;
2675
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
2677
return info->key_defined
2678
|| lodepng_is_alpha_type(info)
2679
|| lodepng_has_palette_alpha(info);
2682
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
2684
return (w * h * lodepng_get_bpp(color) + 7) / 8;
2687
size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
2689
return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8;
2693
#ifdef LODEPNG_COMPILE_PNG
2694
#ifdef LODEPNG_COMPILE_DECODER
2695
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
2696
static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color)
2698
return h * ((w * lodepng_get_bpp(color) + 7) / 8);
2700
#endif /*LODEPNG_COMPILE_DECODER*/
2701
#endif /*LODEPNG_COMPILE_PNG*/
2703
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2705
static void LodePNGUnknownChunks_init(LodePNGInfo* info)
2708
for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
2709
for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
2712
static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
2715
for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
2718
static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
2722
LodePNGUnknownChunks_cleanup(dest);
2724
for(i = 0; i != 3; ++i)
2727
dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
2728
dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
2729
if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
2730
for(j = 0; j < src->unknown_chunks_size[i]; ++j)
2732
dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
2739
/******************************************************************************/
2741
static void LodePNGText_init(LodePNGInfo* info)
2744
info->text_keys = NULL;
2745
info->text_strings = NULL;
2748
static void LodePNGText_cleanup(LodePNGInfo* info)
2751
for(i = 0; i != info->text_num; ++i)
2753
string_cleanup(&info->text_keys[i]);
2754
string_cleanup(&info->text_strings[i]);
2756
lodepng_free(info->text_keys);
2757
lodepng_free(info->text_strings);
2760
static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2763
dest->text_keys = 0;
2764
dest->text_strings = 0;
2766
for(i = 0; i != source->text_num; ++i)
2768
CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
2773
void lodepng_clear_text(LodePNGInfo* info)
2775
LodePNGText_cleanup(info);
2778
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
2780
char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
2781
char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
2782
if(!new_keys || !new_strings)
2784
lodepng_free(new_keys);
2785
lodepng_free(new_strings);
2786
return 83; /*alloc fail*/
2790
info->text_keys = new_keys;
2791
info->text_strings = new_strings;
2793
string_init(&info->text_keys[info->text_num - 1]);
2794
string_set(&info->text_keys[info->text_num - 1], key);
2796
string_init(&info->text_strings[info->text_num - 1]);
2797
string_set(&info->text_strings[info->text_num - 1], str);
2802
/******************************************************************************/
2804
static void LodePNGIText_init(LodePNGInfo* info)
2806
info->itext_num = 0;
2807
info->itext_keys = NULL;
2808
info->itext_langtags = NULL;
2809
info->itext_transkeys = NULL;
2810
info->itext_strings = NULL;
2813
static void LodePNGIText_cleanup(LodePNGInfo* info)
2816
for(i = 0; i != info->itext_num; ++i)
2818
string_cleanup(&info->itext_keys[i]);
2819
string_cleanup(&info->itext_langtags[i]);
2820
string_cleanup(&info->itext_transkeys[i]);
2821
string_cleanup(&info->itext_strings[i]);
2823
lodepng_free(info->itext_keys);
2824
lodepng_free(info->itext_langtags);
2825
lodepng_free(info->itext_transkeys);
2826
lodepng_free(info->itext_strings);
2829
static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2832
dest->itext_keys = 0;
2833
dest->itext_langtags = 0;
2834
dest->itext_transkeys = 0;
2835
dest->itext_strings = 0;
2836
dest->itext_num = 0;
2837
for(i = 0; i != source->itext_num; ++i)
2839
CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
2840
source->itext_transkeys[i], source->itext_strings[i]));
2845
void lodepng_clear_itext(LodePNGInfo* info)
2847
LodePNGIText_cleanup(info);
2850
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
2851
const char* transkey, const char* str)
2853
char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
2854
char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
2855
char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
2856
char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
2857
if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
2859
lodepng_free(new_keys);
2860
lodepng_free(new_langtags);
2861
lodepng_free(new_transkeys);
2862
lodepng_free(new_strings);
2863
return 83; /*alloc fail*/
2867
info->itext_keys = new_keys;
2868
info->itext_langtags = new_langtags;
2869
info->itext_transkeys = new_transkeys;
2870
info->itext_strings = new_strings;
2872
string_init(&info->itext_keys[info->itext_num - 1]);
2873
string_set(&info->itext_keys[info->itext_num - 1], key);
2875
string_init(&info->itext_langtags[info->itext_num - 1]);
2876
string_set(&info->itext_langtags[info->itext_num - 1], langtag);
2878
string_init(&info->itext_transkeys[info->itext_num - 1]);
2879
string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
2881
string_init(&info->itext_strings[info->itext_num - 1]);
2882
string_set(&info->itext_strings[info->itext_num - 1], str);
2886
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2888
void lodepng_info_init(LodePNGInfo* info)
2890
lodepng_color_mode_init(&info->color);
2891
info->interlace_method = 0;
2892
info->compression_method = 0;
2893
info->filter_method = 0;
2894
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2895
info->background_defined = 0;
2896
info->background_r = info->background_g = info->background_b = 0;
2898
LodePNGText_init(info);
2899
LodePNGIText_init(info);
2901
info->time_defined = 0;
2902
info->phys_defined = 0;
2904
LodePNGUnknownChunks_init(info);
2905
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2908
void lodepng_info_cleanup(LodePNGInfo* info)
2910
lodepng_color_mode_cleanup(&info->color);
2911
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2912
LodePNGText_cleanup(info);
2913
LodePNGIText_cleanup(info);
2915
LodePNGUnknownChunks_cleanup(info);
2916
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2919
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2921
lodepng_info_cleanup(dest);
2923
lodepng_color_mode_init(&dest->color);
2924
CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
2926
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2927
CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
2928
CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
2930
LodePNGUnknownChunks_init(dest);
2931
CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
2932
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2936
void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
2938
LodePNGInfo temp = *a;
2943
/* ////////////////////////////////////////////////////////////////////////// */
2945
/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
2946
static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
2948
unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
2949
/*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2950
unsigned p = index & m;
2951
in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
2952
in = in << (bits * (m - p));
2953
if(p == 0) out[index * bits / 8] = in;
2954
else out[index * bits / 8] |= in;
2957
typedef struct ColorTree ColorTree;
2960
One node of a color tree
2961
This is the data structure used to count the number of unique colors and to get a palette
2962
index for a color. It's like an octree, but because the alpha channel is used too, each
2963
node has 16 instead of 8 children.
2967
ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
2968
int index; /*the payload. Only has a meaningful value if this is in the last level*/
2971
static void color_tree_init(ColorTree* tree)
2974
for(i = 0; i != 16; ++i) tree->children[i] = 0;
2978
static void color_tree_cleanup(ColorTree* tree)
2981
for(i = 0; i != 16; ++i)
2983
if(tree->children[i])
2985
color_tree_cleanup(tree->children[i]);
2986
lodepng_free(tree->children[i]);
2991
/*returns -1 if color not present, its index otherwise*/
2992
static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2995
for(bit = 0; bit < 8; ++bit)
2997
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
2998
if(!tree->children[i]) return -1;
2999
else tree = tree->children[i];
3001
return tree ? tree->index : -1;
3004
#ifdef LODEPNG_COMPILE_ENCODER
3005
static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3007
return color_tree_get(tree, r, g, b, a) >= 0;
3009
#endif /*LODEPNG_COMPILE_ENCODER*/
3011
/*color is not allowed to already exist.
3012
Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
3013
static void color_tree_add(ColorTree* tree,
3014
unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
3017
for(bit = 0; bit < 8; ++bit)
3019
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3020
if(!tree->children[i])
3022
tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
3023
color_tree_init(tree->children[i]);
3025
tree = tree->children[i];
3027
tree->index = (int)index;
3030
/*put a pixel, given its RGBA color, into image of any color type*/
3031
static unsigned rgba8ToPixel(unsigned char* out, size_t i,
3032
const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
3033
unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3035
if(mode->colortype == LCT_GREY)
3037
unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3038
if(mode->bitdepth == 8) out[i] = grey;
3039
else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
3042
/*take the most significant bits of grey*/
3043
grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
3044
addColorBits(out, i, mode->bitdepth, grey);
3047
else if(mode->colortype == LCT_RGB)
3049
if(mode->bitdepth == 8)
3057
out[i * 6 + 0] = out[i * 6 + 1] = r;
3058
out[i * 6 + 2] = out[i * 6 + 3] = g;
3059
out[i * 6 + 4] = out[i * 6 + 5] = b;
3062
else if(mode->colortype == LCT_PALETTE)
3064
int index = color_tree_get(tree, r, g, b, a);
3065
if(index < 0) return 82; /*color not in palette*/
3066
if(mode->bitdepth == 8) out[i] = index;
3067
else addColorBits(out, i, mode->bitdepth, (unsigned)index);
3069
else if(mode->colortype == LCT_GREY_ALPHA)
3071
unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3072
if(mode->bitdepth == 8)
3074
out[i * 2 + 0] = grey;
3077
else if(mode->bitdepth == 16)
3079
out[i * 4 + 0] = out[i * 4 + 1] = grey;
3080
out[i * 4 + 2] = out[i * 4 + 3] = a;
3083
else if(mode->colortype == LCT_RGBA)
3085
if(mode->bitdepth == 8)
3094
out[i * 8 + 0] = out[i * 8 + 1] = r;
3095
out[i * 8 + 2] = out[i * 8 + 3] = g;
3096
out[i * 8 + 4] = out[i * 8 + 5] = b;
3097
out[i * 8 + 6] = out[i * 8 + 7] = a;
3101
return 0; /*no error*/
3104
/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3105
static void rgba16ToPixel(unsigned char* out, size_t i,
3106
const LodePNGColorMode* mode,
3107
unsigned short r, unsigned short g, unsigned short b, unsigned short a)
3109
if(mode->colortype == LCT_GREY)
3111
unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3112
out[i * 2 + 0] = (grey >> 8) & 255;
3113
out[i * 2 + 1] = grey & 255;
3115
else if(mode->colortype == LCT_RGB)
3117
out[i * 6 + 0] = (r >> 8) & 255;
3118
out[i * 6 + 1] = r & 255;
3119
out[i * 6 + 2] = (g >> 8) & 255;
3120
out[i * 6 + 3] = g & 255;
3121
out[i * 6 + 4] = (b >> 8) & 255;
3122
out[i * 6 + 5] = b & 255;
3124
else if(mode->colortype == LCT_GREY_ALPHA)
3126
unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3127
out[i * 4 + 0] = (grey >> 8) & 255;
3128
out[i * 4 + 1] = grey & 255;
3129
out[i * 4 + 2] = (a >> 8) & 255;
3130
out[i * 4 + 3] = a & 255;
3132
else if(mode->colortype == LCT_RGBA)
3134
out[i * 8 + 0] = (r >> 8) & 255;
3135
out[i * 8 + 1] = r & 255;
3136
out[i * 8 + 2] = (g >> 8) & 255;
3137
out[i * 8 + 3] = g & 255;
3138
out[i * 8 + 4] = (b >> 8) & 255;
3139
out[i * 8 + 5] = b & 255;
3140
out[i * 8 + 6] = (a >> 8) & 255;
3141
out[i * 8 + 7] = a & 255;
3145
/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3146
static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
3147
unsigned char* b, unsigned char* a,
3148
const unsigned char* in, size_t i,
3149
const LodePNGColorMode* mode)
3151
if(mode->colortype == LCT_GREY)
3153
if(mode->bitdepth == 8)
3155
*r = *g = *b = in[i];
3156
if(mode->key_defined && *r == mode->key_r) *a = 0;
3159
else if(mode->bitdepth == 16)
3161
*r = *g = *b = in[i * 2 + 0];
3162
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3167
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3168
size_t j = i * mode->bitdepth;
3169
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3170
*r = *g = *b = (value * 255) / highest;
3171
if(mode->key_defined && value == mode->key_r) *a = 0;
3175
else if(mode->colortype == LCT_RGB)
3177
if(mode->bitdepth == 8)
3179
*r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3180
if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3188
if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3189
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3190
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3194
else if(mode->colortype == LCT_PALETTE)
3197
if(mode->bitdepth == 8) index = in[i];
3200
size_t j = i * mode->bitdepth;
3201
index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3204
if(index >= mode->palettesize)
3206
/*This is an error according to the PNG spec, but common PNG decoders make it black instead.
3207
Done here too, slightly faster due to no error handling needed.*/
3213
*r = mode->palette[index * 4 + 0];
3214
*g = mode->palette[index * 4 + 1];
3215
*b = mode->palette[index * 4 + 2];
3216
*a = mode->palette[index * 4 + 3];
3219
else if(mode->colortype == LCT_GREY_ALPHA)
3221
if(mode->bitdepth == 8)
3223
*r = *g = *b = in[i * 2 + 0];
3228
*r = *g = *b = in[i * 4 + 0];
3232
else if(mode->colortype == LCT_RGBA)
3234
if(mode->bitdepth == 8)
3251
/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3252
mode test cases, optimized to convert the colors much faster, when converting
3253
to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3254
enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3255
of the input buffer.*/
3256
static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
3257
unsigned has_alpha, const unsigned char* in,
3258
const LodePNGColorMode* mode)
3260
unsigned num_channels = has_alpha ? 4 : 3;
3262
if(mode->colortype == LCT_GREY)
3264
if(mode->bitdepth == 8)
3266
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3268
buffer[0] = buffer[1] = buffer[2] = in[i];
3269
if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
3272
else if(mode->bitdepth == 16)
3274
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3276
buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3277
if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
3282
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3284
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3286
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3287
buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3288
if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
3292
else if(mode->colortype == LCT_RGB)
3294
if(mode->bitdepth == 8)
3296
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3298
buffer[0] = in[i * 3 + 0];
3299
buffer[1] = in[i * 3 + 1];
3300
buffer[2] = in[i * 3 + 2];
3301
if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
3302
&& buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
3307
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3309
buffer[0] = in[i * 6 + 0];
3310
buffer[1] = in[i * 6 + 2];
3311
buffer[2] = in[i * 6 + 4];
3312
if(has_alpha) buffer[3] = mode->key_defined
3313
&& 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3314
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3315
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
3319
else if(mode->colortype == LCT_PALETTE)
3323
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3325
if(mode->bitdepth == 8) index = in[i];
3326
else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3328
if(index >= mode->palettesize)
3330
/*This is an error according to the PNG spec, but most PNG decoders make it black instead.
3331
Done here too, slightly faster due to no error handling needed.*/
3332
buffer[0] = buffer[1] = buffer[2] = 0;
3333
if(has_alpha) buffer[3] = 255;
3337
buffer[0] = mode->palette[index * 4 + 0];
3338
buffer[1] = mode->palette[index * 4 + 1];
3339
buffer[2] = mode->palette[index * 4 + 2];
3340
if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
3344
else if(mode->colortype == LCT_GREY_ALPHA)
3346
if(mode->bitdepth == 8)
3348
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3350
buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3351
if(has_alpha) buffer[3] = in[i * 2 + 1];
3356
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3358
buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3359
if(has_alpha) buffer[3] = in[i * 4 + 2];
3363
else if(mode->colortype == LCT_RGBA)
3365
if(mode->bitdepth == 8)
3367
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3369
buffer[0] = in[i * 4 + 0];
3370
buffer[1] = in[i * 4 + 1];
3371
buffer[2] = in[i * 4 + 2];
3372
if(has_alpha) buffer[3] = in[i * 4 + 3];
3377
for(i = 0; i != numpixels; ++i, buffer += num_channels)
3379
buffer[0] = in[i * 8 + 0];
3380
buffer[1] = in[i * 8 + 2];
3381
buffer[2] = in[i * 8 + 4];
3382
if(has_alpha) buffer[3] = in[i * 8 + 6];
3388
/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3389
given color type, but the given color type must be 16-bit itself.*/
3390
static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3391
const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3393
if(mode->colortype == LCT_GREY)
3395
*r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3396
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3399
else if(mode->colortype == LCT_RGB)
3401
*r = 256 * in[i * 6 + 0] + in[i * 6 + 1];
3402
*g = 256 * in[i * 6 + 2] + in[i * 6 + 3];
3403
*b = 256 * in[i * 6 + 4] + in[i * 6 + 5];
3404
if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3405
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3406
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3409
else if(mode->colortype == LCT_GREY_ALPHA)
3411
*r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1];
3412
*a = 256 * in[i * 4 + 2] + in[i * 4 + 3];
3414
else if(mode->colortype == LCT_RGBA)
3416
*r = 256 * in[i * 8 + 0] + in[i * 8 + 1];
3417
*g = 256 * in[i * 8 + 2] + in[i * 8 + 3];
3418
*b = 256 * in[i * 8 + 4] + in[i * 8 + 5];
3419
*a = 256 * in[i * 8 + 6] + in[i * 8 + 7];
3423
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3424
LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
3425
unsigned w, unsigned h)
3429
size_t numpixels = w * h;
3431
if(lodepng_color_mode_equal(mode_out, mode_in))
3433
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3434
for(i = 0; i != numbytes; ++i) out[i] = in[i];
3438
if(mode_out->colortype == LCT_PALETTE)
3440
size_t palsize = 1u << mode_out->bitdepth;
3441
if(mode_out->palettesize < palsize) palsize = mode_out->palettesize;
3442
color_tree_init(&tree);
3443
for(i = 0; i != palsize; ++i)
3445
unsigned char* p = &mode_out->palette[i * 4];
3446
color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
3450
if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
3452
for(i = 0; i != numpixels; ++i)
3454
unsigned short r = 0, g = 0, b = 0, a = 0;
3455
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3456
rgba16ToPixel(out, i, mode_out, r, g, b, a);
3459
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
3461
getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
3463
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
3465
getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
3469
unsigned char r = 0, g = 0, b = 0, a = 0;
3470
for(i = 0; i != numpixels; ++i)
3472
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3473
rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
3477
if(mode_out->colortype == LCT_PALETTE)
3479
color_tree_cleanup(&tree);
3482
return 0; /*no error (this function currently never has one, but maybe OOM detection added later.)*/
3485
#ifdef LODEPNG_COMPILE_ENCODER
3487
void lodepng_color_profile_init(LodePNGColorProfile* profile)
3489
profile->colored = 0;
3492
profile->key_r = profile->key_g = profile->key_b = 0;
3493
profile->numcolors = 0;
3497
/*function used for debug purposes with C++*/
3498
/*void printColorProfile(LodePNGColorProfile* p)
3500
std::cout << "colored: " << (int)p->colored << ", ";
3501
std::cout << "key: " << (int)p->key << ", ";
3502
std::cout << "key_r: " << (int)p->key_r << ", ";
3503
std::cout << "key_g: " << (int)p->key_g << ", ";
3504
std::cout << "key_b: " << (int)p->key_b << ", ";
3505
std::cout << "alpha: " << (int)p->alpha << ", ";
3506
std::cout << "numcolors: " << (int)p->numcolors << ", ";
3507
std::cout << "bits: " << (int)p->bits << std::endl;
3510
/*Returns how many bits needed to represent given value (max 8 bit)*/
3511
static unsigned getValueRequiredBits(unsigned char value)
3513
if(value == 0 || value == 255) return 1;
3514
/*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3515
if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
3519
/*profile must already have been inited with mode.
3520
It's ok to set some parameters of profile to done already.*/
3521
unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
3522
const unsigned char* in, unsigned w, unsigned h,
3523
const LodePNGColorMode* mode)
3528
size_t numpixels = w * h;
3530
unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
3531
unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
3532
unsigned numcolors_done = 0;
3533
unsigned bpp = lodepng_get_bpp(mode);
3534
unsigned bits_done = bpp == 1 ? 1 : 0;
3535
unsigned maxnumcolors = 257;
3536
unsigned sixteen = 0;
3537
if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
3539
color_tree_init(&tree);
3541
/*Check if the 16-bit input is truly 16-bit*/
3542
if(mode->bitdepth == 16)
3544
unsigned short r, g, b, a;
3545
for(i = 0; i != numpixels; ++i)
3547
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3548
if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
3549
(b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/
3559
unsigned short r = 0, g = 0, b = 0, a = 0;
3561
bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3563
for(i = 0; i != numpixels; ++i)
3565
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3567
if(!colored_done && (r != g || r != b))
3569
profile->colored = 1;
3575
unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3576
if(a != 65535 && (a != 0 || (profile->key && !matchkey)))
3580
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3582
else if(a == 0 && !profile->alpha && !profile->key)
3589
else if(a == 65535 && profile->key && matchkey)
3591
/* Color key cannot be used if an opaque pixel also has that RGB color. */
3597
if(alpha_done && numcolors_done && colored_done && bits_done) break;
3602
for(i = 0; i != numpixels; ++i)
3604
unsigned char r = 0, g = 0, b = 0, a = 0;
3605
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
3607
if(!bits_done && profile->bits < 8)
3609
/*only r is checked, < 8 bits is only relevant for greyscale*/
3610
unsigned bits = getValueRequiredBits(r);
3611
if(bits > profile->bits) profile->bits = bits;
3613
bits_done = (profile->bits >= bpp);
3615
if(!colored_done && (r != g || r != b))
3617
profile->colored = 1;
3619
if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
3624
unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
3625
if(a != 255 && (a != 0 || (profile->key && !matchkey)))
3629
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3631
else if(a == 0 && !profile->alpha && !profile->key)
3638
else if(a == 255 && profile->key && matchkey)
3640
/* Color key cannot be used if an opaque pixel also has that RGB color. */
3643
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3649
if(!color_tree_has(&tree, r, g, b, a))
3651
color_tree_add(&tree, r, g, b, a, profile->numcolors);
3652
if(profile->numcolors < 256)
3654
unsigned char* p = profile->palette;
3655
unsigned n = profile->numcolors;
3661
++profile->numcolors;
3662
numcolors_done = profile->numcolors >= maxnumcolors;
3666
if(alpha_done && numcolors_done && colored_done && bits_done) break;
3669
/*make the profile's key always 16-bit for consistency - repeat each byte twice*/
3670
profile->key_r += (profile->key_r << 8);
3671
profile->key_g += (profile->key_g << 8);
3672
profile->key_b += (profile->key_b << 8);
3675
color_tree_cleanup(&tree);
3679
/*Automatically chooses color type that gives smallest amount of bits in the
3680
output image, e.g. grey if there are only greyscale pixels, palette if there
3681
are less than 256 colors, ...
3682
Updates values of mode with a potentially smaller color model. mode_out should
3683
contain the user chosen color model, but will be overwritten with the new chosen one.*/
3684
unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
3685
const unsigned char* image, unsigned w, unsigned h,
3686
const LodePNGColorMode* mode_in)
3688
LodePNGColorProfile prof;
3690
unsigned i, n, palettebits, grey_ok, palette_ok;
3692
lodepng_color_profile_init(&prof);
3693
error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
3694
if(error) return error;
3695
mode_out->key_defined = 0;
3697
if(prof.key && w * h <= 16)
3699
prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
3700
if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
3702
grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/
3704
palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
3705
palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;
3706
if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
3707
if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/
3711
unsigned char* p = prof.palette;
3712
lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
3713
for(i = 0; i != prof.numcolors; ++i)
3715
error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
3719
mode_out->colortype = LCT_PALETTE;
3720
mode_out->bitdepth = palettebits;
3722
if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
3723
&& mode_in->bitdepth == mode_out->bitdepth)
3725
/*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
3726
lodepng_color_mode_cleanup(mode_out);
3727
lodepng_color_mode_copy(mode_out, mode_in);
3730
else /*8-bit or 16-bit per channel*/
3732
mode_out->bitdepth = prof.bits;
3733
mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA)
3734
: (prof.colored ? LCT_RGB : LCT_GREY);
3736
if(prof.key && !prof.alpha)
3738
unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/
3739
mode_out->key_r = prof.key_r & mask;
3740
mode_out->key_g = prof.key_g & mask;
3741
mode_out->key_b = prof.key_b & mask;
3742
mode_out->key_defined = 1;
3749
#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3752
Paeth predicter, used by PNG filter type 4
3753
The parameters are of type short, but should come from unsigned chars, the shorts
3754
are only needed to make the paeth calculation correct.
3756
static unsigned char paethPredictor(short a, short b, short c)
3758
short pa = abs(b - c);
3759
short pb = abs(a - c);
3760
short pc = abs(a + b - c - c);
3762
if(pc < pa && pc < pb) return (unsigned char)c;
3763
else if(pb < pa) return (unsigned char)b;
3764
else return (unsigned char)a;
3767
/*shared values used by multiple Adam7 related functions*/
3769
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3770
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3771
static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3772
static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3775
Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3776
passw: output containing the width of the 7 passes
3777
passh: output containing the height of the 7 passes
3778
filter_passstart: output containing the index of the start and end of each
3779
reduced image with filter bytes
3780
padded_passstart output containing the index of the start and end of each
3781
reduced image when without filter bytes but with padded scanlines
3782
passstart: output containing the index of the start and end of each reduced
3783
image without padding between scanlines, but still padding between the images
3784
w, h: width and height of non-interlaced image
3786
"padded" is only relevant if bpp is less than 8 and a scanline or image does not
3789
static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
3790
size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
3792
/*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3795
/*calculate width and height in pixels of each pass*/
3796
for(i = 0; i != 7; ++i)
3798
passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
3799
passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
3800
if(passw[i] == 0) passh[i] = 0;
3801
if(passh[i] == 0) passw[i] = 0;
3804
filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
3805
for(i = 0; i != 7; ++i)
3807
/*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3808
filter_passstart[i + 1] = filter_passstart[i]
3809
+ ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
3810
/*bits padded if needed to fill full byte at end of each scanline*/
3811
padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
3812
/*only padded at end of reduced image*/
3813
passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
3817
#ifdef LODEPNG_COMPILE_DECODER
3819
/* ////////////////////////////////////////////////////////////////////////// */
3820
/* / PNG Decoder / */
3821
/* ////////////////////////////////////////////////////////////////////////// */
3823
/*read the information from the header and store it in the LodePNGInfo. return value is error*/
3824
unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
3825
const unsigned char* in, size_t insize)
3827
LodePNGInfo* info = &state->info_png;
3828
if(insize == 0 || in == 0)
3830
CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
3834
CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
3837
/*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3838
lodepng_info_cleanup(info);
3839
lodepng_info_init(info);
3841
if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
3842
|| in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
3844
CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3846
if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R')
3848
CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
3851
/*read the values given in the header*/
3852
*w = lodepng_read32bitInt(&in[16]);
3853
*h = lodepng_read32bitInt(&in[20]);
3854
info->color.bitdepth = in[24];
3855
info->color.colortype = (LodePNGColorType)in[25];
3856
info->compression_method = in[26];
3857
info->filter_method = in[27];
3858
info->interlace_method = in[28];
3860
if(*w == 0 || *h == 0)
3862
CERROR_RETURN_ERROR(state->error, 93);
3865
if(!state->decoder.ignore_crc)
3867
unsigned CRC = lodepng_read32bitInt(&in[29]);
3868
unsigned checksum = lodepng_crc32(&in[12], 17);
3871
CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
3875
/*error: only compression method 0 is allowed in the specification*/
3876
if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
3877
/*error: only filter method 0 is allowed in the specification*/
3878
if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
3879
/*error: only interlace methods 0 and 1 exist in the specification*/
3880
if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
3882
state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
3883
return state->error;
3886
static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
3887
size_t bytewidth, unsigned char filterType, size_t length)
3890
For PNG filter method 0
3891
unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
3892
the filter works byte per byte (bytewidth = 1)
3893
precon is the previous unfiltered scanline, recon the result, scanline the current one
3894
the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
3895
recon and scanline MAY be the same memory address! precon must be disjoint.
3902
for(i = 0; i != length; ++i) recon[i] = scanline[i];
3905
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3906
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
3911
for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
3915
for(i = 0; i != length; ++i) recon[i] = scanline[i];
3921
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + precon[i] / 2;
3922
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
3926
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
3927
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth] / 2;
3933
for(i = 0; i != bytewidth; ++i)
3935
recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
3937
for(i = bytewidth; i < length; ++i)
3939
recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
3944
for(i = 0; i != bytewidth; ++i)
3946
recon[i] = scanline[i];
3948
for(i = bytewidth; i < length; ++i)
3950
/*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
3951
recon[i] = (scanline[i] + recon[i - bytewidth]);
3955
default: return 36; /*error: unexisting filter type given*/
3960
static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
3963
For PNG filter method 0
3964
this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
3965
out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
3966
w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
3967
in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
3971
unsigned char* prevline = 0;
3973
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
3974
size_t bytewidth = (bpp + 7) / 8;
3975
size_t linebytes = (w * bpp + 7) / 8;
3977
for(y = 0; y < h; ++y)
3979
size_t outindex = linebytes * y;
3980
size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
3981
unsigned char filterType = in[inindex];
3983
CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
3985
prevline = &out[outindex];
3992
in: Adam7 interlaced image, with no padding bits between scanlines, but between
3993
reduced images so that each reduced image starts at a byte.
3994
out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
3996
out has the following size in bits: w * h * bpp.
3997
in is possibly bigger due to padding bits between reduced images.
3998
out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
3999
(because that's likely a little bit faster)
4000
NOTE: comments about padding bits are only relevant if bpp < 8
4002
static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4004
unsigned passw[7], passh[7];
4005
size_t filter_passstart[8], padded_passstart[8], passstart[8];
4008
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4012
for(i = 0; i != 7; ++i)
4015
size_t bytewidth = bpp / 8;
4016
for(y = 0; y < passh[i]; ++y)
4017
for(x = 0; x < passw[i]; ++x)
4019
size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4020
size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
4021
for(b = 0; b < bytewidth; ++b)
4023
out[pixeloutstart + b] = in[pixelinstart + b];
4028
else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4030
for(i = 0; i != 7; ++i)
4033
unsigned ilinebits = bpp * passw[i];
4034
unsigned olinebits = bpp * w;
4035
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4036
for(y = 0; y < passh[i]; ++y)
4037
for(x = 0; x < passw[i]; ++x)
4039
ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4040
obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
4041
for(b = 0; b < bpp; ++b)
4043
unsigned char bit = readBitFromReversedStream(&ibp, in);
4044
/*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4045
setBitOfReversedStream0(&obp, out, bit);
4052
static void removePaddingBits(unsigned char* out, const unsigned char* in,
4053
size_t olinebits, size_t ilinebits, unsigned h)
4056
After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4057
to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4058
for the Adam7 code, the color convert code and the output to the user.
4059
in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4060
have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4061
also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4062
only useful if (ilinebits - olinebits) is a value in the range 1..7
4065
size_t diff = ilinebits - olinebits;
4066
size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4067
for(y = 0; y < h; ++y)
4070
for(x = 0; x < olinebits; ++x)
4072
unsigned char bit = readBitFromReversedStream(&ibp, in);
4073
setBitOfReversedStream(&obp, out, bit);
4079
/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4080
the IDAT chunks (with filter index bytes and possible padding bits)
4081
return value is error*/
4082
static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4083
unsigned w, unsigned h, const LodePNGInfo* info_png)
4086
This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4088
*) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4089
*) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4090
NOTE: the in buffer will be overwritten with intermediate data!
4092
unsigned bpp = lodepng_get_bpp(&info_png->color);
4093
if(bpp == 0) return 31; /*error: invalid colortype*/
4095
if(info_png->interlace_method == 0)
4097
if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
4099
CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4100
removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
4102
/*we can immediatly filter into the out buffer, no other steps needed*/
4103
else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4105
else /*interlace_method is 1 (Adam7)*/
4107
unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4110
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4112
for(i = 0; i != 7; ++i)
4114
CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4115
/*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4116
move bytes instead of bits or move not at all*/
4119
/*remove padding bits in scanlines; after this there still may be padding
4120
bits between the different reduced images: each reduced image still starts nicely at a byte*/
4121
removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4122
((passw[i] * bpp + 7) / 8) * 8, passh[i]);
4126
Adam7_deinterlace(out, in, w, h, bpp);
4132
static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4134
unsigned pos = 0, i;
4135
if(color->palette) lodepng_free(color->palette);
4136
color->palettesize = chunkLength / 3;
4137
color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize);
4138
if(!color->palette && color->palettesize)
4140
color->palettesize = 0;
4141
return 83; /*alloc fail*/
4143
if(color->palettesize > 256) return 38; /*error: palette too big*/
4145
for(i = 0; i != color->palettesize; ++i)
4147
color->palette[4 * i + 0] = data[pos++]; /*R*/
4148
color->palette[4 * i + 1] = data[pos++]; /*G*/
4149
color->palette[4 * i + 2] = data[pos++]; /*B*/
4150
color->palette[4 * i + 3] = 255; /*alpha*/
4156
static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
4159
if(color->colortype == LCT_PALETTE)
4161
/*error: more alpha values given than there are palette entries*/
4162
if(chunkLength > color->palettesize) return 38;
4164
for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
4166
else if(color->colortype == LCT_GREY)
4168
/*error: this chunk must be 2 bytes for greyscale image*/
4169
if(chunkLength != 2) return 30;
4171
color->key_defined = 1;
4172
color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
4174
else if(color->colortype == LCT_RGB)
4176
/*error: this chunk must be 6 bytes for RGB image*/
4177
if(chunkLength != 6) return 41;
4179
color->key_defined = 1;
4180
color->key_r = 256u * data[0] + data[1];
4181
color->key_g = 256u * data[2] + data[3];
4182
color->key_b = 256u * data[4] + data[5];
4184
else return 42; /*error: tRNS chunk not allowed for other color models*/
4190
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4191
/*background color chunk (bKGD)*/
4192
static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4194
if(info->color.colortype == LCT_PALETTE)
4196
/*error: this chunk must be 1 byte for indexed color image*/
4197
if(chunkLength != 1) return 43;
4199
info->background_defined = 1;
4200
info->background_r = info->background_g = info->background_b = data[0];
4202
else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
4204
/*error: this chunk must be 2 bytes for greyscale image*/
4205
if(chunkLength != 2) return 44;
4207
info->background_defined = 1;
4208
info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
4210
else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
4212
/*error: this chunk must be 6 bytes for greyscale image*/
4213
if(chunkLength != 6) return 45;
4215
info->background_defined = 1;
4216
info->background_r = 256u * data[0] + data[1];
4217
info->background_g = 256u * data[2] + data[3];
4218
info->background_b = 256u * data[4] + data[5];
4224
/*text chunk (tEXt)*/
4225
static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4228
char *key = 0, *str = 0;
4231
while(!error) /*not really a while loop, only used to break on error*/
4233
unsigned length, string2_begin;
4236
while(length < chunkLength && data[length] != 0) ++length;
4237
/*even though it's not allowed by the standard, no error is thrown if
4238
there's no null termination char, if the text is empty*/
4239
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4241
key = (char*)lodepng_malloc(length + 1);
4242
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4245
for(i = 0; i != length; ++i) key[i] = (char)data[i];
4247
string2_begin = length + 1; /*skip keyword null terminator*/
4249
length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
4250
str = (char*)lodepng_malloc(length + 1);
4251
if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
4254
for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
4256
error = lodepng_add_text(info, key, str);
4267
/*compressed text chunk (zTXt)*/
4268
static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4269
const unsigned char* data, size_t chunkLength)
4274
unsigned length, string2_begin;
4278
ucvector_init(&decoded);
4280
while(!error) /*not really a while loop, only used to break on error*/
4282
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4283
if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4284
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4286
key = (char*)lodepng_malloc(length + 1);
4287
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4290
for(i = 0; i != length; ++i) key[i] = (char)data[i];
4292
if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4294
string2_begin = length + 2;
4295
if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4297
length = chunkLength - string2_begin;
4298
/*will fail if zlib error, e.g. if length is too small*/
4299
error = zlib_decompress(&decoded.data, &decoded.size,
4300
(unsigned char*)(&data[string2_begin]),
4301
length, zlibsettings);
4303
ucvector_push_back(&decoded, 0);
4305
error = lodepng_add_text(info, key, (char*)decoded.data);
4311
ucvector_cleanup(&decoded);
4316
/*international text chunk (iTXt)*/
4317
static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
4318
const unsigned char* data, size_t chunkLength)
4323
unsigned length, begin, compressed;
4324
char *key = 0, *langtag = 0, *transkey = 0;
4326
ucvector_init(&decoded);
4328
while(!error) /*not really a while loop, only used to break on error*/
4330
/*Quick check if the chunk length isn't too small. Even without check
4331
it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4332
if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
4335
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4336
if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
4337
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4339
key = (char*)lodepng_malloc(length + 1);
4340
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4343
for(i = 0; i != length; ++i) key[i] = (char)data[i];
4345
/*read the compression method*/
4346
compressed = data[length + 1];
4347
if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4349
/*even though it's not allowed by the standard, no error is thrown if
4350
there's no null termination char, if the text is empty for the next 3 texts*/
4352
/*read the langtag*/
4355
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4357
langtag = (char*)lodepng_malloc(length + 1);
4358
if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
4360
langtag[length] = 0;
4361
for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
4363
/*read the transkey*/
4364
begin += length + 1;
4366
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4368
transkey = (char*)lodepng_malloc(length + 1);
4369
if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
4371
transkey[length] = 0;
4372
for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
4374
/*read the actual text*/
4375
begin += length + 1;
4377
length = chunkLength < begin ? 0 : chunkLength - begin;
4381
/*will fail if zlib error, e.g. if length is too small*/
4382
error = zlib_decompress(&decoded.data, &decoded.size,
4383
(unsigned char*)(&data[begin]),
4384
length, zlibsettings);
4386
if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
4387
ucvector_push_back(&decoded, 0);
4391
if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
4393
decoded.data[length] = 0;
4394
for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
4397
error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
4403
lodepng_free(langtag);
4404
lodepng_free(transkey);
4405
ucvector_cleanup(&decoded);
4410
static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4412
if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
4414
info->time_defined = 1;
4415
info->time.year = 256u * data[0] + data[1];
4416
info->time.month = data[2];
4417
info->time.day = data[3];
4418
info->time.hour = data[4];
4419
info->time.minute = data[5];
4420
info->time.second = data[6];
4425
static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
4427
if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
4429
info->phys_defined = 1;
4430
info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
4431
info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
4432
info->phys_unit = data[8];
4436
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4438
/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4439
static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
4440
LodePNGState* state,
4441
const unsigned char* in, size_t insize)
4443
unsigned char IEND = 0;
4444
const unsigned char* chunk;
4446
ucvector idat; /*the data from idat chunks*/
4451
/*for unknown chunk order*/
4452
unsigned unknown = 0;
4453
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4454
unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4455
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4457
/*provide some proper output values if error will happen*/
4460
state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
4461
if(state->error) return;
4463
numpixels = *w * *h;
4465
/*multiplication overflow*/
4466
if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92);
4467
/*multiplication overflow possible further below. Allows up to 2^31-1 pixel
4468
bytes with 16-bit RGBA, the rest is room for filter bytes.*/
4469
if(numpixels > 268435455) CERROR_RETURN(state->error, 92);
4471
ucvector_init(&idat);
4472
chunk = &in[33]; /*first byte of the first chunk after the header*/
4474
/*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4475
IDAT data is put at the start of the in buffer*/
4476
while(!IEND && !state->error)
4478
unsigned chunkLength;
4479
const unsigned char* data; /*the data in the chunk*/
4481
/*error: size of the in buffer too small to contain next chunk*/
4482
if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
4484
/*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4485
chunkLength = lodepng_chunk_length(chunk);
4486
/*error: chunk length larger than the max PNG chunk size*/
4487
if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
4489
if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
4491
CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
4494
data = lodepng_chunk_data_const(chunk);
4496
/*IDAT chunk, containing compressed image data*/
4497
if(lodepng_chunk_type_equals(chunk, "IDAT"))
4499
size_t oldsize = idat.size;
4500
if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4501
for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
4502
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4504
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4507
else if(lodepng_chunk_type_equals(chunk, "IEND"))
4511
/*palette chunk (PLTE)*/
4512
else if(lodepng_chunk_type_equals(chunk, "PLTE"))
4514
state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
4515
if(state->error) break;
4516
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4518
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4520
/*palette transparency chunk (tRNS)*/
4521
else if(lodepng_chunk_type_equals(chunk, "tRNS"))
4523
state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
4524
if(state->error) break;
4526
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4527
/*background color chunk (bKGD)*/
4528
else if(lodepng_chunk_type_equals(chunk, "bKGD"))
4530
state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
4531
if(state->error) break;
4533
/*text chunk (tEXt)*/
4534
else if(lodepng_chunk_type_equals(chunk, "tEXt"))
4536
if(state->decoder.read_text_chunks)
4538
state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
4539
if(state->error) break;
4542
/*compressed text chunk (zTXt)*/
4543
else if(lodepng_chunk_type_equals(chunk, "zTXt"))
4545
if(state->decoder.read_text_chunks)
4547
state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4548
if(state->error) break;
4551
/*international text chunk (iTXt)*/
4552
else if(lodepng_chunk_type_equals(chunk, "iTXt"))
4554
if(state->decoder.read_text_chunks)
4556
state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
4557
if(state->error) break;
4560
else if(lodepng_chunk_type_equals(chunk, "tIME"))
4562
state->error = readChunk_tIME(&state->info_png, data, chunkLength);
4563
if(state->error) break;
4565
else if(lodepng_chunk_type_equals(chunk, "pHYs"))
4567
state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
4568
if(state->error) break;
4570
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4571
else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4573
/*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4574
if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
4577
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4578
if(state->decoder.remember_unknown_chunks)
4580
state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
4581
&state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
4582
if(state->error) break;
4584
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4587
if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
4589
if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
4592
if(!IEND) chunk = lodepng_chunk_next_const(chunk);
4595
ucvector_init(&scanlines);
4596
/*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
4597
If the decompressed size does not match the prediction, the image must be corrupt.*/
4598
if(state->info_png.interlace_method == 0)
4600
/*The extra *h is added because this are the filter bytes every scanline starts with*/
4601
predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h;
4605
/*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
4606
const LodePNGColorMode* color = &state->info_png.color;
4608
predict += lodepng_get_raw_size_idat((*w + 7) / 8, (*h + 7) / 8, color) + (*h + 7) / 8;
4609
if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) / 8, (*h + 7) / 8, color) + (*h + 7) / 8;
4610
predict += lodepng_get_raw_size_idat((*w + 3) / 4, (*h + 3) / 8, color) + (*h + 3) / 8;
4611
if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) / 4, (*h + 3) / 4, color) + (*h + 3) / 4;
4612
predict += lodepng_get_raw_size_idat((*w + 1) / 2, (*h + 1) / 4, color) + (*h + 1) / 4;
4613
if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) / 2, (*h + 1) / 2, color) + (*h + 1) / 2;
4614
predict += lodepng_get_raw_size_idat((*w + 0) / 1, (*h + 0) / 2, color) + (*h + 0) / 2;
4616
if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
4619
state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
4620
idat.size, &state->decoder.zlibsettings);
4621
if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/
4623
ucvector_cleanup(&idat);
4627
size_t outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
4629
ucvector_init(&outv);
4630
if(!ucvector_resizev(&outv, outsize, 0)) state->error = 83; /*alloc fail*/
4631
if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png);
4634
ucvector_cleanup(&scanlines);
4637
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
4638
LodePNGState* state,
4639
const unsigned char* in, size_t insize)
4642
decodeGeneric(out, w, h, state, in, insize);
4643
if(state->error) return state->error;
4644
if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
4646
/*same color type, no copying or converting of data needed*/
4647
/*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4648
the raw image has to the end user*/
4649
if(!state->decoder.color_convert)
4651
state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
4652
if(state->error) return state->error;
4657
/*color conversion needed; sort of copy of the data*/
4658
unsigned char* data = *out;
4661
/*TODO: check if this works according to the statement in the documentation: "The converter can convert
4662
from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4663
if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
4664
&& !(state->info_raw.bitdepth == 8))
4666
return 56; /*unsupported color mode conversion*/
4669
outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
4670
*out = (unsigned char*)lodepng_malloc(outsize);
4673
state->error = 83; /*alloc fail*/
4675
else state->error = lodepng_convert(*out, data, &state->info_raw,
4676
&state->info_png.color, *w, *h);
4679
return state->error;
4682
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
4683
size_t insize, LodePNGColorType colortype, unsigned bitdepth)
4687
lodepng_state_init(&state);
4688
state.info_raw.colortype = colortype;
4689
state.info_raw.bitdepth = bitdepth;
4690
error = lodepng_decode(out, w, h, &state, in, insize);
4691
lodepng_state_cleanup(&state);
4695
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4697
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
4700
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4702
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
4705
#ifdef LODEPNG_COMPILE_DISK
4706
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
4707
LodePNGColorType colortype, unsigned bitdepth)
4709
unsigned char* buffer;
4712
error = lodepng_load_file(&buffer, &buffersize, filename);
4713
if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
4714
lodepng_free(buffer);
4718
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4720
return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
4723
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4725
return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
4727
#endif /*LODEPNG_COMPILE_DISK*/
4729
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
4731
settings->color_convert = 1;
4732
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4733
settings->read_text_chunks = 1;
4734
settings->remember_unknown_chunks = 0;
4735
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4736
settings->ignore_crc = 0;
4737
lodepng_decompress_settings_init(&settings->zlibsettings);
4740
#endif /*LODEPNG_COMPILE_DECODER*/
4742
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4744
void lodepng_state_init(LodePNGState* state)
4746
#ifdef LODEPNG_COMPILE_DECODER
4747
lodepng_decoder_settings_init(&state->decoder);
4748
#endif /*LODEPNG_COMPILE_DECODER*/
4749
#ifdef LODEPNG_COMPILE_ENCODER
4750
lodepng_encoder_settings_init(&state->encoder);
4751
#endif /*LODEPNG_COMPILE_ENCODER*/
4752
lodepng_color_mode_init(&state->info_raw);
4753
lodepng_info_init(&state->info_png);
4757
void lodepng_state_cleanup(LodePNGState* state)
4759
lodepng_color_mode_cleanup(&state->info_raw);
4760
lodepng_info_cleanup(&state->info_png);
4763
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
4765
lodepng_state_cleanup(dest);
4767
lodepng_color_mode_init(&dest->info_raw);
4768
lodepng_info_init(&dest->info_png);
4769
dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
4770
dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
4773
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4775
#ifdef LODEPNG_COMPILE_ENCODER
4777
/* ////////////////////////////////////////////////////////////////////////// */
4778
/* / PNG Encoder / */
4779
/* ////////////////////////////////////////////////////////////////////////// */
4781
/*chunkName must be string of 4 characters*/
4782
static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
4784
CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
4785
out->allocsize = out->size; /*fix the allocsize again*/
4789
static void writeSignature(ucvector* out)
4791
/*8 bytes PNG signature, aka the magic bytes*/
4792
ucvector_push_back(out, 137);
4793
ucvector_push_back(out, 80);
4794
ucvector_push_back(out, 78);
4795
ucvector_push_back(out, 71);
4796
ucvector_push_back(out, 13);
4797
ucvector_push_back(out, 10);
4798
ucvector_push_back(out, 26);
4799
ucvector_push_back(out, 10);
4802
static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
4803
LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
4807
ucvector_init(&header);
4809
lodepng_add32bitInt(&header, w); /*width*/
4810
lodepng_add32bitInt(&header, h); /*height*/
4811
ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
4812
ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
4813
ucvector_push_back(&header, 0); /*compression method*/
4814
ucvector_push_back(&header, 0); /*filter method*/
4815
ucvector_push_back(&header, interlace_method); /*interlace method*/
4817
error = addChunk(out, "IHDR", header.data, header.size);
4818
ucvector_cleanup(&header);
4823
static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
4828
ucvector_init(&PLTE);
4829
for(i = 0; i != info->palettesize * 4; ++i)
4831
/*add all channels except alpha channel*/
4832
if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
4834
error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
4835
ucvector_cleanup(&PLTE);
4840
static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
4845
ucvector_init(&tRNS);
4846
if(info->colortype == LCT_PALETTE)
4848
size_t amount = info->palettesize;
4849
/*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4850
for(i = info->palettesize; i != 0; --i)
4852
if(info->palette[4 * (i - 1) + 3] == 255) --amount;
4855
/*add only alpha channel*/
4856
for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
4858
else if(info->colortype == LCT_GREY)
4860
if(info->key_defined)
4862
ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4863
ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4866
else if(info->colortype == LCT_RGB)
4868
if(info->key_defined)
4870
ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4871
ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4872
ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256));
4873
ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256));
4874
ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256));
4875
ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256));
4879
error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
4880
ucvector_cleanup(&tRNS);
4885
static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
4886
LodePNGCompressSettings* zlibsettings)
4891
/*compress with the Zlib compressor*/
4892
ucvector_init(&zlibdata);
4893
error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
4894
if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
4895
ucvector_cleanup(&zlibdata);
4900
static unsigned addChunk_IEND(ucvector* out)
4903
error = addChunk(out, "IEND", 0, 0);
4907
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4909
static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
4914
ucvector_init(&text);
4915
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
4916
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4917
ucvector_push_back(&text, 0); /*0 termination char*/
4918
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
4919
error = addChunk(out, "tEXt", text.data, text.size);
4920
ucvector_cleanup(&text);
4925
static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
4926
LodePNGCompressSettings* zlibsettings)
4929
ucvector data, compressed;
4930
size_t i, textsize = strlen(textstring);
4932
ucvector_init(&data);
4933
ucvector_init(&compressed);
4934
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4935
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4936
ucvector_push_back(&data, 0); /*0 termination char*/
4937
ucvector_push_back(&data, 0); /*compression method: 0*/
4939
error = zlib_compress(&compressed.data, &compressed.size,
4940
(unsigned char*)textstring, textsize, zlibsettings);
4943
for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
4944
error = addChunk(out, "zTXt", data.data, data.size);
4947
ucvector_cleanup(&compressed);
4948
ucvector_cleanup(&data);
4952
static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
4953
const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
4957
size_t i, textsize = strlen(textstring);
4959
ucvector_init(&data);
4961
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
4962
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
4963
ucvector_push_back(&data, 0); /*null termination char*/
4964
ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
4965
ucvector_push_back(&data, 0); /*compression method*/
4966
for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
4967
ucvector_push_back(&data, 0); /*null termination char*/
4968
for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
4969
ucvector_push_back(&data, 0); /*null termination char*/
4973
ucvector compressed_data;
4974
ucvector_init(&compressed_data);
4975
error = zlib_compress(&compressed_data.data, &compressed_data.size,
4976
(unsigned char*)textstring, textsize, zlibsettings);
4979
for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
4981
ucvector_cleanup(&compressed_data);
4983
else /*not compressed*/
4985
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
4988
if(!error) error = addChunk(out, "iTXt", data.data, data.size);
4989
ucvector_cleanup(&data);
4993
static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info)
4997
ucvector_init(&bKGD);
4998
if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
5000
ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5001
ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5003
else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
5005
ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256));
5006
ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256));
5007
ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256));
5008
ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256));
5009
ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256));
5010
ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256));
5012
else if(info->color.colortype == LCT_PALETTE)
5014
ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/
5017
error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
5018
ucvector_cleanup(&bKGD);
5023
static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time)
5026
unsigned char* data = (unsigned char*)lodepng_malloc(7);
5027
if(!data) return 83; /*alloc fail*/
5028
data[0] = (unsigned char)(time->year / 256);
5029
data[1] = (unsigned char)(time->year % 256);
5030
data[2] = (unsigned char)time->month;
5031
data[3] = (unsigned char)time->day;
5032
data[4] = (unsigned char)time->hour;
5033
data[5] = (unsigned char)time->minute;
5034
data[6] = (unsigned char)time->second;
5035
error = addChunk(out, "tIME", data, 7);
5040
static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
5044
ucvector_init(&data);
5046
lodepng_add32bitInt(&data, info->phys_x);
5047
lodepng_add32bitInt(&data, info->phys_y);
5048
ucvector_push_back(&data, info->phys_unit);
5050
error = addChunk(out, "pHYs", data.data, data.size);
5051
ucvector_cleanup(&data);
5056
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5058
static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
5059
size_t length, size_t bytewidth, unsigned char filterType)
5065
for(i = 0; i != length; ++i) out[i] = scanline[i];
5068
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5069
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
5074
for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
5078
for(i = 0; i != length; ++i) out[i] = scanline[i];
5084
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - prevline[i] / 2;
5085
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2);
5089
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5090
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth] / 2;
5096
/*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5097
for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
5098
for(i = bytewidth; i < length; ++i)
5100
out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
5105
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
5106
/*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5107
for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
5110
default: return; /*unexisting filter type given*/
5114
/* log2 approximation. A slight bit faster than std::log. */
5115
static float flog2(float f)
5118
while(f > 32) { result += 4; f /= 16; }
5119
while(f > 2) { ++result; f /= 2; }
5120
return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
5123
static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
5124
const LodePNGColorMode* info, const LodePNGEncoderSettings* settings)
5127
For PNG filter method 0
5128
out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5129
the scanlines with 1 extra byte per scanline
5132
unsigned bpp = lodepng_get_bpp(info);
5133
/*the width of a scanline in bytes, not including the filter type*/
5134
size_t linebytes = (w * bpp + 7) / 8;
5135
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5136
size_t bytewidth = (bpp + 7) / 8;
5137
const unsigned char* prevline = 0;
5140
LodePNGFilterStrategy strategy = settings->filter_strategy;
5143
There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5144
* If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5145
use fixed filtering, with the filter None).
5146
* (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5147
not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5148
all five filters and select the filter that produces the smallest sum of absolute values per row.
5149
This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5151
If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5152
but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5155
if(settings->filter_palette_zero &&
5156
(info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
5158
if(bpp == 0) return 31; /*error: invalid color type*/
5160
if(strategy == LFS_ZERO)
5162
for(y = 0; y != h; ++y)
5164
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5165
size_t inindex = linebytes * y;
5166
out[outindex] = 0; /*filter type byte*/
5167
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
5168
prevline = &in[inindex];
5171
else if(strategy == LFS_MINSUM)
5173
/*adaptive filtering*/
5175
ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5176
size_t smallest = 0;
5177
unsigned char type, bestType = 0;
5179
for(type = 0; type != 5; ++type)
5181
ucvector_init(&attempt[type]);
5182
if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5187
for(y = 0; y != h; ++y)
5189
/*try the 5 filter types*/
5190
for(type = 0; type != 5; ++type)
5192
filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5194
/*calculate the sum of the result*/
5198
for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type].data[x]);
5202
for(x = 0; x != linebytes; ++x)
5204
/*For differences, each byte should be treated as signed, values above 127 are negative
5205
(converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5206
This means filtertype 0 is almost never chosen, but that is justified.*/
5207
unsigned char s = attempt[type].data[x];
5208
sum[type] += s < 128 ? s : (255U - s);
5212
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5213
if(type == 0 || sum[type] < smallest)
5216
smallest = sum[type];
5220
prevline = &in[y * linebytes];
5222
/*now fill the out values*/
5223
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5224
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5228
for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5230
else if(strategy == LFS_ENTROPY)
5233
ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5235
unsigned type, bestType = 0;
5236
unsigned count[256];
5238
for(type = 0; type != 5; ++type)
5240
ucvector_init(&attempt[type]);
5241
if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/
5244
for(y = 0; y != h; ++y)
5246
/*try the 5 filter types*/
5247
for(type = 0; type != 5; ++type)
5249
filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5250
for(x = 0; x != 256; ++x) count[x] = 0;
5251
for(x = 0; x != linebytes; ++x) ++count[attempt[type].data[x]];
5252
++count[type]; /*the filter type itself is part of the scanline*/
5254
for(x = 0; x != 256; ++x)
5256
float p = count[x] / (float)(linebytes + 1);
5257
sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
5259
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5260
if(type == 0 || sum[type] < smallest)
5263
smallest = sum[type];
5267
prevline = &in[y * linebytes];
5269
/*now fill the out values*/
5270
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5271
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5274
for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5276
else if(strategy == LFS_PREDEFINED)
5278
for(y = 0; y != h; ++y)
5280
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
5281
size_t inindex = linebytes * y;
5282
unsigned char type = settings->predefined_filters[y];
5283
out[outindex] = type; /*filter type byte*/
5284
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
5285
prevline = &in[inindex];
5288
else if(strategy == LFS_BRUTE_FORCE)
5290
/*brute force filter chooser.
5291
deflate the scanline after every filter attempt to see which one deflates best.
5292
This is very slow and gives only slightly smaller, sometimes even larger, result*/
5294
ucvector attempt[5]; /*five filtering attempts, one for each filter type*/
5295
size_t smallest = 0;
5296
unsigned type = 0, bestType = 0;
5297
unsigned char* dummy;
5298
LodePNGCompressSettings zlibsettings = settings->zlibsettings;
5299
/*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5300
to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5301
better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5302
cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5303
zlibsettings.btype = 1;
5304
/*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5305
images only, so disable it*/
5306
zlibsettings.custom_zlib = 0;
5307
zlibsettings.custom_deflate = 0;
5308
for(type = 0; type != 5; ++type)
5310
ucvector_init(&attempt[type]);
5311
ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/
5313
for(y = 0; y != h; ++y) /*try the 5 filter types*/
5315
for(type = 0; type != 5; ++type)
5317
unsigned testsize = attempt[type].size;
5318
/*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5320
filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type);
5323
zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings);
5324
lodepng_free(dummy);
5325
/*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5326
if(type == 0 || size[type] < smallest)
5329
smallest = size[type];
5332
prevline = &in[y * linebytes];
5333
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
5334
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x];
5336
for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]);
5338
else return 88; /* unknown filter strategy */
5343
static void addPaddingBits(unsigned char* out, const unsigned char* in,
5344
size_t olinebits, size_t ilinebits, unsigned h)
5346
/*The opposite of the removePaddingBits function
5347
olinebits must be >= ilinebits*/
5349
size_t diff = olinebits - ilinebits;
5350
size_t obp = 0, ibp = 0; /*bit pointers*/
5351
for(y = 0; y != h; ++y)
5354
for(x = 0; x < ilinebits; ++x)
5356
unsigned char bit = readBitFromReversedStream(&ibp, in);
5357
setBitOfReversedStream(&obp, out, bit);
5359
/*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5360
"Use of uninitialised value of size ###" warning from valgrind*/
5361
for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
5366
in: non-interlaced image with size w*h
5367
out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5368
no padding bits between scanlines, but between reduced images so that each
5369
reduced image starts at a byte.
5371
there are no padding bits, not between scanlines, not between reduced images
5372
in has the following size in bits: w * h * bpp.
5373
out is possibly bigger due to padding bits between reduced images
5374
NOTE: comments about padding bits are only relevant if bpp < 8
5376
static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
5378
unsigned passw[7], passh[7];
5379
size_t filter_passstart[8], padded_passstart[8], passstart[8];
5382
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5386
for(i = 0; i != 7; ++i)
5389
size_t bytewidth = bpp / 8;
5390
for(y = 0; y < passh[i]; ++y)
5391
for(x = 0; x < passw[i]; ++x)
5393
size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
5394
size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
5395
for(b = 0; b < bytewidth; ++b)
5397
out[pixeloutstart + b] = in[pixelinstart + b];
5402
else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5404
for(i = 0; i != 7; ++i)
5407
unsigned ilinebits = bpp * passw[i];
5408
unsigned olinebits = bpp * w;
5409
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
5410
for(y = 0; y < passh[i]; ++y)
5411
for(x = 0; x < passw[i]; ++x)
5413
ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
5414
obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
5415
for(b = 0; b < bpp; ++b)
5417
unsigned char bit = readBitFromReversedStream(&ibp, in);
5418
setBitOfReversedStream(&obp, out, bit);
5425
/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5426
return value is error**/
5427
static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
5428
unsigned w, unsigned h,
5429
const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings)
5432
This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5433
*) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5434
*) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5436
unsigned bpp = lodepng_get_bpp(&info_png->color);
5439
if(info_png->interlace_method == 0)
5441
*outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5442
*out = (unsigned char*)lodepng_malloc(*outsize);
5443
if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
5447
/*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5448
if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
5450
unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8));
5451
if(!padded) error = 83; /*alloc fail*/
5454
addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
5455
error = filter(*out, padded, w, h, &info_png->color, settings);
5457
lodepng_free(padded);
5461
/*we can immediatly filter into the out buffer, no other steps needed*/
5462
error = filter(*out, in, w, h, &info_png->color, settings);
5466
else /*interlace_method is 1 (Adam7)*/
5468
unsigned passw[7], passh[7];
5469
size_t filter_passstart[8], padded_passstart[8], passstart[8];
5470
unsigned char* adam7;
5472
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
5474
*outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5475
*out = (unsigned char*)lodepng_malloc(*outsize);
5476
if(!(*out)) error = 83; /*alloc fail*/
5478
adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
5479
if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
5485
Adam7_interlace(adam7, in, w, h, bpp);
5486
for(i = 0; i != 7; ++i)
5490
unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
5491
if(!padded) ERROR_BREAK(83); /*alloc fail*/
5492
addPaddingBits(padded, &adam7[passstart[i]],
5493
((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
5494
error = filter(&(*out)[filter_passstart[i]], padded,
5495
passw[i], passh[i], &info_png->color, settings);
5496
lodepng_free(padded);
5500
error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
5501
passw[i], passh[i], &info_png->color, settings);
5508
lodepng_free(adam7);
5515
palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5516
returns 0 if the palette is opaque,
5517
returns 1 if the palette has a single color with alpha 0 ==> color key
5518
returns 2 if the palette is semi-translucent.
5520
static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize)
5524
unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5525
for(i = 0; i != palettesize; ++i)
5527
if(!key && palette[4 * i + 3] == 0)
5529
r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
5531
i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5533
else if(palette[4 * i + 3] != 255) return 2;
5534
/*when key, no opaque RGB may have key's RGB*/
5535
else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
5540
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5541
static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
5543
unsigned char* inchunk = data;
5544
while((size_t)(inchunk - data) < datasize)
5546
CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
5547
out->allocsize = out->size; /*fix the allocsize again*/
5548
inchunk = lodepng_chunk_next(inchunk);
5552
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5554
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
5555
const unsigned char* image, unsigned w, unsigned h,
5556
LodePNGState* state)
5560
unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
5561
size_t datasize = 0;
5563
/*provide some proper output values if error will happen*/
5568
lodepng_info_init(&info);
5569
lodepng_info_copy(&info, &state->info_png);
5571
if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
5572
&& (info.color.palettesize == 0 || info.color.palettesize > 256))
5574
state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
5575
return state->error;
5578
if(state->encoder.auto_convert)
5580
state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
5582
if(state->error) return state->error;
5584
if(state->encoder.zlibsettings.btype > 2)
5586
CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
5588
if(state->info_png.interlace_method > 1)
5590
CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
5593
state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
5594
if(state->error) return state->error; /*error: unexisting color type given*/
5595
state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
5596
if(state->error) return state->error; /*error: unexisting color type given*/
5598
if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
5600
unsigned char* converted;
5601
size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
5603
converted = (unsigned char*)lodepng_malloc(size);
5604
if(!converted && size) state->error = 83; /*alloc fail*/
5607
state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
5609
if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
5610
lodepng_free(converted);
5612
else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
5614
ucvector_init(&outv);
5615
while(!state->error) /*while only executed once, to break on error*/
5617
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5619
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5620
/*write signature and chunks*/
5621
writeSignature(&outv);
5623
addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
5624
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5625
/*unknown chunks between IHDR and PLTE*/
5626
if(info.unknown_chunks_data[0])
5628
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
5629
if(state->error) break;
5631
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5633
if(info.color.colortype == LCT_PALETTE)
5635
addChunk_PLTE(&outv, &info.color);
5637
if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA))
5639
addChunk_PLTE(&outv, &info.color);
5642
if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0)
5644
addChunk_tRNS(&outv, &info.color);
5646
if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined)
5648
addChunk_tRNS(&outv, &info.color);
5650
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5651
/*bKGD (must come between PLTE and the IDAt chunks*/
5652
if(info.background_defined) addChunk_bKGD(&outv, &info);
5653
/*pHYs (must come before the IDAT chunks)*/
5654
if(info.phys_defined) addChunk_pHYs(&outv, &info);
5656
/*unknown chunks between PLTE and IDAT*/
5657
if(info.unknown_chunks_data[1])
5659
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
5660
if(state->error) break;
5662
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5663
/*IDAT (multiple IDAT chunks must be consecutive)*/
5664
state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
5665
if(state->error) break;
5666
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5668
if(info.time_defined) addChunk_tIME(&outv, &info.time);
5669
/*tEXt and/or zTXt*/
5670
for(i = 0; i != info.text_num; ++i)
5672
if(strlen(info.text_keys[i]) > 79)
5674
state->error = 66; /*text chunk too large*/
5677
if(strlen(info.text_keys[i]) < 1)
5679
state->error = 67; /*text chunk too small*/
5682
if(state->encoder.text_compression)
5684
addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
5688
addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
5691
/*LodePNG version id in text chunk*/
5692
if(state->encoder.add_id)
5694
unsigned alread_added_id_text = 0;
5695
for(i = 0; i != info.text_num; ++i)
5697
if(!strcmp(info.text_keys[i], "LodePNG"))
5699
alread_added_id_text = 1;
5703
if(alread_added_id_text == 0)
5705
addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
5709
for(i = 0; i != info.itext_num; ++i)
5711
if(strlen(info.itext_keys[i]) > 79)
5713
state->error = 66; /*text chunk too large*/
5716
if(strlen(info.itext_keys[i]) < 1)
5718
state->error = 67; /*text chunk too small*/
5721
addChunk_iTXt(&outv, state->encoder.text_compression,
5722
info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
5723
&state->encoder.zlibsettings);
5726
/*unknown chunks between IDAT and IEND*/
5727
if(info.unknown_chunks_data[2])
5729
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
5730
if(state->error) break;
5732
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5733
addChunk_IEND(&outv);
5735
break; /*this isn't really a while loop; no error happened so break out now!*/
5738
lodepng_info_cleanup(&info);
5740
/*instead of cleaning the vector up, give it to the output*/
5742
*outsize = outv.size;
5744
return state->error;
5747
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
5748
unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
5752
lodepng_state_init(&state);
5753
state.info_raw.colortype = colortype;
5754
state.info_raw.bitdepth = bitdepth;
5755
state.info_png.color.colortype = colortype;
5756
state.info_png.color.bitdepth = bitdepth;
5757
lodepng_encode(out, outsize, image, w, h, &state);
5758
error = state.error;
5759
lodepng_state_cleanup(&state);
5763
unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5765
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
5768
unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
5770
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
5773
#ifdef LODEPNG_COMPILE_DISK
5774
unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
5775
LodePNGColorType colortype, unsigned bitdepth)
5777
unsigned char* buffer;
5779
unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
5780
if(!error) error = lodepng_save_file(buffer, buffersize, filename);
5781
lodepng_free(buffer);
5785
unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5787
return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
5790
unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
5792
return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
5794
#endif /*LODEPNG_COMPILE_DISK*/
5796
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
5798
lodepng_compress_settings_init(&settings->zlibsettings);
5799
settings->filter_palette_zero = 1;
5800
settings->filter_strategy = LFS_MINSUM;
5801
settings->auto_convert = 1;
5802
settings->force_palette = 0;
5803
settings->predefined_filters = 0;
5804
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5805
settings->add_id = 0;
5806
settings->text_compression = 1;
5807
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5810
#endif /*LODEPNG_COMPILE_ENCODER*/
5811
#endif /*LODEPNG_COMPILE_PNG*/
5813
#ifdef LODEPNG_COMPILE_ERROR_TEXT
5815
This returns the description of a numerical error code in English. This is also
5816
the documentation of all the error codes.
5818
const char* lodepng_error_text(unsigned code)
5822
case 0: return "no error, everything went ok";
5823
case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5824
case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
5825
case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5826
case 13: return "problem while processing dynamic deflate block";
5827
case 14: return "problem while processing dynamic deflate block";
5828
case 15: return "problem while processing dynamic deflate block";
5829
case 16: return "unexisting code while processing dynamic deflate block";
5830
case 17: return "end of out buffer memory reached while inflating";
5831
case 18: return "invalid distance code while inflating";
5832
case 19: return "end of out buffer memory reached while inflating";
5833
case 20: return "invalid deflate block BTYPE encountered while decoding";
5834
case 21: return "NLEN is not ones complement of LEN in a deflate block";
5835
/*end of out buffer memory reached while inflating:
5836
This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5837
all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5838
happen in a normal, well encoded, PNG image.*/
5839
case 22: return "end of out buffer memory reached while inflating";
5840
case 23: return "end of in buffer memory reached while inflating";
5841
case 24: return "invalid FCHECK in zlib header";
5842
case 25: return "invalid compression method in zlib header";
5843
case 26: return "FDICT encountered in zlib header while it's not used for PNG";
5844
case 27: return "PNG file is smaller than a PNG header";
5845
/*Checks the magic file header, the first 8 bytes of the PNG file*/
5846
case 28: return "incorrect PNG signature, it's no PNG or corrupted";
5847
case 29: return "first chunk is not the header chunk";
5848
case 30: return "chunk length too large, chunk broken off at end of file";
5849
case 31: return "illegal PNG color type or bpp";
5850
case 32: return "illegal PNG compression method";
5851
case 33: return "illegal PNG filter method";
5852
case 34: return "illegal PNG interlace method";
5853
case 35: return "chunk length of a chunk is too large or the chunk too small";
5854
case 36: return "illegal PNG filter type encountered";
5855
case 37: return "illegal bit depth for this color type given";
5856
case 38: return "the palette is too big"; /*more than 256 colors*/
5857
case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
5858
case 40: return "tRNS chunk has wrong size for greyscale image";
5859
case 41: return "tRNS chunk has wrong size for RGB image";
5860
case 42: return "tRNS chunk appeared while it was not allowed for this color type";
5861
case 43: return "bKGD chunk has wrong size for palette image";
5862
case 44: return "bKGD chunk has wrong size for greyscale image";
5863
case 45: return "bKGD chunk has wrong size for RGB image";
5864
/*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/
5865
case 48: return "empty input or file doesn't exist";
5866
case 49: return "jumped past memory while generating dynamic huffman tree";
5867
case 50: return "jumped past memory while generating dynamic huffman tree";
5868
case 51: return "jumped past memory while inflating huffman block";
5869
case 52: return "jumped past memory while inflating";
5870
case 53: return "size of zlib data too small";
5871
case 54: return "repeat symbol in tree while there was no value symbol yet";
5872
/*jumped past tree while generating huffman tree, this could be when the
5873
tree will have more leaves than symbols after generating it out of the
5874
given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
5875
case 55: return "jumped past tree while generating huffman tree";
5876
case 56: return "given output image colortype or bitdepth not supported for color conversion";
5877
case 57: return "invalid CRC encountered (checking CRC can be disabled)";
5878
case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
5879
case 59: return "requested color conversion not supported";
5880
case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
5881
case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
5882
/*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
5883
case 62: return "conversion from color to greyscale not supported";
5884
case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
5885
/*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
5886
case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
5887
case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
5888
case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
5889
case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
5890
case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
5891
case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
5892
case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
5893
case 73: return "invalid tIME chunk size";
5894
case 74: return "invalid pHYs chunk size";
5895
/*length could be wrong, or data chopped off*/
5896
case 75: return "no null termination char found while decoding text chunk";
5897
case 76: return "iTXt chunk too short to contain required bytes";
5898
case 77: return "integer overflow in buffer size";
5899
case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
5900
case 79: return "failed to open file for writing";
5901
case 80: return "tried creating a tree of 0 symbols";
5902
case 81: return "lazy matching at pos 0 is impossible";
5903
case 82: return "color conversion to palette requested while a color isn't in palette";
5904
case 83: return "memory allocation failed";
5905
case 84: return "given image too small to contain all pixels to be encoded";
5906
case 86: return "impossible offset in lz77 encoding (internal bug)";
5907
case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
5908
case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
5909
case 89: return "text chunk keyword too short or long: must have size 1-79";
5910
/*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
5911
case 90: return "windowsize must be a power of two";
5912
case 91: return "invalid decompressed idat size";
5913
case 92: return "too many pixels, not supported";
5914
case 93: return "zero width or height is invalid";
5916
return "unknown error code";
5918
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/