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