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