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