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