4 * Slightly modified from LodePNG (see below for copyright and
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.
13 LodePNG version 20121216
15 Copyright (c) 2005-2012 Lode Vandevenne
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.
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:
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.
30 2. Altered source versions must be plainly marked as such, and must not be
31 misrepresented as being the original software.
33 3. This notice may not be removed or altered from any source
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.
45 // #include <stdlib.h>
48 #include "../refind/screen.h"
50 #ifdef LODEPNG_COMPILE_CPP
52 #endif /*LODEPNG_COMPILE_CPP*/
54 #define VERSION_STRING "20121216"
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
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.*/
69 static void *mymalloc(size_t size
) {
72 // size += sizeof (size_t);
73 ptr
= AllocateZeroPool(size
+ sizeof(size_t));
75 *(size_t *) ptr
= size
;
76 return ((size_t *) ptr
) + 1;
82 static void myfree (void *ptr
) {
84 ptr
= (void *) (((size_t *) ptr
) - 1);
89 static size_t report_size(void *ptr
) {
91 return * (((size_t *) ptr
) - 1);
96 static void *myrealloc(void *ptr
, size_t new_size
) {
100 new_pool
= mymalloc(new_size
);
101 if (new_pool
&& ptr
) {
102 old_size
= report_size(ptr
);
103 CopyMem(new_pool
, ptr
, (old_size
< new_size
) ? old_size
: new_size
);
108 // Finds length of ASCII string, which MUST be NULL-terminated.
109 int MyStrlen(const char *InString
) {
113 while (InString
[Length
] != '\0')
119 /* ////////////////////////////////////////////////////////////////////////// */
120 /* ////////////////////////////////////////////////////////////////////////// */
121 /* // Tools for C, and common code for PNG and Zlib. // */
122 /* ////////////////////////////////////////////////////////////////////////// */
123 /* ////////////////////////////////////////////////////////////////////////// */
126 Often in case of an error a value is assigned to a variable and then it breaks
127 out of a loop (to go to the cleanup phase of a function). This macro does that.
128 It makes the error handling code shorter and more readable.
130 Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
132 #define CERROR_BREAK(errorvar, code)\
138 /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
139 #define ERROR_BREAK(code) CERROR_BREAK(error, code)
141 /*Set error var to the error code, and return it.*/
142 #define CERROR_RETURN_ERROR(errorvar, code)\
148 /*Try the code, if it returns error, also return the error.*/
149 #define CERROR_TRY_RETURN(call)\
151 unsigned error = call;\
152 if(error) return error;\
156 About uivector, ucvector and string:
157 -All of them wrap dynamic arrays or text strings in a similar way.
158 -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
159 -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
160 -They're not used in the interface, only internally in this file as static functions.
161 -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
164 #ifdef LODEPNG_COMPILE_ZLIB
165 /*dynamic vector of unsigned ints*/
167 typedef struct uivector
170 size_t size
; /*size in number of unsigned longs*/
171 size_t allocsize
; /*allocated size in bytes*/
174 static void uivector_cleanup(void* p
)
176 ((uivector
*)p
)->size
= ((uivector
*)p
)->allocsize
= 0;
177 myfree(((uivector
*)p
)->data
);
178 ((uivector
*)p
)->data
= NULL
;
181 /*returns 1 if success, 0 if failure ==> nothing done*/
182 static unsigned uivector_resize(uivector
* p
, size_t size
)
184 if(size
* sizeof(unsigned) > p
->allocsize
)
186 size_t newsize
= size
* sizeof(unsigned) * 2;
187 void* data
= myrealloc(p
->data
, newsize
);
190 p
->allocsize
= newsize
;
191 p
->data
= (unsigned*)data
;
200 /*resize and give all new elements the value*/
201 static unsigned uivector_resizev(uivector
* p
, size_t size
, unsigned value
)
203 size_t oldsize
= p
->size
, i
;
204 if(!uivector_resize(p
, size
)) return 0;
205 for(i
= oldsize
; i
< size
; i
++) p
->data
[i
] = value
;
209 static void uivector_init(uivector
* p
)
212 p
->size
= p
->allocsize
= 0;
215 #ifdef LODEPNG_COMPILE_ENCODER
216 /*returns 1 if success, 0 if failure ==> nothing done*/
217 static unsigned uivector_push_back(uivector
* p
, unsigned c
)
219 if(!uivector_resize(p
, p
->size
+ 1)) return 0;
220 p
->data
[p
->size
- 1] = c
;
224 /*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/
225 static unsigned uivector_copy(uivector
* p
, const uivector
* q
)
228 if(!uivector_resize(p
, q
->size
)) return 0;
229 for(i
= 0; i
< q
->size
; i
++) p
->data
[i
] = q
->data
[i
];
233 static void uivector_swap(uivector
* p
, uivector
* q
)
237 tmp
= p
->size
; p
->size
= q
->size
; q
->size
= tmp
;
238 tmp
= p
->allocsize
; p
->allocsize
= q
->allocsize
; q
->allocsize
= tmp
;
239 tmpp
= p
->data
; p
->data
= q
->data
; q
->data
= tmpp
;
241 #endif /*LODEPNG_COMPILE_ENCODER*/
242 #endif /*LODEPNG_COMPILE_ZLIB*/
244 /* /////////////////////////////////////////////////////////////////////////// */
246 /*dynamic vector of unsigned chars*/
247 typedef struct ucvector
250 size_t size
; /*used size*/
251 size_t allocsize
; /*allocated size*/
254 /*returns 1 if success, 0 if failure ==> nothing done*/
255 static unsigned ucvector_resize(ucvector
* p
, size_t size
)
257 if(size
* sizeof(unsigned char) > p
->allocsize
)
259 size_t newsize
= size
* sizeof(unsigned char) * 2;
260 void* data
= myrealloc(p
->data
, newsize
);
263 p
->allocsize
= newsize
;
264 p
->data
= (unsigned char*)data
;
267 else return 0; /*error: not enough memory*/
273 #ifdef LODEPNG_COMPILE_PNG
275 static void ucvector_cleanup(void* p
)
277 ((ucvector
*)p
)->size
= ((ucvector
*)p
)->allocsize
= 0;
278 myfree(((ucvector
*)p
)->data
);
279 ((ucvector
*)p
)->data
= NULL
;
282 static void ucvector_init(ucvector
* p
)
285 p
->size
= p
->allocsize
= 0;
288 #ifdef LODEPNG_COMPILE_DECODER
289 /*resize and give all new elements the value*/
290 static unsigned ucvector_resizev(ucvector
* p
, size_t size
, unsigned char value
)
292 size_t oldsize
= p
->size
, i
;
293 if(!ucvector_resize(p
, size
)) return 0;
294 for(i
= oldsize
; i
< size
; i
++) p
->data
[i
] = value
;
297 #endif /*LODEPNG_COMPILE_DECODER*/
298 #endif /*LODEPNG_COMPILE_PNG*/
300 #ifdef LODEPNG_COMPILE_ZLIB
301 /*you can both convert from vector to buffer&size and vica versa. If you use
302 init_buffer to take over a buffer and size, it is not needed to use cleanup*/
303 static void ucvector_init_buffer(ucvector
* p
, unsigned char* buffer
, size_t size
)
306 p
->allocsize
= p
->size
= size
;
308 #endif /*LODEPNG_COMPILE_ZLIB*/
310 #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
311 /*returns 1 if success, 0 if failure ==> nothing done*/
312 static unsigned ucvector_push_back(ucvector
* p
, unsigned char c
)
314 if(!ucvector_resize(p
, p
->size
+ 1)) return 0;
315 p
->data
[p
->size
- 1] = c
;
318 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
321 /* ////////////////////////////////////////////////////////////////////////// */
323 #ifdef LODEPNG_COMPILE_PNG
324 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
325 /*returns 1 if success, 0 if failure ==> nothing done*/
326 static unsigned string_resize(char** out
, size_t size
)
328 char* data
= (char*)myrealloc(*out
, size
+ 1);
331 data
[size
] = 0; /*null termination char*/
337 /*init a {char*, size_t} pair for use as string*/
338 static void string_init(char** out
)
341 string_resize(out
, 0);
344 /*free the above pair again*/
345 static void string_cleanup(char** out
)
351 static void string_set(char** out
, const char* in
)
353 size_t insize
= MyStrlen(in
), i
= 0;
354 if(string_resize(out
, insize
))
356 for(i
= 0; i
< insize
; i
++)
362 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
363 #endif /*LODEPNG_COMPILE_PNG*/
365 /* ////////////////////////////////////////////////////////////////////////// */
367 unsigned lodepng_read32bitInt(const unsigned char* buffer
)
369 return (buffer
[0] << 24) | (buffer
[1] << 16) | (buffer
[2] << 8) | buffer
[3];
372 #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
373 /*buffer must have at least 4 allocated bytes available*/
374 static void lodepng_set32bitInt(unsigned char* buffer
, unsigned value
)
376 buffer
[0] = (unsigned char)((value
>> 24) & 0xff);
377 buffer
[1] = (unsigned char)((value
>> 16) & 0xff);
378 buffer
[2] = (unsigned char)((value
>> 8) & 0xff);
379 buffer
[3] = (unsigned char)((value
) & 0xff);
381 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
383 #ifdef LODEPNG_COMPILE_ENCODER
384 static void lodepng_add32bitInt(ucvector
* buffer
, unsigned value
)
386 ucvector_resize(buffer
, buffer
->size
+ 4); /*todo: give error if resize failed*/
387 lodepng_set32bitInt(&buffer
->data
[buffer
->size
- 4], value
);
389 #endif /*LODEPNG_COMPILE_ENCODER*/
391 /* ////////////////////////////////////////////////////////////////////////// */
393 /* ////////////////////////////////////////////////////////////////////////// */
395 #ifdef LODEPNG_COMPILE_DISK
397 unsigned lodepng_load_file(unsigned char** out
, size_t* outsize
, const char* filename
)
402 /*provide some proper output values if error will happen*/
406 file
= fopen(filename
, "rb");
410 fseek(file
, 0 , SEEK_END
);
414 /*read contents of the file into the vector*/
416 *out
= (unsigned char*)mymalloc((size_t)size
);
417 if(size
&& (*out
)) (*outsize
) = fread(*out
, 1, (size_t)size
, file
);
420 if(!(*out
) && size
) return 83; /*the above malloc failed*/
424 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
425 unsigned lodepng_save_file(const unsigned char* buffer
, size_t buffersize
, const char* filename
)
428 file
= fopen(filename
, "wb" );
430 fwrite((char*)buffer
, 1 , buffersize
, file
);
435 #endif /*LODEPNG_COMPILE_DISK*/
437 /* ////////////////////////////////////////////////////////////////////////// */
438 /* ////////////////////////////////////////////////////////////////////////// */
439 /* // End of common code and tools. Begin of Zlib related code. // */
440 /* ////////////////////////////////////////////////////////////////////////// */
441 /* ////////////////////////////////////////////////////////////////////////// */
443 #ifdef LODEPNG_COMPILE_ZLIB
444 #ifdef LODEPNG_COMPILE_ENCODER
445 /*TODO: this ignores potential out of memory errors*/
446 static void addBitToStream(size_t* bitpointer
, ucvector
* bitstream
, unsigned char bit
)
448 /*add a new byte at the end*/
449 if((*bitpointer
) % 8 == 0) ucvector_push_back(bitstream
, (unsigned char)0);
450 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
451 (bitstream
->data
[bitstream
->size
- 1]) |= (bit
<< ((*bitpointer
) & 0x7));
455 static void addBitsToStream(size_t* bitpointer
, ucvector
* bitstream
, unsigned value
, size_t nbits
)
458 for(i
= 0; i
< nbits
; i
++) addBitToStream(bitpointer
, bitstream
, (unsigned char)((value
>> i
) & 1));
461 static void addBitsToStreamReversed(size_t* bitpointer
, ucvector
* bitstream
, unsigned value
, size_t nbits
)
464 for(i
= 0; i
< nbits
; i
++) addBitToStream(bitpointer
, bitstream
, (unsigned char)((value
>> (nbits
- 1 - i
)) & 1));
466 #endif /*LODEPNG_COMPILE_ENCODER*/
468 #ifdef LODEPNG_COMPILE_DECODER
470 #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
472 static unsigned char readBitFromStream(size_t* bitpointer
, const unsigned char* bitstream
)
474 unsigned char result
= (unsigned char)(READBIT(*bitpointer
, bitstream
));
479 static unsigned readBitsFromStream(size_t* bitpointer
, const unsigned char* bitstream
, size_t nbits
)
481 unsigned result
= 0, i
;
482 for(i
= 0; i
< nbits
; i
++)
484 result
+= ((unsigned)READBIT(*bitpointer
, bitstream
)) << i
;
489 #endif /*LODEPNG_COMPILE_DECODER*/
491 /* ////////////////////////////////////////////////////////////////////////// */
492 /* / Deflate - Huffman / */
493 /* ////////////////////////////////////////////////////////////////////////// */
495 #define FIRST_LENGTH_CODE_INDEX 257
496 #define LAST_LENGTH_CODE_INDEX 285
497 /*256 literals, the end code, some length codes, and 2 unused codes*/
498 #define NUM_DEFLATE_CODE_SYMBOLS 288
499 /*the distance codes have their own symbols, 30 used, 2 unused*/
500 #define NUM_DISTANCE_SYMBOLS 32
501 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
502 #define NUM_CODE_LENGTH_CODES 19
504 /*the base lengths represented by codes 257-285*/
505 static const unsigned LENGTHBASE
[29]
506 = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
507 67, 83, 99, 115, 131, 163, 195, 227, 258};
509 /*the extra bits used by codes 257-285 (added to base length)*/
510 static const unsigned LENGTHEXTRA
[29]
511 = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
512 4, 4, 4, 4, 5, 5, 5, 5, 0};
514 /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
515 static const unsigned DISTANCEBASE
[30]
516 = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
517 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
519 /*the extra bits of backwards distances (added to base)*/
520 static const unsigned DISTANCEEXTRA
[30]
521 = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
522 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
524 /*the order in which "code length alphabet code lengths" are stored, out of this
525 the huffman tree of the dynamic huffman tree lengths is generated*/
526 static const unsigned CLCL_ORDER
[NUM_CODE_LENGTH_CODES
]
527 = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
529 /* ////////////////////////////////////////////////////////////////////////// */
532 Huffman tree struct, containing multiple representations of the tree
535 typedef struct HuffmanTree
539 unsigned* lengths
; /*the lengths of the codes of the 1d-tree*/
540 unsigned maxbitlen
; /*maximum number of bits a single code can get*/
541 unsigned numcodes
; /*number of symbols in the alphabet = number of codes*/
544 /*function used for debug purposes to draw the tree in ascii art with C++*/
545 /*#include <iostream>
546 static void HuffmanTree_draw(HuffmanTree* tree)
548 std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
549 for(size_t i = 0; i < tree->tree1d.size; i++)
551 if(tree->lengths.data[i])
552 std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
554 std::cout << std::endl;
557 static void HuffmanTree_init(HuffmanTree
* tree
)
564 static void HuffmanTree_cleanup(HuffmanTree
* tree
)
566 myfree(tree
->tree2d
);
567 myfree(tree
->tree1d
);
568 myfree(tree
->lengths
);
571 /*the tree representation used by the decoder. return value is error*/
572 static unsigned HuffmanTree_make2DTree(HuffmanTree
* tree
)
574 unsigned nodefilled
= 0; /*up to which node it is filled*/
575 unsigned treepos
= 0; /*position in the tree (1 of the numcodes columns)*/
578 tree
->tree2d
= (unsigned*)mymalloc(tree
->numcodes
* 2 * sizeof(unsigned));
579 if(!tree
->tree2d
) return 83; /*alloc fail*/
582 convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
583 uninited, a value >= numcodes is an address to another bit, a value < numcodes
584 is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
585 many columns as codes - 1.
586 A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
587 Here, the internal nodes are stored (what their 0 and 1 option point to).
588 There is only memory for such good tree currently, if there are more nodes
589 (due to too long length codes), error 55 will happen
591 for(n
= 0; n
< tree
->numcodes
* 2; n
++)
593 tree
->tree2d
[n
] = 32767; /*32767 here means the tree2d isn't filled there yet*/
596 for(n
= 0; n
< tree
->numcodes
; n
++) /*the codes*/
598 for(i
= 0; i
< tree
->lengths
[n
]; i
++) /*the bits for this code*/
600 unsigned char bit
= (unsigned char)((tree
->tree1d
[n
] >> (tree
->lengths
[n
] - i
- 1)) & 1);
601 if(treepos
> tree
->numcodes
- 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/
602 if(tree
->tree2d
[2 * treepos
+ bit
] == 32767) /*not yet filled in*/
604 if(i
+ 1 == tree
->lengths
[n
]) /*last bit*/
606 tree
->tree2d
[2 * treepos
+ bit
] = n
; /*put the current code in it*/
611 /*put address of the next step in here, first that address has to be found of course
612 (it's just nodefilled + 1)...*/
614 /*addresses encoded with numcodes added to it*/
615 tree
->tree2d
[2 * treepos
+ bit
] = nodefilled
+ tree
->numcodes
;
616 treepos
= nodefilled
;
619 else treepos
= tree
->tree2d
[2 * treepos
+ bit
] - tree
->numcodes
;
623 for(n
= 0; n
< tree
->numcodes
* 2; n
++)
625 if(tree
->tree2d
[n
] == 32767) tree
->tree2d
[n
] = 0; /*remove possible remaining 32767's*/
632 Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
633 numcodes, lengths and maxbitlen must already be filled in correctly. return
636 static unsigned HuffmanTree_makeFromLengths2(HuffmanTree
* tree
)
640 unsigned bits
, n
, error
= 0;
642 uivector_init(&blcount
);
643 uivector_init(&nextcode
);
645 tree
->tree1d
= (unsigned*)mymalloc(tree
->numcodes
* sizeof(unsigned));
646 if(!tree
->tree1d
) error
= 83; /*alloc fail*/
648 if(!uivector_resizev(&blcount
, tree
->maxbitlen
+ 1, 0)
649 || !uivector_resizev(&nextcode
, tree
->maxbitlen
+ 1, 0))
650 error
= 83; /*alloc fail*/
654 /*step 1: count number of instances of each code length*/
655 for(bits
= 0; bits
< tree
->numcodes
; bits
++) blcount
.data
[tree
->lengths
[bits
]]++;
656 /*step 2: generate the nextcode values*/
657 for(bits
= 1; bits
<= tree
->maxbitlen
; bits
++)
659 nextcode
.data
[bits
] = (nextcode
.data
[bits
- 1] + blcount
.data
[bits
- 1]) << 1;
661 /*step 3: generate all the codes*/
662 for(n
= 0; n
< tree
->numcodes
; n
++)
664 if(tree
->lengths
[n
] != 0) tree
->tree1d
[n
] = nextcode
.data
[tree
->lengths
[n
]]++;
668 uivector_cleanup(&blcount
);
669 uivector_cleanup(&nextcode
);
671 if(!error
) return HuffmanTree_make2DTree(tree
);
676 given the code lengths (as stored in the PNG file), generate the tree as defined
677 by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
678 return value is error.
680 static unsigned HuffmanTree_makeFromLengths(HuffmanTree
* tree
, const unsigned* bitlen
,
681 size_t numcodes
, unsigned maxbitlen
)
684 tree
->lengths
= (unsigned*)mymalloc(numcodes
* sizeof(unsigned));
685 if(!tree
->lengths
) return 83; /*alloc fail*/
686 for(i
= 0; i
< numcodes
; i
++) tree
->lengths
[i
] = bitlen
[i
];
687 tree
->numcodes
= (unsigned)numcodes
; /*number of symbols*/
688 tree
->maxbitlen
= maxbitlen
;
689 return HuffmanTree_makeFromLengths2(tree
);
692 #ifdef LODEPNG_COMPILE_ENCODER
695 A coin, this is the terminology used for the package-merge algorithm and the
696 coin collector's problem. This is used to generate the huffman tree.
697 A coin can be multiple coins (when they're merged)
702 float weight
; /*the sum of all weights in this coin*/
705 static void coin_init(Coin
* c
)
707 uivector_init(&c
->symbols
);
710 /*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/
711 static void coin_cleanup(void* c
)
713 uivector_cleanup(&((Coin
*)c
)->symbols
);
716 static void coin_copy(Coin
* c1
, const Coin
* c2
)
718 c1
->weight
= c2
->weight
;
719 uivector_copy(&c1
->symbols
, &c2
->symbols
);
722 static void add_coins(Coin
* c1
, const Coin
* c2
)
725 for(i
= 0; i
< c2
->symbols
.size
; i
++) uivector_push_back(&c1
->symbols
, c2
->symbols
.data
[i
]);
726 c1
->weight
+= c2
->weight
;
729 static void init_coins(Coin
* coins
, size_t num
)
732 for(i
= 0; i
< num
; i
++) coin_init(&coins
[i
]);
735 static void cleanup_coins(Coin
* coins
, size_t num
)
738 for(i
= 0; i
< num
; i
++) coin_cleanup(&coins
[i
]);
742 This uses a simple combsort to sort the data. This function is not critical for
743 overall encoding speed and the data amount isn't that large.
745 static void sort_coins(Coin
* data
, size_t amount
)
748 unsigned char swapped
= 0;
749 while((gap
> 1) || swapped
)
752 gap
= (gap
* 10) / 13; /*shrink factor 1.3*/
753 if(gap
== 9 || gap
== 10) gap
= 11; /*combsort11*/
756 for(i
= 0; i
< amount
- gap
; i
++)
759 if(data
[j
].weight
< data
[i
].weight
)
761 float temp
= data
[j
].weight
; data
[j
].weight
= data
[i
].weight
; data
[i
].weight
= temp
;
762 uivector_swap(&data
[i
].symbols
, &data
[j
].symbols
);
769 static unsigned append_symbol_coins(Coin
* coins
, const unsigned* frequencies
, unsigned numcodes
, size_t sum
)
772 unsigned j
= 0; /*index of present symbols*/
773 for(i
= 0; i
< numcodes
; i
++)
775 if(frequencies
[i
] != 0) /*only include symbols that are present*/
777 coins
[j
].weight
= frequencies
[i
] / (float)sum
;
778 uivector_push_back(&coins
[j
].symbols
, i
);
785 unsigned lodepng_huffman_code_lengths(unsigned* lengths
, const unsigned* frequencies
,
786 size_t numcodes
, unsigned maxbitlen
)
789 size_t sum
= 0, numpresent
= 0;
791 Coin
* coins
; /*the coins of the currently calculated row*/
792 Coin
* prev_row
; /*the previous row of coins*/
796 if(numcodes
== 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
798 for(i
= 0; i
< numcodes
; i
++)
800 if(frequencies
[i
] > 0)
803 sum
+= frequencies
[i
];
807 for(i
= 0; i
< numcodes
; i
++) lengths
[i
] = 0;
809 /*ensure at least two present symbols. There should be at least one symbol
810 according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To
811 make these work as well ensure there are at least two symbols. The
812 Package-Merge code below also doesn't work correctly if there's only one
813 symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
816 lengths
[0] = lengths
[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
818 else if(numpresent
== 1)
820 for(i
= 0; i
< numcodes
; i
++)
825 lengths
[i
== 0 ? 1 : 0] = 1;
832 /*Package-Merge algorithm represented by coin collector's problem
833 For every symbol, maxbitlen coins will be created*/
835 coinmem
= numpresent
* 2; /*max amount of coins needed with the current algo*/
836 coins
= (Coin
*)mymalloc(sizeof(Coin
) * coinmem
);
837 prev_row
= (Coin
*)mymalloc(sizeof(Coin
) * coinmem
);
838 if(!coins
|| !prev_row
) return 83; /*alloc fail*/
839 init_coins(coins
, coinmem
);
840 init_coins(prev_row
, coinmem
);
842 /*first row, lowest denominator*/
843 error
= append_symbol_coins(coins
, frequencies
, numcodes
, sum
);
844 numcoins
= numpresent
;
845 sort_coins(coins
, numcoins
);
848 unsigned numprev
= 0;
849 for(j
= 1; j
<= maxbitlen
&& !error
; j
++) /*each of the remaining rows*/
853 /*swap prev_row and coins, and their amounts*/
854 tempcoins
= prev_row
; prev_row
= coins
; coins
= tempcoins
;
855 tempnum
= numprev
; numprev
= numcoins
; numcoins
= tempnum
;
857 cleanup_coins(coins
, numcoins
);
858 init_coins(coins
, numcoins
);
862 /*fill in the merged coins of the previous row*/
863 for(i
= 0; i
+ 1 < numprev
; i
+= 2)
865 /*merge prev_row[i] and prev_row[i + 1] into new coin*/
866 Coin
* coin
= &coins
[numcoins
++];
867 coin_copy(coin
, &prev_row
[i
]);
868 add_coins(coin
, &prev_row
[i
+ 1]);
870 /*fill in all the original symbols again*/
873 error
= append_symbol_coins(coins
+ numcoins
, frequencies
, numcodes
, sum
);
874 numcoins
+= numpresent
;
876 sort_coins(coins
, numcoins
);
882 /*calculate the lenghts of each symbol, as the amount of times a coin of each symbol is used*/
883 for(i
= 0; i
< numpresent
- 1; i
++)
885 Coin
* coin
= &coins
[i
];
886 for(j
= 0; j
< coin
->symbols
.size
; j
++) lengths
[coin
->symbols
.data
[j
]]++;
890 cleanup_coins(coins
, coinmem
);
892 cleanup_coins(prev_row
, coinmem
);
899 /*Create the Huffman tree given the symbol frequencies*/
900 static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree
* tree
, const unsigned* frequencies
,
901 size_t mincodes
, size_t numcodes
, unsigned maxbitlen
)
904 while(!frequencies
[numcodes
- 1] && numcodes
> mincodes
) numcodes
--; /*trim zeroes*/
905 tree
->maxbitlen
= maxbitlen
;
906 tree
->numcodes
= (unsigned)numcodes
; /*number of symbols*/
907 tree
->lengths
= (unsigned*)myrealloc(tree
->lengths
, numcodes
* sizeof(unsigned));
908 if(!tree
->lengths
) return 83; /*alloc fail*/
909 /*initialize all lengths to 0*/
910 SetMem(tree
->lengths
, numcodes
* sizeof(unsigned), 0);
912 error
= lodepng_huffman_code_lengths(tree
->lengths
, frequencies
, numcodes
, maxbitlen
);
913 if(!error
) error
= HuffmanTree_makeFromLengths2(tree
);
917 static unsigned HuffmanTree_getCode(const HuffmanTree
* tree
, unsigned index
)
919 return tree
->tree1d
[index
];
922 static unsigned HuffmanTree_getLength(const HuffmanTree
* tree
, unsigned index
)
924 return tree
->lengths
[index
];
926 #endif /*LODEPNG_COMPILE_ENCODER*/
928 /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
929 static unsigned generateFixedLitLenTree(HuffmanTree
* tree
)
931 unsigned i
, error
= 0;
932 unsigned* bitlen
= (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS
* sizeof(unsigned));
933 if(!bitlen
) return 83; /*alloc fail*/
935 /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
936 for(i
= 0; i
<= 143; i
++) bitlen
[i
] = 8;
937 for(i
= 144; i
<= 255; i
++) bitlen
[i
] = 9;
938 for(i
= 256; i
<= 279; i
++) bitlen
[i
] = 7;
939 for(i
= 280; i
<= 287; i
++) bitlen
[i
] = 8;
941 error
= HuffmanTree_makeFromLengths(tree
, bitlen
, NUM_DEFLATE_CODE_SYMBOLS
, 15);
947 /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
948 static unsigned generateFixedDistanceTree(HuffmanTree
* tree
)
950 unsigned i
, error
= 0;
951 unsigned* bitlen
= (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS
* sizeof(unsigned));
952 if(!bitlen
) return 83; /*alloc fail*/
954 /*there are 32 distance codes, but 30-31 are unused*/
955 for(i
= 0; i
< NUM_DISTANCE_SYMBOLS
; i
++) bitlen
[i
] = 5;
956 error
= HuffmanTree_makeFromLengths(tree
, bitlen
, NUM_DISTANCE_SYMBOLS
, 15);
962 #ifdef LODEPNG_COMPILE_DECODER
965 returns the code, or (unsigned)(-1) if error happened
966 inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
968 static unsigned huffmanDecodeSymbol(const unsigned char* in
, size_t* bp
,
969 const HuffmanTree
* codetree
, size_t inbitlength
)
971 unsigned treepos
= 0, ct
;
974 if(*bp
>= inbitlength
) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
976 decode the symbol from the tree. The "readBitFromStream" code is inlined in
977 the expression below because this is the biggest bottleneck while decoding
979 ct
= codetree
->tree2d
[(treepos
<< 1) + READBIT(*bp
, in
)];
981 if(ct
< codetree
->numcodes
) return ct
; /*the symbol is decoded, return it*/
982 else treepos
= ct
- codetree
->numcodes
; /*symbol not yet decoded, instead move tree position*/
984 if(treepos
>= codetree
->numcodes
) return (unsigned)(-1); /*error: it appeared outside the codetree*/
987 #endif /*LODEPNG_COMPILE_DECODER*/
989 #ifdef LODEPNG_COMPILE_DECODER
991 /* ////////////////////////////////////////////////////////////////////////// */
992 /* / Inflator (Decompressor) / */
993 /* ////////////////////////////////////////////////////////////////////////// */
995 /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
996 static void getTreeInflateFixed(HuffmanTree
* tree_ll
, HuffmanTree
* tree_d
)
998 /*TODO: check for out of memory errors*/
999 generateFixedLitLenTree(tree_ll
);
1000 generateFixedDistanceTree(tree_d
);
1003 /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
1004 static unsigned getTreeInflateDynamic(HuffmanTree
* tree_ll
, HuffmanTree
* tree_d
,
1005 const unsigned char* in
, size_t* bp
, size_t inlength
)
1007 /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
1009 unsigned n
, HLIT
, HDIST
, HCLEN
, i
;
1010 size_t inbitlength
= inlength
* 8;
1012 /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
1013 unsigned* bitlen_ll
= 0; /*lit,len code lengths*/
1014 unsigned* bitlen_d
= 0; /*dist code lengths*/
1015 /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
1016 unsigned* bitlen_cl
= 0;
1017 HuffmanTree tree_cl
; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
1019 if((*bp
) >> 3 >= inlength
- 2) return 49; /*error: the bit pointer is or will go past the memory*/
1021 /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
1022 HLIT
= readBitsFromStream(bp
, in
, 5) + 257;
1023 /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
1024 HDIST
= readBitsFromStream(bp
, in
, 5) + 1;
1025 /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
1026 HCLEN
= readBitsFromStream(bp
, in
, 4) + 4;
1028 HuffmanTree_init(&tree_cl
);
1032 /*read the code length codes out of 3 * (amount of code length codes) bits*/
1034 bitlen_cl
= (unsigned*)mymalloc(NUM_CODE_LENGTH_CODES
* sizeof(unsigned));
1035 if(!bitlen_cl
) ERROR_BREAK(83 /*alloc fail*/);
1037 for(i
= 0; i
< NUM_CODE_LENGTH_CODES
; i
++)
1039 if(i
< HCLEN
) bitlen_cl
[CLCL_ORDER
[i
]] = readBitsFromStream(bp
, in
, 3);
1040 else bitlen_cl
[CLCL_ORDER
[i
]] = 0; /*if not, it must stay 0*/
1043 error
= HuffmanTree_makeFromLengths(&tree_cl
, bitlen_cl
, NUM_CODE_LENGTH_CODES
, 7);
1046 /*now we can use this tree to read the lengths for the tree that this function will return*/
1047 bitlen_ll
= (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS
* sizeof(unsigned));
1048 bitlen_d
= (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS
* sizeof(unsigned));
1049 if(!bitlen_ll
|| !bitlen_d
) ERROR_BREAK(83 /*alloc fail*/);
1050 for(i
= 0; i
< NUM_DEFLATE_CODE_SYMBOLS
; i
++) bitlen_ll
[i
] = 0;
1051 for(i
= 0; i
< NUM_DISTANCE_SYMBOLS
; i
++) bitlen_d
[i
] = 0;
1053 /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1055 while(i
< HLIT
+ HDIST
)
1057 unsigned code
= huffmanDecodeSymbol(in
, bp
, &tree_cl
, inbitlength
);
1058 if(code
<= 15) /*a length code*/
1060 if(i
< HLIT
) bitlen_ll
[i
] = code
;
1061 else bitlen_d
[i
- HLIT
] = code
;
1064 else if(code
== 16) /*repeat previous*/
1066 unsigned replength
= 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1067 unsigned value
; /*set value to the previous code*/
1069 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1070 if (i
== 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1072 replength
+= readBitsFromStream(bp
, in
, 2);
1074 if(i
< HLIT
+ 1) value
= bitlen_ll
[i
- 1];
1075 else value
= bitlen_d
[i
- HLIT
- 1];
1076 /*repeat this value in the next lengths*/
1077 for(n
= 0; n
< replength
; n
++)
1079 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1080 if(i
< HLIT
) bitlen_ll
[i
] = value
;
1081 else bitlen_d
[i
- HLIT
] = value
;
1085 else if(code
== 17) /*repeat "0" 3-10 times*/
1087 unsigned replength
= 3; /*read in the bits that indicate repeat length*/
1088 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1090 replength
+= readBitsFromStream(bp
, in
, 3);
1092 /*repeat this value in the next lengths*/
1093 for(n
= 0; n
< replength
; n
++)
1095 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1097 if(i
< HLIT
) bitlen_ll
[i
] = 0;
1098 else bitlen_d
[i
- HLIT
] = 0;
1102 else if(code
== 18) /*repeat "0" 11-138 times*/
1104 unsigned replength
= 11; /*read in the bits that indicate repeat length*/
1105 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1107 replength
+= readBitsFromStream(bp
, in
, 7);
1109 /*repeat this value in the next lengths*/
1110 for(n
= 0; n
< replength
; n
++)
1112 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1114 if(i
< HLIT
) bitlen_ll
[i
] = 0;
1115 else bitlen_d
[i
- HLIT
] = 0;
1119 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1121 if(code
== (unsigned)(-1))
1123 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1124 (10=no endcode, 11=wrong jump outside of tree)*/
1125 error
= (*bp
) > inbitlength
? 10 : 11;
1127 else error
= 16; /*unexisting code, this can never happen*/
1133 if(bitlen_ll
[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1135 /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1136 error
= HuffmanTree_makeFromLengths(tree_ll
, bitlen_ll
, NUM_DEFLATE_CODE_SYMBOLS
, 15);
1138 error
= HuffmanTree_makeFromLengths(tree_d
, bitlen_d
, NUM_DISTANCE_SYMBOLS
, 15);
1140 break; /*end of error-while*/
1146 HuffmanTree_cleanup(&tree_cl
);
1151 /*inflate a block with dynamic of fixed Huffman tree*/
1152 static unsigned inflateHuffmanBlock(ucvector
* out
, const unsigned char* in
, size_t* bp
,
1153 size_t* pos
, size_t inlength
, unsigned btype
)
1156 HuffmanTree tree_ll
; /*the huffman tree for literal and length codes*/
1157 HuffmanTree tree_d
; /*the huffman tree for distance codes*/
1158 size_t inbitlength
= inlength
* 8;
1160 HuffmanTree_init(&tree_ll
);
1161 HuffmanTree_init(&tree_d
);
1163 if(btype
== 1) getTreeInflateFixed(&tree_ll
, &tree_d
);
1164 else if(btype
== 2) error
= getTreeInflateDynamic(&tree_ll
, &tree_d
, in
, bp
, inlength
);
1166 while(!error
) /*decode all symbols until end reached, breaks at end code*/
1168 /*code_ll is literal, length or end code*/
1169 unsigned code_ll
= huffmanDecodeSymbol(in
, bp
, &tree_ll
, inbitlength
);
1170 if(code_ll
<= 255) /*literal symbol*/
1172 if((*pos
) >= out
->size
)
1174 /*reserve more room at once*/
1175 if(!ucvector_resize(out
, ((*pos
) + 1) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1177 out
->data
[(*pos
)] = (unsigned char)(code_ll
);
1180 else if(code_ll
>= FIRST_LENGTH_CODE_INDEX
&& code_ll
<= LAST_LENGTH_CODE_INDEX
) /*length code*/
1182 unsigned code_d
, distance
;
1183 unsigned numextrabits_l
, numextrabits_d
; /*extra bits for length and distance*/
1184 size_t start
, forward
, backward
, length
;
1186 /*part 1: get length base*/
1187 length
= LENGTHBASE
[code_ll
- FIRST_LENGTH_CODE_INDEX
];
1189 /*part 2: get extra bits and add the value of that to length*/
1190 numextrabits_l
= LENGTHEXTRA
[code_ll
- FIRST_LENGTH_CODE_INDEX
];
1191 if(*bp
>= inbitlength
) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1192 length
+= readBitsFromStream(bp
, in
, numextrabits_l
);
1194 /*part 3: get distance code*/
1195 code_d
= huffmanDecodeSymbol(in
, bp
, &tree_d
, inbitlength
);
1198 if(code_ll
== (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1200 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1201 (10=no endcode, 11=wrong jump outside of tree)*/
1202 error
= (*bp
) > inlength
* 8 ? 10 : 11;
1204 else error
= 18; /*error: invalid distance code (30-31 are never used)*/
1207 distance
= DISTANCEBASE
[code_d
];
1209 /*part 4: get extra bits from distance*/
1210 numextrabits_d
= DISTANCEEXTRA
[code_d
];
1211 if(*bp
>= inbitlength
) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1213 distance
+= readBitsFromStream(bp
, in
, numextrabits_d
);
1215 /*part 5: fill in all the out[n] values based on the length and dist*/
1217 if(distance
> start
) ERROR_BREAK(52); /*too long backward distance*/
1218 backward
= start
- distance
;
1219 if((*pos
) + length
>= out
->size
)
1221 /*reserve more room at once*/
1222 if(!ucvector_resize(out
, ((*pos
) + length
) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1225 for(forward
= 0; forward
< length
; forward
++)
1227 out
->data
[(*pos
)] = out
->data
[backward
];
1230 if(backward
>= start
) backward
= start
- distance
;
1233 else if(code_ll
== 256)
1235 break; /*end code, break the loop*/
1237 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1239 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1240 (10=no endcode, 11=wrong jump outside of tree)*/
1241 error
= (*bp
) > inlength
* 8 ? 10 : 11;
1246 HuffmanTree_cleanup(&tree_ll
);
1247 HuffmanTree_cleanup(&tree_d
);
1252 static unsigned inflateNoCompression(ucvector
* out
, const unsigned char* in
, size_t* bp
, size_t* pos
, size_t inlength
)
1254 /*go to first boundary of byte*/
1256 unsigned LEN
, NLEN
, n
, error
= 0;
1257 while(((*bp
) & 0x7) != 0) (*bp
)++;
1258 p
= (*bp
) / 8; /*byte position*/
1260 /*read LEN (2 bytes) and NLEN (2 bytes)*/
1261 if(p
>= inlength
- 4) return 52; /*error, bit pointer will jump past memory*/
1262 LEN
= in
[p
] + 256 * in
[p
+ 1]; p
+= 2;
1263 NLEN
= in
[p
] + 256 * in
[p
+ 1]; p
+= 2;
1265 /*check if 16-bit NLEN is really the one's complement of LEN*/
1266 if(LEN
+ NLEN
!= 65535) return 21; /*error: NLEN is not one's complement of LEN*/
1268 if((*pos
) + LEN
>= out
->size
)
1270 if(!ucvector_resize(out
, (*pos
) + LEN
)) return 83; /*alloc fail*/
1273 /*read the literal data: LEN bytes are now stored in the out buffer*/
1274 if(p
+ LEN
> inlength
) return 23; /*error: reading outside of in buffer*/
1275 for(n
= 0; n
< LEN
; n
++) out
->data
[(*pos
)++] = in
[p
++];
1282 static unsigned lodepng_inflatev(ucvector
* out
,
1283 const unsigned char* in
, size_t insize
,
1284 const LodePNGDecompressSettings
* settings
)
1286 /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1288 unsigned BFINAL
= 0;
1289 size_t pos
= 0; /*byte position in the out buffer*/
1298 if(bp
+ 2 >= insize
* 8) return 52; /*error, bit pointer will jump past memory*/
1299 BFINAL
= readBitFromStream(&bp
, in
);
1300 BTYPE
= 1 * readBitFromStream(&bp
, in
);
1301 BTYPE
+= 2 * readBitFromStream(&bp
, in
);
1303 if(BTYPE
== 3) return 20; /*error: invalid BTYPE*/
1304 else if(BTYPE
== 0) error
= inflateNoCompression(out
, in
, &bp
, &pos
, insize
); /*no compression*/
1305 else error
= inflateHuffmanBlock(out
, in
, &bp
, &pos
, insize
, BTYPE
); /*compression, BTYPE 01 or 10*/
1307 if(error
) return error
;
1310 /*Only now we know the true size of out, resize it to that*/
1311 if(!ucvector_resize(out
, pos
)) error
= 83; /*alloc fail*/
1316 unsigned lodepng_inflate(unsigned char** out
, size_t* outsize
,
1317 const unsigned char* in
, size_t insize
,
1318 const LodePNGDecompressSettings
* settings
)
1322 ucvector_init_buffer(&v
, *out
, *outsize
);
1323 error
= lodepng_inflatev(&v
, in
, insize
, settings
);
1329 static unsigned inflate(unsigned char** out
, size_t* outsize
,
1330 const unsigned char* in
, size_t insize
,
1331 const LodePNGDecompressSettings
* settings
)
1333 if(settings
->custom_inflate
)
1335 return settings
->custom_inflate(out
, outsize
, in
, insize
, settings
);
1339 return lodepng_inflate(out
, outsize
, in
, insize
, settings
);
1343 #endif /*LODEPNG_COMPILE_DECODER*/
1345 #ifdef LODEPNG_COMPILE_ENCODER
1347 /* ////////////////////////////////////////////////////////////////////////// */
1348 /* / Deflator (Compressor) / */
1349 /* ////////////////////////////////////////////////////////////////////////// */
1351 static const size_t MAX_SUPPORTED_DEFLATE_LENGTH
= 258;
1353 /*bitlen is the size in bits of the code*/
1354 static void addHuffmanSymbol(size_t* bp
, ucvector
* compressed
, unsigned code
, unsigned bitlen
)
1356 addBitsToStreamReversed(bp
, compressed
, code
, bitlen
);
1359 /*search the index in the array, that has the largest value smaller than or equal to the given value,
1360 given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1361 static size_t searchCodeIndex(const unsigned* array
, size_t array_size
, size_t value
)
1363 /*linear search implementation*/
1364 /*for(size_t i = 1; i < array_size; i++) if(array[i] > value) return i - 1;
1365 return array_size - 1;*/
1367 /*binary search implementation (not that much faster) (precondition: array_size > 0)*/
1369 size_t right
= array_size
- 1;
1370 while(left
<= right
)
1372 size_t mid
= (left
+ right
) / 2;
1373 if(array
[mid
] <= value
) left
= mid
+ 1; /*the value to find is more to the right*/
1374 else if(array
[mid
- 1] > value
) right
= mid
- 1; /*the value to find is more to the left*/
1375 else return mid
- 1;
1377 return array_size
- 1;
1380 static void addLengthDistance(uivector
* values
, size_t length
, size_t distance
)
1382 /*values in encoded vector are those used by deflate:
1383 0-255: literal bytes
1385 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1388 unsigned length_code
= (unsigned)searchCodeIndex(LENGTHBASE
, 29, length
);
1389 unsigned extra_length
= (unsigned)(length
- LENGTHBASE
[length_code
]);
1390 unsigned dist_code
= (unsigned)searchCodeIndex(DISTANCEBASE
, 30, distance
);
1391 unsigned extra_distance
= (unsigned)(distance
- DISTANCEBASE
[dist_code
]);
1393 uivector_push_back(values
, length_code
+ FIRST_LENGTH_CODE_INDEX
);
1394 uivector_push_back(values
, extra_length
);
1395 uivector_push_back(values
, dist_code
);
1396 uivector_push_back(values
, extra_distance
);
1399 static const unsigned HASH_NUM_VALUES
= 65536;
1400 static const unsigned HASH_NUM_CHARACTERS
= 3;
1401 static const unsigned HASH_SHIFT
= 2;
1403 The HASH_NUM_CHARACTERS value is used to make encoding faster by using longer
1404 sequences to generate a hash value from the stream bytes. Setting it to 3
1405 gives exactly the same compression as the brute force method, since deflate's
1406 run length encoding starts with lengths of 3. Setting it to higher values,
1407 like 6, can make the encoding faster (not always though!), but will cause the
1408 encoding to miss any length between 3 and this value, so that the compression
1409 may be worse (but this can vary too depending on the image, sometimes it is
1410 even a bit better instead).
1411 The HASH_NUM_VALUES is the amount of unique possible hash values that
1412 combinations of bytes can give, the higher it is the more memory is needed, but
1413 if it's too low the advantage of hashing is gone.
1419 int* head
; /*hash value to head circular pos*/
1420 int* val
; /*circular pos to hash value*/
1421 /*circular pos to prev circular pos*/
1426 static unsigned hash_init(Hash
* hash
, unsigned windowsize
)
1429 hash
->head
= (int*)mymalloc(sizeof(int) * HASH_NUM_VALUES
);
1430 hash
->val
= (int*)mymalloc(sizeof(int) * windowsize
);
1431 hash
->chain
= (UINT16
*)mymalloc(sizeof(UINT16
) * windowsize
);
1432 hash
->zeros
= (UINT16
*)mymalloc(sizeof(UINT16
) * windowsize
);
1434 if(!hash
->head
|| !hash
->val
|| !hash
->chain
|| !hash
->zeros
) return 83; /*alloc fail*/
1436 /*initialize hash table*/
1437 for(i
= 0; i
< HASH_NUM_VALUES
; i
++) hash
->head
[i
] = -1;
1438 for(i
= 0; i
< windowsize
; i
++) hash
->val
[i
] = -1;
1439 for(i
= 0; i
< windowsize
; i
++) hash
->chain
[i
] = i
; /*same value as index indicates uninitialized*/
1444 static void hash_cleanup(Hash
* hash
)
1448 myfree(hash
->chain
);
1449 myfree(hash
->zeros
);
1452 static unsigned getHash(const unsigned char* data
, size_t size
, size_t pos
)
1454 unsigned result
= 0;
1456 if(pos
>= size
) return 0;
1457 amount
= HASH_NUM_CHARACTERS
;
1458 if(pos
+ amount
>= size
) amount
= size
- pos
;
1459 for(i
= 0; i
< amount
; i
++) result
^= (data
[pos
+ i
] << (i
* HASH_SHIFT
));
1460 return result
% HASH_NUM_VALUES
;
1463 static unsigned countZeros(const unsigned char* data
, size_t size
, size_t pos
)
1465 const unsigned char* start
= data
+ pos
;
1466 const unsigned char* end
= start
+ MAX_SUPPORTED_DEFLATE_LENGTH
;
1467 if(end
> data
+ size
) end
= data
+ size
;
1469 while (data
!= end
&& *data
== 0) data
++;
1470 /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1471 return (unsigned)(data
- start
);
1474 static void updateHashChain(Hash
* hash
, size_t pos
, int hashval
, unsigned windowsize
)
1476 unsigned wpos
= pos
% windowsize
;
1477 hash
->val
[wpos
] = hashval
;
1478 if(hash
->head
[hashval
] != -1) hash
->chain
[wpos
] = hash
->head
[hashval
];
1479 hash
->head
[hashval
] = wpos
;
1483 LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1484 is in the form of unsigned integers with codes representing for example literal bytes, or
1485 length/distance pairs.
1486 It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1487 sliding window (of windowsize) is used, and all past bytes in that window can be used as
1488 the "dictionary". A brute force search through all possible distances would be slow, and
1489 this hash technique is one out of several ways to speed this up.
1491 static unsigned encodeLZ77(uivector
* out
, Hash
* hash
,
1492 const unsigned char* in
, size_t inpos
, size_t insize
, unsigned windowsize
,
1493 unsigned minmatch
, unsigned nicematch
, unsigned lazymatching
)
1495 UINT16 numzeros
= 0;
1496 int usezeros
= windowsize
>= 8192; /*for small window size, the 'max chain length' optimization does a better job*/
1497 unsigned pos
, i
, error
= 0;
1498 /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1499 unsigned maxchainlength
= windowsize
>= 8192 ? windowsize
: windowsize
/ 8;
1500 unsigned maxlazymatch
= windowsize
>= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH
: 64;
1504 unsigned offset
; /*the offset represents the distance in LZ77 terminology*/
1507 unsigned lazylength
= 0, lazyoffset
= 0;
1509 unsigned current_offset
, current_length
;
1510 const unsigned char *lastptr
, *foreptr
, *backptr
;
1511 UINT16 hashpos
, prevpos
;
1513 for(pos
= inpos
; pos
< insize
; pos
++)
1515 size_t wpos
= pos
% windowsize
; /*position for in 'circular' hash buffers*/
1517 hashval
= getHash(in
, insize
, pos
);
1518 updateHashChain(hash
, pos
, hashval
, windowsize
);
1520 if(usezeros
&& hashval
== 0)
1522 numzeros
= countZeros(in
, insize
, pos
);
1523 hash
->zeros
[wpos
] = numzeros
;
1526 /*the length and offset found for the current position*/
1530 prevpos
= hash
->head
[hashval
];
1531 hashpos
= hash
->chain
[prevpos
];
1533 lastptr
= &in
[insize
< pos
+ MAX_SUPPORTED_DEFLATE_LENGTH
? insize
: pos
+ MAX_SUPPORTED_DEFLATE_LENGTH
];
1535 /*search for the longest string*/
1536 if(hash
->val
[wpos
] == (int)hashval
)
1538 unsigned chainlength
= 0;
1541 /*stop when went completely around the circular buffer*/
1542 if(prevpos
< wpos
&& hashpos
> prevpos
&& hashpos
<= wpos
) break;
1543 if(prevpos
> wpos
&& (hashpos
<= wpos
|| hashpos
> prevpos
)) break;
1544 if(chainlength
++ >= maxchainlength
) break;
1546 current_offset
= hashpos
<= wpos
? wpos
- hashpos
: wpos
- hashpos
+ windowsize
;
1547 if(current_offset
> 0)
1549 /*test the next characters*/
1551 backptr
= &in
[pos
- current_offset
];
1553 /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1554 if(usezeros
&& hashval
== 0 && hash
->val
[hashpos
] == 0 /*hashval[hashpos] may be out of date*/)
1556 UINT16 skip
= hash
->zeros
[hashpos
];
1557 if(skip
> numzeros
) skip
= numzeros
;
1562 /* multiple checks at once per array bounds check */
1563 while(foreptr
!= lastptr
&& *backptr
== *foreptr
) /*maximum supported length by deflate is max length*/
1568 current_length
= (unsigned)(foreptr
- &in
[pos
]);
1570 if(current_length
> length
)
1572 length
= current_length
; /*the longest length*/
1573 offset
= current_offset
; /*the offset that is related to this longest length*/
1574 /*jump out once a length of max length is found (speed gain)*/
1575 if(current_length
>= nicematch
|| current_length
== MAX_SUPPORTED_DEFLATE_LENGTH
) break;
1579 if(hashpos
== hash
->chain
[hashpos
]) break;
1582 hashpos
= hash
->chain
[hashpos
];
1588 if(!lazy
&& length
>= 3 && length
<= maxlazymatch
&& length
< MAX_SUPPORTED_DEFLATE_LENGTH
)
1591 lazylength
= length
;
1592 lazyoffset
= offset
;
1593 continue; /*try the next byte*/
1598 if(pos
== 0) ERROR_BREAK(81);
1599 if(length
> lazylength
+ 1)
1601 /*push the previous character as literal*/
1602 if(!uivector_push_back(out
, in
[pos
- 1])) ERROR_BREAK(83 /*alloc fail*/);
1606 length
= lazylength
;
1607 offset
= lazyoffset
;
1608 hash
->head
[hashval
] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1613 if(length
>= 3 && offset
> windowsize
) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1615 /**encode it as length/distance pair or literal value**/
1616 if(length
< 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1618 if(!uivector_push_back(out
, in
[pos
])) ERROR_BREAK(83 /*alloc fail*/);
1620 else if(length
< minmatch
|| (length
== 3 && offset
> 4096))
1622 /*compensate for the fact that longer offsets have more extra bits, a
1623 length of only 3 may be not worth it then*/
1624 if(!uivector_push_back(out
, in
[pos
])) ERROR_BREAK(83 /*alloc fail*/);
1628 addLengthDistance(out
, length
, offset
);
1629 for(i
= 1; i
< length
; i
++)
1632 hashval
= getHash(in
, insize
, pos
);
1633 updateHashChain(hash
, pos
, hashval
, windowsize
);
1634 if(usezeros
&& hashval
== 0)
1636 hash
->zeros
[pos
% windowsize
] = countZeros(in
, insize
, pos
);
1641 } /*end of the loop through each character of input*/
1642 } /*end of "if(!error)"*/
1647 /* /////////////////////////////////////////////////////////////////////////// */
1649 static unsigned deflateNoCompression(ucvector
* out
, const unsigned char* data
, size_t datasize
)
1651 /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1652 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1654 size_t i
, j
, numdeflateblocks
= (datasize
+ 65534) / 65535;
1655 unsigned datapos
= 0;
1656 for(i
= 0; i
< numdeflateblocks
; i
++)
1658 unsigned BFINAL
, BTYPE
, LEN
, NLEN
;
1659 unsigned char firstbyte
;
1661 BFINAL
= (i
== numdeflateblocks
- 1);
1664 firstbyte
= (unsigned char)(BFINAL
+ ((BTYPE
& 1) << 1) + ((BTYPE
& 2) << 1));
1665 ucvector_push_back(out
, firstbyte
);
1668 if(datasize
- datapos
< 65535) LEN
= (unsigned)datasize
- datapos
;
1671 ucvector_push_back(out
, (unsigned char)(LEN
% 256));
1672 ucvector_push_back(out
, (unsigned char)(LEN
/ 256));
1673 ucvector_push_back(out
, (unsigned char)(NLEN
% 256));
1674 ucvector_push_back(out
, (unsigned char)(NLEN
/ 256));
1676 /*Decompressed data*/
1677 for(j
= 0; j
< 65535 && datapos
< datasize
; j
++)
1679 ucvector_push_back(out
, data
[datapos
++]);
1687 write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1688 tree_ll: the tree for lit and len codes.
1689 tree_d: the tree for distance codes.
1691 static void writeLZ77data(size_t* bp
, ucvector
* out
, const uivector
* lz77_encoded
,
1692 const HuffmanTree
* tree_ll
, const HuffmanTree
* tree_d
)
1695 for(i
= 0; i
< lz77_encoded
->size
; i
++)
1697 unsigned val
= lz77_encoded
->data
[i
];
1698 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(tree_ll
, val
), HuffmanTree_getLength(tree_ll
, val
));
1699 if(val
> 256) /*for a length code, 3 more things have to be added*/
1701 unsigned length_index
= val
- FIRST_LENGTH_CODE_INDEX
;
1702 unsigned n_length_extra_bits
= LENGTHEXTRA
[length_index
];
1703 unsigned length_extra_bits
= lz77_encoded
->data
[++i
];
1705 unsigned distance_code
= lz77_encoded
->data
[++i
];
1707 unsigned distance_index
= distance_code
;
1708 unsigned n_distance_extra_bits
= DISTANCEEXTRA
[distance_index
];
1709 unsigned distance_extra_bits
= lz77_encoded
->data
[++i
];
1711 addBitsToStream(bp
, out
, length_extra_bits
, n_length_extra_bits
);
1712 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(tree_d
, distance_code
),
1713 HuffmanTree_getLength(tree_d
, distance_code
));
1714 addBitsToStream(bp
, out
, distance_extra_bits
, n_distance_extra_bits
);
1719 /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1720 static unsigned deflateDynamic(ucvector
* out
, size_t* bp
, Hash
* hash
,
1721 const unsigned char* data
, size_t datapos
, size_t dataend
,
1722 const LodePNGCompressSettings
* settings
, int final
)
1727 A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1728 literal bytes and length/distance pairs. This is then huffman compressed with
1729 two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1730 another huffman tree is used for the dist values ("d"). These two trees are
1731 stored using their code lengths, and to compress even more these code lengths
1732 are also run-length encoded and huffman compressed. This gives a huffman tree
1733 of code lengths "cl". The code lenghts used to describe this third tree are
1734 the code length code lengths ("clcl").
1737 /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1738 uivector lz77_encoded
;
1739 HuffmanTree tree_ll
; /*tree for lit,len values*/
1740 HuffmanTree tree_d
; /*tree for distance codes*/
1741 HuffmanTree tree_cl
; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1742 uivector frequencies_ll
; /*frequency of lit,len codes*/
1743 uivector frequencies_d
; /*frequency of dist codes*/
1744 uivector frequencies_cl
; /*frequency of code length codes*/
1745 uivector bitlen_lld
; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1746 uivector bitlen_lld_e
; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1747 /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1748 (these are written as is in the file, it would be crazy to compress these using yet another huffman
1749 tree that needs to be represented by yet another set of code lengths)*/
1751 size_t datasize
= dataend
- datapos
;
1754 Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1755 bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1756 bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1757 bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1760 unsigned BFINAL
= final
;
1761 size_t numcodes_ll
, numcodes_d
, i
;
1762 unsigned HLIT
, HDIST
, HCLEN
;
1764 uivector_init(&lz77_encoded
);
1765 HuffmanTree_init(&tree_ll
);
1766 HuffmanTree_init(&tree_d
);
1767 HuffmanTree_init(&tree_cl
);
1768 uivector_init(&frequencies_ll
);
1769 uivector_init(&frequencies_d
);
1770 uivector_init(&frequencies_cl
);
1771 uivector_init(&bitlen_lld
);
1772 uivector_init(&bitlen_lld_e
);
1773 uivector_init(&bitlen_cl
);
1775 /*This while loop never loops due to a break at the end, it is here to
1776 allow breaking out of it to the cleanup phase on error conditions.*/
1779 if(settings
->use_lz77
)
1781 error
= encodeLZ77(&lz77_encoded
, hash
, data
, datapos
, dataend
, settings
->windowsize
,
1782 settings
->minmatch
, settings
->nicematch
, settings
->lazymatching
);
1787 if(!uivector_resize(&lz77_encoded
, datasize
)) ERROR_BREAK(83 /*alloc fail*/);
1788 for(i
= datapos
; i
< dataend
; i
++) lz77_encoded
.data
[i
] = data
[i
]; /*no LZ77, but still will be Huffman compressed*/
1791 if(!uivector_resizev(&frequencies_ll
, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
1792 if(!uivector_resizev(&frequencies_d
, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
1794 /*Count the frequencies of lit, len and dist codes*/
1795 for(i
= 0; i
< lz77_encoded
.size
; i
++)
1797 unsigned symbol
= lz77_encoded
.data
[i
];
1798 frequencies_ll
.data
[symbol
]++;
1801 unsigned dist
= lz77_encoded
.data
[i
+ 2];
1802 frequencies_d
.data
[dist
]++;
1806 frequencies_ll
.data
[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1808 /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1809 error
= HuffmanTree_makeFromFrequencies(&tree_ll
, frequencies_ll
.data
, 257, frequencies_ll
.size
, 15);
1811 /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1812 error
= HuffmanTree_makeFromFrequencies(&tree_d
, frequencies_d
.data
, 2, frequencies_d
.size
, 15);
1815 numcodes_ll
= tree_ll
.numcodes
; if(numcodes_ll
> 286) numcodes_ll
= 286;
1816 numcodes_d
= tree_d
.numcodes
; if(numcodes_d
> 30) numcodes_d
= 30;
1817 /*store the code lengths of both generated trees in bitlen_lld*/
1818 for(i
= 0; i
< numcodes_ll
; i
++) uivector_push_back(&bitlen_lld
, HuffmanTree_getLength(&tree_ll
, (unsigned)i
));
1819 for(i
= 0; i
< numcodes_d
; i
++) uivector_push_back(&bitlen_lld
, HuffmanTree_getLength(&tree_d
, (unsigned)i
));
1821 /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1822 17 (3-10 zeroes), 18 (11-138 zeroes)*/
1823 for(i
= 0; i
< (unsigned)bitlen_lld
.size
; i
++)
1825 unsigned j
= 0; /*amount of repititions*/
1826 while(i
+ j
+ 1 < (unsigned)bitlen_lld
.size
&& bitlen_lld
.data
[i
+ j
+ 1] == bitlen_lld
.data
[i
]) j
++;
1828 if(bitlen_lld
.data
[i
] == 0 && j
>= 2) /*repeat code for zeroes*/
1830 j
++; /*include the first zero*/
1831 if(j
<= 10) /*repeat code 17 supports max 10 zeroes*/
1833 uivector_push_back(&bitlen_lld_e
, 17);
1834 uivector_push_back(&bitlen_lld_e
, j
- 3);
1836 else /*repeat code 18 supports max 138 zeroes*/
1838 if(j
> 138) j
= 138;
1839 uivector_push_back(&bitlen_lld_e
, 18);
1840 uivector_push_back(&bitlen_lld_e
, j
- 11);
1844 else if(j
>= 3) /*repeat code for value other than zero*/
1847 unsigned num
= j
/ 6, rest
= j
% 6;
1848 uivector_push_back(&bitlen_lld_e
, bitlen_lld
.data
[i
]);
1849 for(k
= 0; k
< num
; k
++)
1851 uivector_push_back(&bitlen_lld_e
, 16);
1852 uivector_push_back(&bitlen_lld_e
, 6 - 3);
1856 uivector_push_back(&bitlen_lld_e
, 16);
1857 uivector_push_back(&bitlen_lld_e
, rest
- 3);
1862 else /*too short to benefit from repeat code*/
1864 uivector_push_back(&bitlen_lld_e
, bitlen_lld
.data
[i
]);
1868 /*generate tree_cl, the huffmantree of huffmantrees*/
1870 if(!uivector_resizev(&frequencies_cl
, NUM_CODE_LENGTH_CODES
, 0)) ERROR_BREAK(83 /*alloc fail*/);
1871 for(i
= 0; i
< bitlen_lld_e
.size
; i
++)
1873 frequencies_cl
.data
[bitlen_lld_e
.data
[i
]]++;
1874 /*after a repeat code come the bits that specify the number of repetitions,
1875 those don't need to be in the frequencies_cl calculation*/
1876 if(bitlen_lld_e
.data
[i
] >= 16) i
++;
1879 error
= HuffmanTree_makeFromFrequencies(&tree_cl
, frequencies_cl
.data
,
1880 frequencies_cl
.size
, frequencies_cl
.size
, 7);
1883 if(!uivector_resize(&bitlen_cl
, tree_cl
.numcodes
)) ERROR_BREAK(83 /*alloc fail*/);
1884 for(i
= 0; i
< tree_cl
.numcodes
; i
++)
1886 /*lenghts of code length tree is in the order as specified by deflate*/
1887 bitlen_cl
.data
[i
] = HuffmanTree_getLength(&tree_cl
, CLCL_ORDER
[i
]);
1889 while(bitlen_cl
.data
[bitlen_cl
.size
- 1] == 0 && bitlen_cl
.size
> 4)
1891 /*remove zeros at the end, but minimum size must be 4*/
1892 if(!uivector_resize(&bitlen_cl
, bitlen_cl
.size
- 1)) ERROR_BREAK(83 /*alloc fail*/);
1897 Write everything into the output
1899 After the BFINAL and BTYPE, the dynamic block consists out of the following:
1900 - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1901 - (HCLEN+4)*3 bits code lengths of code length alphabet
1902 - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
1903 alphabet, + possible repetition codes 16, 17, 18)
1904 - HDIST + 1 code lengths of distance alphabet (encoded using the code length
1905 alphabet, + possible repetition codes 16, 17, 18)
1910 /*Write block type*/
1911 addBitToStream(bp
, out
, BFINAL
);
1912 addBitToStream(bp
, out
, 0); /*first bit of BTYPE "dynamic"*/
1913 addBitToStream(bp
, out
, 1); /*second bit of BTYPE "dynamic"*/
1915 /*write the HLIT, HDIST and HCLEN values*/
1916 HLIT
= (unsigned)(numcodes_ll
- 257);
1917 HDIST
= (unsigned)(numcodes_d
- 1);
1918 HCLEN
= (unsigned)bitlen_cl
.size
- 4;
1919 /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
1920 while(!bitlen_cl
.data
[HCLEN
+ 4 - 1] && HCLEN
> 0) HCLEN
--;
1921 addBitsToStream(bp
, out
, HLIT
, 5);
1922 addBitsToStream(bp
, out
, HDIST
, 5);
1923 addBitsToStream(bp
, out
, HCLEN
, 4);
1925 /*write the code lenghts of the code length alphabet*/
1926 for(i
= 0; i
< HCLEN
+ 4; i
++) addBitsToStream(bp
, out
, bitlen_cl
.data
[i
], 3);
1928 /*write the lenghts of the lit/len AND the dist alphabet*/
1929 for(i
= 0; i
< bitlen_lld_e
.size
; i
++)
1931 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_cl
, bitlen_lld_e
.data
[i
]),
1932 HuffmanTree_getLength(&tree_cl
, bitlen_lld_e
.data
[i
]));
1933 /*extra bits of repeat codes*/
1934 if(bitlen_lld_e
.data
[i
] == 16) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 2);
1935 else if(bitlen_lld_e
.data
[i
] == 17) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 3);
1936 else if(bitlen_lld_e
.data
[i
] == 18) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 7);
1939 /*write the compressed data symbols*/
1940 writeLZ77data(bp
, out
, &lz77_encoded
, &tree_ll
, &tree_d
);
1941 /*error: the length of the end code 256 must be larger than 0*/
1942 if(HuffmanTree_getLength(&tree_ll
, 256) == 0) ERROR_BREAK(64);
1944 /*write the end code*/
1945 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, 256), HuffmanTree_getLength(&tree_ll
, 256));
1947 break; /*end of error-while*/
1951 uivector_cleanup(&lz77_encoded
);
1952 HuffmanTree_cleanup(&tree_ll
);
1953 HuffmanTree_cleanup(&tree_d
);
1954 HuffmanTree_cleanup(&tree_cl
);
1955 uivector_cleanup(&frequencies_ll
);
1956 uivector_cleanup(&frequencies_d
);
1957 uivector_cleanup(&frequencies_cl
);
1958 uivector_cleanup(&bitlen_lld_e
);
1959 uivector_cleanup(&bitlen_lld
);
1960 uivector_cleanup(&bitlen_cl
);
1965 static unsigned deflateFixed(ucvector
* out
, size_t* bp
, Hash
* hash
,
1966 const unsigned char* data
,
1967 size_t datapos
, size_t dataend
,
1968 const LodePNGCompressSettings
* settings
, int final
)
1970 HuffmanTree tree_ll
; /*tree for literal values and length codes*/
1971 HuffmanTree tree_d
; /*tree for distance codes*/
1973 unsigned BFINAL
= final
;
1977 HuffmanTree_init(&tree_ll
);
1978 HuffmanTree_init(&tree_d
);
1980 generateFixedLitLenTree(&tree_ll
);
1981 generateFixedDistanceTree(&tree_d
);
1983 addBitToStream(bp
, out
, BFINAL
);
1984 addBitToStream(bp
, out
, 1); /*first bit of BTYPE*/
1985 addBitToStream(bp
, out
, 0); /*second bit of BTYPE*/
1987 if(settings
->use_lz77
) /*LZ77 encoded*/
1989 uivector lz77_encoded
;
1990 uivector_init(&lz77_encoded
);
1991 error
= encodeLZ77(&lz77_encoded
, hash
, data
, datapos
, dataend
, settings
->windowsize
,
1992 settings
->minmatch
, settings
->nicematch
, settings
->lazymatching
);
1993 if(!error
) writeLZ77data(bp
, out
, &lz77_encoded
, &tree_ll
, &tree_d
);
1994 uivector_cleanup(&lz77_encoded
);
1996 else /*no LZ77, but still will be Huffman compressed*/
1998 for(i
= datapos
; i
< dataend
; i
++)
2000 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, data
[i
]), HuffmanTree_getLength(&tree_ll
, data
[i
]));
2004 if(!error
) addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, 256), HuffmanTree_getLength(&tree_ll
, 256));
2007 HuffmanTree_cleanup(&tree_ll
);
2008 HuffmanTree_cleanup(&tree_d
);
2013 static unsigned lodepng_deflatev(ucvector
* out
, const unsigned char* in
, size_t insize
,
2014 const LodePNGCompressSettings
* settings
)
2017 size_t i
, blocksize
, numdeflateblocks
;
2018 size_t bp
= 0; /*the bit pointer*/
2021 if(settings
->btype
> 2) return 61;
2022 else if(settings
->btype
== 0) return deflateNoCompression(out
, in
, insize
);
2023 else if(settings
->btype
== 1) blocksize
= insize
;
2024 else /*if(settings->btype == 2)*/
2026 blocksize
= insize
/ 8 + 8;
2027 if(blocksize
< 65535) blocksize
= 65535;
2030 numdeflateblocks
= (insize
+ blocksize
- 1) / blocksize
;
2031 if(numdeflateblocks
== 0) numdeflateblocks
= 1;
2033 error
= hash_init(&hash
, settings
->windowsize
);
2034 if(error
) return error
;
2036 for(i
= 0; i
< numdeflateblocks
&& !error
; i
++)
2038 int final
= i
== numdeflateblocks
- 1;
2039 size_t start
= i
* blocksize
;
2040 size_t end
= start
+ blocksize
;
2041 if(end
> insize
) end
= insize
;
2043 if(settings
->btype
== 1) error
= deflateFixed(out
, &bp
, &hash
, in
, start
, end
, settings
, final
);
2044 else if(settings
->btype
== 2) error
= deflateDynamic(out
, &bp
, &hash
, in
, start
, end
, settings
, final
);
2047 hash_cleanup(&hash
);
2052 unsigned lodepng_deflate(unsigned char** out
, size_t* outsize
,
2053 const unsigned char* in
, size_t insize
,
2054 const LodePNGCompressSettings
* settings
)
2058 ucvector_init_buffer(&v
, *out
, *outsize
);
2059 error
= lodepng_deflatev(&v
, in
, insize
, settings
);
2065 static unsigned deflate(unsigned char** out
, size_t* outsize
,
2066 const unsigned char* in
, size_t insize
,
2067 const LodePNGCompressSettings
* settings
)
2069 if(settings
->custom_deflate
)
2071 return settings
->custom_deflate(out
, outsize
, in
, insize
, settings
);
2075 return lodepng_deflate(out
, outsize
, in
, insize
, settings
);
2079 #endif /*LODEPNG_COMPILE_DECODER*/
2081 /* ////////////////////////////////////////////////////////////////////////// */
2083 /* ////////////////////////////////////////////////////////////////////////// */
2085 static unsigned update_adler32(unsigned adler
, const unsigned char* data
, unsigned len
)
2087 unsigned s1
= adler
& 0xffff;
2088 unsigned s2
= (adler
>> 16) & 0xffff;
2092 /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2093 unsigned amount
= len
> 5550 ? 5550 : len
;
2105 return (s2
<< 16) | s1
;
2108 /*Return the adler32 of the bytes data[0..len-1]*/
2109 static unsigned adler32(const unsigned char* data
, unsigned len
)
2111 return update_adler32(1L, data
, len
);
2114 /* ////////////////////////////////////////////////////////////////////////// */
2116 /* ////////////////////////////////////////////////////////////////////////// */
2118 #ifdef LODEPNG_COMPILE_DECODER
2120 unsigned lodepng_zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2121 size_t insize
, const LodePNGDecompressSettings
* settings
)
2124 unsigned CM
, CINFO
, FDICT
;
2126 if(insize
< 2) return 53; /*error, size of zlib data too small*/
2127 /*read information from zlib header*/
2128 if((in
[0] * 256 + in
[1]) % 31 != 0)
2130 /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2135 CINFO
= (in
[0] >> 4) & 15;
2136 /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2137 FDICT
= (in
[1] >> 5) & 1;
2138 /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2140 if(CM
!= 8 || CINFO
> 7)
2142 /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2147 /*error: the specification of PNG says about the zlib stream:
2148 "The additional flags shall not specify a preset dictionary."*/
2152 error
= inflate(out
, outsize
, in
+ 2, insize
- 2, settings
);
2153 if(error
) return error
;
2155 if(!settings
->ignore_adler32
)
2157 unsigned ADLER32
= lodepng_read32bitInt(&in
[insize
- 4]);
2158 unsigned checksum
= adler32(*out
, (unsigned)(*outsize
));
2159 if(checksum
!= ADLER32
) return 58; /*error, adler checksum not correct, data must be corrupted*/
2162 return 0; /*no error*/
2165 static unsigned zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2166 size_t insize
, const LodePNGDecompressSettings
* settings
)
2168 if(settings
->custom_zlib
)
2169 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2171 return lodepng_zlib_decompress(out
, outsize
, in
, insize
, settings
);
2174 #endif /*LODEPNG_COMPILE_DECODER*/
2176 #ifdef LODEPNG_COMPILE_ENCODER
2178 unsigned lodepng_zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2179 size_t insize
, const LodePNGCompressSettings
* settings
)
2181 /*initially, *out must be NULL and outsize 0, if you just give some random *out
2182 that's pointing to a non allocated buffer, this'll crash*/
2186 unsigned char* deflatedata
= 0;
2187 size_t deflatesize
= 0;
2190 /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2191 unsigned CMF
= 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2192 unsigned FLEVEL
= 0;
2194 unsigned CMFFLG
= 256 * CMF
+ FDICT
* 32 + FLEVEL
* 64;
2195 unsigned FCHECK
= 31 - CMFFLG
% 31;
2198 /*ucvector-controlled version of the output buffer, for dynamic array*/
2199 ucvector_init_buffer(&outv
, *out
, *outsize
);
2201 ucvector_push_back(&outv
, (unsigned char)(CMFFLG
/ 256));
2202 ucvector_push_back(&outv
, (unsigned char)(CMFFLG
% 256));
2204 error
= deflate(&deflatedata
, &deflatesize
, in
, insize
, settings
);
2208 ADLER32
= adler32(in
, (unsigned)insize
);
2209 for(i
= 0; i
< deflatesize
; i
++) ucvector_push_back(&outv
, deflatedata
[i
]);
2210 myfree(deflatedata
);
2211 lodepng_add32bitInt(&outv
, ADLER32
);
2215 *outsize
= outv
.size
;
2220 /* compress using the default or custom zlib function */
2221 static unsigned zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2222 size_t insize
, const LodePNGCompressSettings
* settings
)
2224 if(settings
->custom_zlib
)
2226 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2230 return lodepng_zlib_compress(out
, outsize
, in
, insize
, settings
);
2234 #endif /*LODEPNG_COMPILE_ENCODER*/
2236 #else /*no LODEPNG_COMPILE_ZLIB*/
2238 #ifdef LODEPNG_COMPILE_DECODER
2239 static unsigned zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2240 size_t insize
, const LodePNGDecompressSettings
* settings
)
2242 if (!settings
->custom_zlib
) return 87; /*no custom zlib function provided */
2243 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2245 #endif /*LODEPNG_COMPILE_DECODER*/
2246 #ifdef LODEPNG_COMPILE_ENCODER
2247 static unsigned zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2248 size_t insize
, const LodePNGCompressSettings
* settings
)
2250 if (!settings
->custom_zlib
) return 87; /*no custom zlib function provided */
2251 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2253 #endif /*LODEPNG_COMPILE_ENCODER*/
2255 #endif /*LODEPNG_COMPILE_ZLIB*/
2257 /* ////////////////////////////////////////////////////////////////////////// */
2259 #ifdef LODEPNG_COMPILE_ENCODER
2261 /*this is a good tradeoff between speed and compression ratio*/
2262 #define DEFAULT_WINDOWSIZE 2048
2264 void lodepng_compress_settings_init(LodePNGCompressSettings
* settings
)
2266 /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2267 settings
->btype
= 2;
2268 settings
->use_lz77
= 1;
2269 settings
->windowsize
= DEFAULT_WINDOWSIZE
;
2270 settings
->minmatch
= 3;
2271 settings
->nicematch
= 128;
2272 settings
->lazymatching
= 1;
2274 settings
->custom_zlib
= 0;
2275 settings
->custom_deflate
= 0;
2276 settings
->custom_context
= 0;
2279 const LodePNGCompressSettings lodepng_default_compress_settings
= {2, 1, DEFAULT_WINDOWSIZE
, 3, 128, 1, 0, 0, 0};
2282 #endif /*LODEPNG_COMPILE_ENCODER*/
2284 #ifdef LODEPNG_COMPILE_DECODER
2286 void lodepng_decompress_settings_init(LodePNGDecompressSettings
* settings
)
2288 settings
->ignore_adler32
= 0;
2290 settings
->custom_zlib
= 0;
2291 settings
->custom_inflate
= 0;
2292 settings
->custom_context
= 0;
2295 const LodePNGDecompressSettings lodepng_default_decompress_settings
= {0, 0, 0, 0};
2297 #endif /*LODEPNG_COMPILE_DECODER*/
2299 /* ////////////////////////////////////////////////////////////////////////// */
2300 /* ////////////////////////////////////////////////////////////////////////// */
2301 /* // End of Zlib related code. Begin of PNG related code. // */
2302 /* ////////////////////////////////////////////////////////////////////////// */
2303 /* ////////////////////////////////////////////////////////////////////////// */
2305 #ifdef LODEPNG_COMPILE_PNG
2307 /* ////////////////////////////////////////////////////////////////////////// */
2309 /* ////////////////////////////////////////////////////////////////////////// */
2311 static unsigned Crc32_crc_table_computed
= 0;
2312 static unsigned Crc32_crc_table
[256];
2314 /*Make the table for a fast CRC.*/
2315 static void Crc32_make_crc_table(void)
2318 for(n
= 0; n
< 256; n
++)
2321 for(k
= 0; k
< 8; k
++)
2323 if(c
& 1) c
= 0xedb88320L
^ (c
>> 1);
2326 Crc32_crc_table
[n
] = c
;
2328 Crc32_crc_table_computed
= 1;
2331 /*Update a running CRC with the bytes buf[0..len-1]--the CRC should be
2332 initialized to all 1's, and the transmitted value is the 1's complement of the
2333 final running CRC (see the crc() routine below).*/
2334 static unsigned Crc32_update_crc(const unsigned char* buf
, unsigned crc
, size_t len
)
2339 if(!Crc32_crc_table_computed
) Crc32_make_crc_table();
2340 for(n
= 0; n
< len
; n
++)
2342 c
= Crc32_crc_table
[(c
^ buf
[n
]) & 0xff] ^ (c
>> 8);
2347 /*Return the CRC of the bytes buf[0..len-1].*/
2348 unsigned lodepng_crc32(const unsigned char* buf
, size_t len
)
2350 return Crc32_update_crc(buf
, 0xffffffffL
, len
) ^ 0xffffffffL
;
2353 /* ////////////////////////////////////////////////////////////////////////// */
2354 /* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2355 /* ////////////////////////////////////////////////////////////////////////// */
2357 static unsigned char readBitFromReversedStream(size_t* bitpointer
, const unsigned char* bitstream
)
2359 unsigned char result
= (unsigned char)((bitstream
[(*bitpointer
) >> 3] >> (7 - ((*bitpointer
) & 0x7))) & 1);
2364 static unsigned readBitsFromReversedStream(size_t* bitpointer
, const unsigned char* bitstream
, size_t nbits
)
2366 unsigned result
= 0;
2368 for(i
= nbits
- 1; i
< nbits
; i
--)
2370 result
+= (unsigned)readBitFromReversedStream(bitpointer
, bitstream
) << i
;
2375 #ifdef LODEPNG_COMPILE_DECODER
2376 static void setBitOfReversedStream0(size_t* bitpointer
, unsigned char* bitstream
, unsigned char bit
)
2378 /*the current bit in bitstream must be 0 for this to work*/
2381 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2382 bitstream
[(*bitpointer
) >> 3] |= (bit
<< (7 - ((*bitpointer
) & 0x7)));
2386 #endif /*LODEPNG_COMPILE_DECODER*/
2388 static void setBitOfReversedStream(size_t* bitpointer
, unsigned char* bitstream
, unsigned char bit
)
2390 /*the current bit in bitstream may be 0 or 1 for this to work*/
2391 if(bit
== 0) bitstream
[(*bitpointer
) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer
) & 0x7))));
2392 else bitstream
[(*bitpointer
) >> 3] |= (1 << (7 - ((*bitpointer
) & 0x7)));
2396 /* ////////////////////////////////////////////////////////////////////////// */
2397 /* / PNG chunks / */
2398 /* ////////////////////////////////////////////////////////////////////////// */
2400 unsigned lodepng_chunk_length(const unsigned char* chunk
)
2402 return lodepng_read32bitInt(&chunk
[0]);
2405 void lodepng_chunk_type(char type
[5], const unsigned char* chunk
)
2408 for(i
= 0; i
< 4; i
++) type
[i
] = chunk
[4 + i
];
2409 type
[4] = 0; /*null termination char*/
2412 unsigned char lodepng_chunk_type_equals(const unsigned char* chunk
, const char* type
)
2414 if(MyStrlen(type
) != 4) return 0;
2415 return (chunk
[4] == type
[0] && chunk
[5] == type
[1] && chunk
[6] == type
[2] && chunk
[7] == type
[3]);
2418 unsigned char lodepng_chunk_ancillary(const unsigned char* chunk
)
2420 return((chunk
[4] & 32) != 0);
2423 unsigned char lodepng_chunk_private(const unsigned char* chunk
)
2425 return((chunk
[6] & 32) != 0);
2428 unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk
)
2430 return((chunk
[7] & 32) != 0);
2433 unsigned char* lodepng_chunk_data(unsigned char* chunk
)
2438 const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk
)
2443 unsigned lodepng_chunk_check_crc(const unsigned char* chunk
)
2445 unsigned length
= lodepng_chunk_length(chunk
);
2446 unsigned CRC
= lodepng_read32bitInt(&chunk
[length
+ 8]);
2447 /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2448 unsigned checksum
= lodepng_crc32(&chunk
[4], length
+ 4);
2449 if(CRC
!= checksum
) return 1;
2453 void lodepng_chunk_generate_crc(unsigned char* chunk
)
2455 unsigned length
= lodepng_chunk_length(chunk
);
2456 unsigned CRC
= lodepng_crc32(&chunk
[4], length
+ 4);
2457 lodepng_set32bitInt(chunk
+ 8 + length
, CRC
);
2460 unsigned char* lodepng_chunk_next(unsigned char* chunk
)
2462 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2463 return &chunk
[total_chunk_length
];
2466 const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk
)
2468 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2469 return &chunk
[total_chunk_length
];
2472 unsigned lodepng_chunk_append(unsigned char** out
, size_t* outlength
, const unsigned char* chunk
)
2475 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2476 unsigned char *chunk_start
, *new_buffer
;
2477 size_t new_length
= (*outlength
) + total_chunk_length
;
2478 if(new_length
< total_chunk_length
|| new_length
< (*outlength
)) return 77; /*integer overflow happened*/
2480 new_buffer
= (unsigned char*)myrealloc(*out
, new_length
);
2481 if(!new_buffer
) return 83; /*alloc fail*/
2482 (*out
) = new_buffer
;
2483 (*outlength
) = new_length
;
2484 chunk_start
= &(*out
)[new_length
- total_chunk_length
];
2486 for(i
= 0; i
< total_chunk_length
; i
++) chunk_start
[i
] = chunk
[i
];
2491 unsigned lodepng_chunk_create(unsigned char** out
, size_t* outlength
, unsigned length
,
2492 const char* type
, const unsigned char* data
)
2495 unsigned char *chunk
, *new_buffer
;
2496 size_t new_length
= (*outlength
) + length
+ 12;
2497 if(new_length
< length
+ 12 || new_length
< (*outlength
)) return 77; /*integer overflow happened*/
2498 new_buffer
= (unsigned char*)myrealloc(*out
, new_length
);
2499 if(!new_buffer
) return 83; /*alloc fail*/
2500 (*out
) = new_buffer
;
2501 (*outlength
) = new_length
;
2502 chunk
= &(*out
)[(*outlength
) - length
- 12];
2505 lodepng_set32bitInt(chunk
, (unsigned)length
);
2507 /*2: chunk name (4 letters)*/
2514 for(i
= 0; i
< length
; i
++) chunk
[8 + i
] = data
[i
];
2516 /*4: CRC (of the chunkname characters and the data)*/
2517 lodepng_chunk_generate_crc(chunk
);
2522 /* ////////////////////////////////////////////////////////////////////////// */
2523 /* / Color types and such / */
2524 /* ////////////////////////////////////////////////////////////////////////// */
2526 /*return type is a LodePNG error code*/
2527 static unsigned checkColorValidity(LodePNGColorType colortype
, unsigned bd
) /*bd = bitdepth*/
2531 case 0: if(!(bd
== 1 || bd
== 2 || bd
== 4 || bd
== 8 || bd
== 16)) return 37; break; /*grey*/
2532 case 2: if(!( bd
== 8 || bd
== 16)) return 37; break; /*RGB*/
2533 case 3: if(!(bd
== 1 || bd
== 2 || bd
== 4 || bd
== 8 )) return 37; break; /*palette*/
2534 case 4: if(!( bd
== 8 || bd
== 16)) return 37; break; /*grey + alpha*/
2535 case 6: if(!( bd
== 8 || bd
== 16)) return 37; break; /*RGBA*/
2538 return 0; /*allowed color type / bits combination*/
2541 static unsigned getNumColorChannels(LodePNGColorType colortype
)
2545 case 0: return 1; /*grey*/
2546 case 2: return 3; /*RGB*/
2547 case 3: return 1; /*palette*/
2548 case 4: return 2; /*grey + alpha*/
2549 case 6: return 4; /*RGBA*/
2551 return 0; /*unexisting color type*/
2554 static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype
, unsigned bitdepth
)
2556 /*bits per pixel is amount of channels * bits per channel*/
2557 return getNumColorChannels(colortype
) * bitdepth
;
2560 /* ////////////////////////////////////////////////////////////////////////// */
2562 void lodepng_color_mode_init(LodePNGColorMode
* info
)
2564 info
->key_defined
= 0;
2565 info
->key_r
= info
->key_g
= info
->key_b
= 0;
2566 info
->colortype
= LCT_RGBA
;
2569 info
->palettesize
= 0;
2572 void lodepng_color_mode_cleanup(LodePNGColorMode
* info
)
2574 lodepng_palette_clear(info
);
2577 unsigned lodepng_color_mode_copy(LodePNGColorMode
* dest
, const LodePNGColorMode
* source
)
2580 lodepng_color_mode_cleanup(dest
);
2584 dest
->palette
= (unsigned char*)mymalloc(source
->palettesize
* 4);
2585 if(!dest
->palette
&& source
->palettesize
) return 83; /*alloc fail*/
2586 for(i
= 0; i
< source
->palettesize
* 4; i
++) dest
->palette
[i
] = source
->palette
[i
];
2591 static int lodepng_color_mode_equal(const LodePNGColorMode
* a
, const LodePNGColorMode
* b
)
2594 if(a
->colortype
!= b
->colortype
) return 0;
2595 if(a
->bitdepth
!= b
->bitdepth
) return 0;
2596 if(a
->key_defined
!= b
->key_defined
) return 0;
2599 if(a
->key_r
!= b
->key_r
) return 0;
2600 if(a
->key_g
!= b
->key_g
) return 0;
2601 if(a
->key_b
!= b
->key_b
) return 0;
2603 if(a
->palettesize
!= b
->palettesize
) return 0;
2604 for(i
= 0; i
< a
->palettesize
* 4; i
++)
2606 if(a
->palette
[i
] != b
->palette
[i
]) return 0;
2611 void lodepng_palette_clear(LodePNGColorMode
* info
)
2613 if(info
->palette
) myfree(info
->palette
);
2614 info
->palettesize
= 0;
2617 unsigned lodepng_palette_add(LodePNGColorMode
* info
,
2618 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
2620 unsigned char* data
;
2621 /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2622 the max of 256 colors, it'll have the exact alloc size*/
2623 if(!(info
->palettesize
& (info
->palettesize
- 1))) /*if palettesize is 0 or a power of two*/
2625 /*allocated data must be at least 4* palettesize (for 4 color bytes)*/
2626 size_t alloc_size
= info
->palettesize
== 0 ? 4 : info
->palettesize
* 4 * 2;
2627 data
= (unsigned char*)myrealloc(info
->palette
, alloc_size
);
2628 if(!data
) return 83; /*alloc fail*/
2629 else info
->palette
= data
;
2631 info
->palette
[4 * info
->palettesize
+ 0] = r
;
2632 info
->palette
[4 * info
->palettesize
+ 1] = g
;
2633 info
->palette
[4 * info
->palettesize
+ 2] = b
;
2634 info
->palette
[4 * info
->palettesize
+ 3] = a
;
2635 info
->palettesize
++;
2639 unsigned lodepng_get_bpp(const LodePNGColorMode
* info
)
2641 /*calculate bits per pixel out of colortype and bitdepth*/
2642 return lodepng_get_bpp_lct(info
->colortype
, info
->bitdepth
);
2645 unsigned lodepng_get_channels(const LodePNGColorMode
* info
)
2647 return getNumColorChannels(info
->colortype
);
2650 unsigned lodepng_is_greyscale_type(const LodePNGColorMode
* info
)
2652 return info
->colortype
== LCT_GREY
|| info
->colortype
== LCT_GREY_ALPHA
;
2655 unsigned lodepng_is_alpha_type(const LodePNGColorMode
* info
)
2657 return (info
->colortype
& 4) != 0; /*4 or 6*/
2660 unsigned lodepng_is_palette_type(const LodePNGColorMode
* info
)
2662 return info
->colortype
== LCT_PALETTE
;
2665 unsigned lodepng_has_palette_alpha(const LodePNGColorMode
* info
)
2668 for(i
= 0; i
< info
->palettesize
; i
++)
2670 if(info
->palette
[i
* 4 + 3] < 255) return 1;
2675 unsigned lodepng_can_have_alpha(const LodePNGColorMode
* info
)
2677 return info
->key_defined
2678 || lodepng_is_alpha_type(info
)
2679 || lodepng_has_palette_alpha(info
);
2682 size_t lodepng_get_raw_size(unsigned w
, unsigned h
, const LodePNGColorMode
* color
)
2684 return (w
* h
* lodepng_get_bpp(color
) + 7) / 8;
2687 size_t lodepng_get_raw_size_lct(unsigned w
, unsigned h
, LodePNGColorType colortype
, unsigned bitdepth
)
2689 return (w
* h
* lodepng_get_bpp_lct(colortype
, bitdepth
) + 7) / 8;
2692 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2694 static void LodePNGUnknownChunks_init(LodePNGInfo
* info
)
2697 for(i
= 0; i
< 3; i
++) info
->unknown_chunks_data
[i
] = 0;
2698 for(i
= 0; i
< 3; i
++) info
->unknown_chunks_size
[i
] = 0;
2701 static void LodePNGUnknownChunks_cleanup(LodePNGInfo
* info
)
2704 for(i
= 0; i
< 3; i
++) myfree(info
->unknown_chunks_data
[i
]);
2707 static unsigned LodePNGUnknownChunks_copy(LodePNGInfo
* dest
, const LodePNGInfo
* src
)
2711 LodePNGUnknownChunks_cleanup(dest
);
2713 for(i
= 0; i
< 3; i
++)
2716 dest
->unknown_chunks_size
[i
] = src
->unknown_chunks_size
[i
];
2717 dest
->unknown_chunks_data
[i
] = (unsigned char*)mymalloc(src
->unknown_chunks_size
[i
]);
2718 if(!dest
->unknown_chunks_data
[i
] && dest
->unknown_chunks_size
[i
]) return 83; /*alloc fail*/
2719 for(j
= 0; j
< src
->unknown_chunks_size
[i
]; j
++)
2721 dest
->unknown_chunks_data
[i
][j
] = src
->unknown_chunks_data
[i
][j
];
2728 /******************************************************************************/
2730 static void LodePNGText_init(LodePNGInfo
* info
)
2733 info
->text_keys
= NULL
;
2734 info
->text_strings
= NULL
;
2737 static void LodePNGText_cleanup(LodePNGInfo
* info
)
2740 for(i
= 0; i
< info
->text_num
; i
++)
2742 string_cleanup(&info
->text_keys
[i
]);
2743 string_cleanup(&info
->text_strings
[i
]);
2745 myfree(info
->text_keys
);
2746 myfree(info
->text_strings
);
2749 static unsigned LodePNGText_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2752 dest
->text_keys
= 0;
2753 dest
->text_strings
= 0;
2755 for(i
= 0; i
< source
->text_num
; i
++)
2757 CERROR_TRY_RETURN(lodepng_add_text(dest
, source
->text_keys
[i
], source
->text_strings
[i
]));
2762 void lodepng_clear_text(LodePNGInfo
* info
)
2764 LodePNGText_cleanup(info
);
2767 unsigned lodepng_add_text(LodePNGInfo
* info
, const char* key
, const char* str
)
2769 char** new_keys
= (char**)(myrealloc(info
->text_keys
, sizeof(char*) * (info
->text_num
+ 1)));
2770 char** new_strings
= (char**)(myrealloc(info
->text_strings
, sizeof(char*) * (info
->text_num
+ 1)));
2771 if(!new_keys
|| !new_strings
)
2774 myfree(new_strings
);
2775 return 83; /*alloc fail*/
2779 info
->text_keys
= new_keys
;
2780 info
->text_strings
= new_strings
;
2782 string_init(&info
->text_keys
[info
->text_num
- 1]);
2783 string_set(&info
->text_keys
[info
->text_num
- 1], key
);
2785 string_init(&info
->text_strings
[info
->text_num
- 1]);
2786 string_set(&info
->text_strings
[info
->text_num
- 1], str
);
2791 /******************************************************************************/
2793 static void LodePNGIText_init(LodePNGInfo
* info
)
2795 info
->itext_num
= 0;
2796 info
->itext_keys
= NULL
;
2797 info
->itext_langtags
= NULL
;
2798 info
->itext_transkeys
= NULL
;
2799 info
->itext_strings
= NULL
;
2802 static void LodePNGIText_cleanup(LodePNGInfo
* info
)
2805 for(i
= 0; i
< info
->itext_num
; i
++)
2807 string_cleanup(&info
->itext_keys
[i
]);
2808 string_cleanup(&info
->itext_langtags
[i
]);
2809 string_cleanup(&info
->itext_transkeys
[i
]);
2810 string_cleanup(&info
->itext_strings
[i
]);
2812 myfree(info
->itext_keys
);
2813 myfree(info
->itext_langtags
);
2814 myfree(info
->itext_transkeys
);
2815 myfree(info
->itext_strings
);
2818 static unsigned LodePNGIText_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2821 dest
->itext_keys
= 0;
2822 dest
->itext_langtags
= 0;
2823 dest
->itext_transkeys
= 0;
2824 dest
->itext_strings
= 0;
2825 dest
->itext_num
= 0;
2826 for(i
= 0; i
< source
->itext_num
; i
++)
2828 CERROR_TRY_RETURN(lodepng_add_itext(dest
, source
->itext_keys
[i
], source
->itext_langtags
[i
],
2829 source
->itext_transkeys
[i
], source
->itext_strings
[i
]));
2834 void lodepng_clear_itext(LodePNGInfo
* info
)
2836 LodePNGIText_cleanup(info
);
2839 unsigned lodepng_add_itext(LodePNGInfo
* info
, const char* key
, const char* langtag
,
2840 const char* transkey
, const char* str
)
2842 char** new_keys
= (char**)(myrealloc(info
->itext_keys
, sizeof(char*) * (info
->itext_num
+ 1)));
2843 char** new_langtags
= (char**)(myrealloc(info
->itext_langtags
, sizeof(char*) * (info
->itext_num
+ 1)));
2844 char** new_transkeys
= (char**)(myrealloc(info
->itext_transkeys
, sizeof(char*) * (info
->itext_num
+ 1)));
2845 char** new_strings
= (char**)(myrealloc(info
->itext_strings
, sizeof(char*) * (info
->itext_num
+ 1)));
2846 if(!new_keys
|| !new_langtags
|| !new_transkeys
|| !new_strings
)
2849 myfree(new_langtags
);
2850 myfree(new_transkeys
);
2851 myfree(new_strings
);
2852 return 83; /*alloc fail*/
2856 info
->itext_keys
= new_keys
;
2857 info
->itext_langtags
= new_langtags
;
2858 info
->itext_transkeys
= new_transkeys
;
2859 info
->itext_strings
= new_strings
;
2861 string_init(&info
->itext_keys
[info
->itext_num
- 1]);
2862 string_set(&info
->itext_keys
[info
->itext_num
- 1], key
);
2864 string_init(&info
->itext_langtags
[info
->itext_num
- 1]);
2865 string_set(&info
->itext_langtags
[info
->itext_num
- 1], langtag
);
2867 string_init(&info
->itext_transkeys
[info
->itext_num
- 1]);
2868 string_set(&info
->itext_transkeys
[info
->itext_num
- 1], transkey
);
2870 string_init(&info
->itext_strings
[info
->itext_num
- 1]);
2871 string_set(&info
->itext_strings
[info
->itext_num
- 1], str
);
2875 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2877 void lodepng_info_init(LodePNGInfo
* info
)
2879 lodepng_color_mode_init(&info
->color
);
2880 info
->interlace_method
= 0;
2881 info
->compression_method
= 0;
2882 info
->filter_method
= 0;
2883 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2884 info
->background_defined
= 0;
2885 info
->background_r
= info
->background_g
= info
->background_b
= 0;
2887 LodePNGText_init(info
);
2888 LodePNGIText_init(info
);
2890 info
->time_defined
= 0;
2891 info
->phys_defined
= 0;
2893 LodePNGUnknownChunks_init(info
);
2894 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2897 void lodepng_info_cleanup(LodePNGInfo
* info
)
2899 lodepng_color_mode_cleanup(&info
->color
);
2900 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2901 LodePNGText_cleanup(info
);
2902 LodePNGIText_cleanup(info
);
2904 LodePNGUnknownChunks_cleanup(info
);
2905 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2908 unsigned lodepng_info_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2910 lodepng_info_cleanup(dest
);
2912 lodepng_color_mode_init(&dest
->color
);
2913 CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest
->color
, &source
->color
));
2915 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2916 CERROR_TRY_RETURN(LodePNGText_copy(dest
, source
));
2917 CERROR_TRY_RETURN(LodePNGIText_copy(dest
, source
));
2919 LodePNGUnknownChunks_init(dest
);
2920 CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest
, source
));
2921 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2925 void lodepng_info_swap(LodePNGInfo
* a
, LodePNGInfo
* b
)
2927 LodePNGInfo temp
= *a
;
2932 /* ////////////////////////////////////////////////////////////////////////// */
2934 /*index: bitgroup index, bits: bitgroup size(1, 2 or 4, in: bitgroup value, out: octet array to add bits to*/
2935 static void addColorBits(unsigned char* out
, size_t index
, unsigned bits
, unsigned in
)
2937 /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2938 unsigned p
= index
% (8 / bits
);
2939 in
&= (1 << bits
) - 1; /*filter out any other bits of the input value*/
2940 in
= in
<< (bits
* (8 / bits
- p
- 1));
2941 if(p
== 0) out
[index
* bits
/ 8] = in
;
2942 else out
[index
* bits
/ 8] |= in
;
2946 typedef struct ColorTree ColorTree
;
2949 One node of a color tree
2950 This is the data structure used to count the number of unique colors and to get a palette
2951 index for a color. It's like an octree, but because the alpha channel is used too, each
2952 node has 16 instead of 8 children.
2956 ColorTree
* children
[16]; /*up to 16 pointers to ColorTree of next level*/
2957 int index
; /*the payload. Only has a meaningful value if this is in the last level*/
2960 static void color_tree_init(ColorTree
* tree
)
2963 for(i
= 0; i
< 16; i
++) tree
->children
[i
] = 0;
2967 static void color_tree_cleanup(ColorTree
* tree
)
2970 for(i
= 0; i
< 16; i
++)
2972 if(tree
->children
[i
])
2974 color_tree_cleanup(tree
->children
[i
]);
2975 myfree(tree
->children
[i
]);
2980 /*returns -1 if color not present, its index otherwise*/
2981 static int color_tree_get(ColorTree
* tree
, unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
2984 for(bit
= 0; bit
< 8; bit
++)
2986 int i
= 8 * ((r
>> bit
) & 1) + 4 * ((g
>> bit
) & 1) + 2 * ((b
>> bit
) & 1) + 1 * ((a
>> bit
) & 1);
2987 if(!tree
->children
[i
]) return -1;
2988 else tree
= tree
->children
[i
];
2990 return tree
? tree
->index
: -1;
2993 #ifdef LODEPNG_COMPILE_ENCODER
2994 static int color_tree_has(ColorTree
* tree
, unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
2996 return color_tree_get(tree
, r
, g
, b
, a
) >= 0;
2998 #endif /*LODEPNG_COMPILE_ENCODER*/
3000 /*color is not allowed to already exist.
3001 Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
3002 static void color_tree_add(ColorTree
* tree
,
3003 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
, int index
)
3006 for(bit
= 0; bit
< 8; bit
++)
3008 int i
= 8 * ((r
>> bit
) & 1) + 4 * ((g
>> bit
) & 1) + 2 * ((b
>> bit
) & 1) + 1 * ((a
>> bit
) & 1);
3009 if(!tree
->children
[i
])
3011 tree
->children
[i
] = (ColorTree
*)mymalloc(sizeof(ColorTree
));
3012 color_tree_init(tree
->children
[i
]);
3014 tree
= tree
->children
[i
];
3016 tree
->index
= index
;
3019 /*put a pixel, given its RGBA color, into image of any color type*/
3020 static unsigned rgba8ToPixel(unsigned char* out
, size_t i
,
3021 const LodePNGColorMode
* mode
, ColorTree
* tree
/*for palette*/,
3022 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
3024 if(mode
->colortype
== LCT_GREY
)
3026 unsigned char grey
= r
; /*((UINT16)r + g + b) / 3*/;
3027 if(mode
->bitdepth
== 8) out
[i
] = grey
;
3028 else if(mode
->bitdepth
== 16) out
[i
* 2 + 0] = out
[i
* 2 + 1] = grey
;
3031 /*take the most significant bits of grey*/
3032 grey
= (grey
>> (8 - mode
->bitdepth
)) & ((1 << mode
->bitdepth
) - 1);
3033 addColorBits(out
, i
, mode
->bitdepth
, grey
);
3036 else if(mode
->colortype
== LCT_RGB
)
3038 if(mode
->bitdepth
== 8)
3046 out
[i
* 6 + 0] = out
[i
* 6 + 1] = r
;
3047 out
[i
* 6 + 2] = out
[i
* 6 + 3] = g
;
3048 out
[i
* 6 + 4] = out
[i
* 6 + 5] = b
;
3051 else if(mode
->colortype
== LCT_PALETTE
)
3053 int index
= color_tree_get(tree
, r
, g
, b
, a
);
3054 if(index
< 0) return 82; /*color not in palette*/
3055 if(mode
->bitdepth
== 8) out
[i
] = index
;
3056 else addColorBits(out
, i
, mode
->bitdepth
, index
);
3058 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3060 unsigned char grey
= r
; /*((UINT16)r + g + b) / 3*/;
3061 if(mode
->bitdepth
== 8)
3063 out
[i
* 2 + 0] = grey
;
3066 else if(mode
->bitdepth
== 16)
3068 out
[i
* 4 + 0] = out
[i
* 4 + 1] = grey
;
3069 out
[i
* 4 + 2] = out
[i
* 4 + 3] = a
;
3072 else if(mode
->colortype
== LCT_RGBA
)
3074 if(mode
->bitdepth
== 8)
3083 out
[i
* 8 + 0] = out
[i
* 8 + 1] = r
;
3084 out
[i
* 8 + 2] = out
[i
* 8 + 3] = g
;
3085 out
[i
* 8 + 4] = out
[i
* 8 + 5] = b
;
3086 out
[i
* 8 + 6] = out
[i
* 8 + 7] = a
;
3090 return 0; /*no error*/
3093 /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3094 static unsigned rgba16ToPixel(unsigned char* out
, size_t i
,
3095 const LodePNGColorMode
* mode
,
3096 UINT16 r
, UINT16 g
, UINT16 b
, UINT16 a
)
3098 if(mode
->bitdepth
!= 16) return 85; /*must be 16 for this function*/
3099 if(mode
->colortype
== LCT_GREY
)
3101 UINT16 grey
= r
; /*((unsigned)r + g + b) / 3*/;
3102 out
[i
* 2 + 0] = (grey
>> 8) & 255;
3103 out
[i
* 2 + 1] = grey
& 255;
3105 else if(mode
->colortype
== LCT_RGB
)
3107 out
[i
* 6 + 0] = (r
>> 8) & 255;
3108 out
[i
* 6 + 1] = r
& 255;
3109 out
[i
* 6 + 2] = (g
>> 8) & 255;
3110 out
[i
* 6 + 3] = g
& 255;
3111 out
[i
* 6 + 4] = (b
>> 8) & 255;
3112 out
[i
* 6 + 5] = b
& 255;
3114 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3116 UINT16 grey
= r
; /*((unsigned)r + g + b) / 3*/;
3117 out
[i
* 4 + 0] = (grey
>> 8) & 255;
3118 out
[i
* 4 + 1] = grey
& 255;
3119 out
[i
* 4 + 2] = (a
>> 8) & 255;
3120 out
[i
* 4 + 3] = a
& 255;
3122 else if(mode
->colortype
== LCT_RGBA
)
3124 out
[i
* 8 + 0] = (r
>> 8) & 255;
3125 out
[i
* 8 + 1] = r
& 255;
3126 out
[i
* 8 + 2] = (g
>> 8) & 255;
3127 out
[i
* 8 + 3] = g
& 255;
3128 out
[i
* 8 + 4] = (b
>> 8) & 255;
3129 out
[i
* 8 + 5] = b
& 255;
3130 out
[i
* 8 + 6] = (a
>> 8) & 255;
3131 out
[i
* 8 + 7] = a
& 255;
3134 return 0; /*no error*/
3137 /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3138 static unsigned getPixelColorRGBA8(unsigned char* r
, unsigned char* g
,
3139 unsigned char* b
, unsigned char* a
,
3140 const unsigned char* in
, size_t i
,
3141 const LodePNGColorMode
* mode
)
3143 if(mode
->colortype
== LCT_GREY
)
3145 if(mode
->bitdepth
== 8)
3147 *r
= *g
= *b
= in
[i
];
3148 if(mode
->key_defined
&& *r
== mode
->key_r
) *a
= 0;
3151 else if(mode
->bitdepth
== 16)
3153 *r
= *g
= *b
= in
[i
* 2 + 0];
3154 if(mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
) *a
= 0;
3159 unsigned highest
= ((1U << mode
->bitdepth
) - 1U); /*highest possible value for this bit depth*/
3160 size_t j
= i
* mode
->bitdepth
;
3161 unsigned value
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3162 *r
= *g
= *b
= (value
* 255) / highest
;
3163 if(mode
->key_defined
&& value
== mode
->key_r
) *a
= 0;
3167 else if(mode
->colortype
== LCT_RGB
)
3169 if(mode
->bitdepth
== 8)
3171 *r
= in
[i
* 3 + 0]; *g
= in
[i
* 3 + 1]; *b
= in
[i
* 3 + 2];
3172 if(mode
->key_defined
&& *r
== mode
->key_r
&& *g
== mode
->key_g
&& *b
== mode
->key_b
) *a
= 0;
3180 if(mode
->key_defined
&& 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3181 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3182 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
) *a
= 0;
3186 else if(mode
->colortype
== LCT_PALETTE
)
3189 if(mode
->bitdepth
== 8) index
= in
[i
];
3192 size_t j
= i
* mode
->bitdepth
;
3193 index
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3195 if(index
>= mode
->palettesize
) return 47; /*index out of palette*/
3196 *r
= mode
->palette
[index
* 4 + 0];
3197 *g
= mode
->palette
[index
* 4 + 1];
3198 *b
= mode
->palette
[index
* 4 + 2];
3199 *a
= mode
->palette
[index
* 4 + 3];
3201 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3203 if(mode
->bitdepth
== 8)
3205 *r
= *g
= *b
= in
[i
* 2 + 0];
3210 *r
= *g
= *b
= in
[i
* 4 + 0];
3214 else if(mode
->colortype
== LCT_RGBA
)
3216 if(mode
->bitdepth
== 8)
3232 return 0; /*no error*/
3235 /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3236 mode test cases, optimized to convert the colors much faster, when converting
3237 to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3238 enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3239 of the input buffer.*/
3240 static unsigned getPixelColorsRGBA8(unsigned char* buffer
, size_t numpixels
,
3241 unsigned has_alpha
, const unsigned char* in
,
3242 const LodePNGColorMode
* mode
)
3244 unsigned num_channels
= has_alpha
? 4 : 3;
3246 if(mode
->colortype
== LCT_GREY
)
3248 if(mode
->bitdepth
== 8)
3250 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3252 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
];
3253 if(has_alpha
) buffer
[3] = mode
->key_defined
&& in
[i
] == mode
->key_r
? 0 : 255;
3256 else if(mode
->bitdepth
== 16)
3258 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3260 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 2];
3261 if(has_alpha
) buffer
[3] = mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
? 0 : 255;
3266 unsigned highest
= ((1U << mode
->bitdepth
) - 1U); /*highest possible value for this bit depth*/
3268 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3270 unsigned value
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3271 buffer
[0] = buffer
[1] = buffer
[2] = (value
* 255) / highest
;
3272 if(has_alpha
) buffer
[3] = mode
->key_defined
&& value
== mode
->key_r
? 0 : 255;
3276 else if(mode
->colortype
== LCT_RGB
)
3278 if(mode
->bitdepth
== 8)
3280 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3282 buffer
[0] = in
[i
* 3 + 0];
3283 buffer
[1] = in
[i
* 3 + 1];
3284 buffer
[2] = in
[i
* 3 + 2];
3285 if(has_alpha
) buffer
[3] = mode
->key_defined
&& buffer
[0] == mode
->key_r
3286 && buffer
[1]== mode
->key_g
&& buffer
[2] == mode
->key_b
? 0 : 255;
3291 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3293 buffer
[0] = in
[i
* 6 + 0];
3294 buffer
[1] = in
[i
* 6 + 2];
3295 buffer
[2] = in
[i
* 6 + 4];
3296 if(has_alpha
) buffer
[3] = mode
->key_defined
3297 && 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3298 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3299 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
? 0 : 255;
3303 else if(mode
->colortype
== LCT_PALETTE
)
3307 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3309 if(mode
->bitdepth
== 8) index
= in
[i
];
3310 else index
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3311 if(index
>= mode
->palettesize
) return 47; /*index out of palette*/
3312 buffer
[0] = mode
->palette
[index
* 4 + 0];
3313 buffer
[1] = mode
->palette
[index
* 4 + 1];
3314 buffer
[2] = mode
->palette
[index
* 4 + 2];
3315 if(has_alpha
) buffer
[3] = mode
->palette
[index
* 4 + 3];
3318 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3320 if(mode
->bitdepth
== 8)
3322 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3324 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 2 + 0];
3325 if(has_alpha
) buffer
[3] = in
[i
* 2 + 1];
3330 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3332 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 4 + 0];
3333 if(has_alpha
) buffer
[3] = in
[i
* 4 + 2];
3337 else if(mode
->colortype
== LCT_RGBA
)
3339 if(mode
->bitdepth
== 8)
3341 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3343 buffer
[0] = in
[i
* 4 + 0];
3344 buffer
[1] = in
[i
* 4 + 1];
3345 buffer
[2] = in
[i
* 4 + 2];
3346 if(has_alpha
) buffer
[3] = in
[i
* 4 + 3];
3351 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3353 buffer
[0] = in
[i
* 8 + 0];
3354 buffer
[1] = in
[i
* 8 + 2];
3355 buffer
[2] = in
[i
* 8 + 4];
3356 if(has_alpha
) buffer
[3] = in
[i
* 8 + 6];
3361 return 0; /*no error*/
3364 /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3365 given color type, but the given color type must be 16-bit itself.*/
3366 static unsigned getPixelColorRGBA16(UINT16
* r
, UINT16
* g
, UINT16
* b
, UINT16
* a
,
3367 const unsigned char* in
, size_t i
, const LodePNGColorMode
* mode
)
3369 if(mode
->bitdepth
!= 16) return 85; /*error: this function only supports 16-bit input*/
3371 if(mode
->colortype
== LCT_GREY
)
3373 *r
= *g
= *b
= 256 * in
[i
* 2 + 0] + in
[i
* 2 + 1];
3374 if(mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
) *a
= 0;
3377 else if(mode
->colortype
== LCT_RGB
)
3379 *r
= 256 * in
[i
* 6 + 0] + in
[i
* 6 + 1];
3380 *g
= 256 * in
[i
* 6 + 2] + in
[i
* 6 + 3];
3381 *b
= 256 * in
[i
* 6 + 4] + in
[i
* 6 + 5];
3382 if(mode
->key_defined
&& 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3383 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3384 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
) *a
= 0;
3387 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3389 *r
= *g
= *b
= 256 * in
[i
* 4 + 0] + in
[i
* 4 + 1];
3390 *a
= 256 * in
[i
* 4 + 2] + in
[i
* 4 + 3];
3392 else if(mode
->colortype
== LCT_RGBA
)
3394 *r
= 256 * in
[i
* 8 + 0] + in
[i
* 8 + 1];
3395 *g
= 256 * in
[i
* 8 + 2] + in
[i
* 8 + 3];
3396 *b
= 256 * in
[i
* 8 + 4] + in
[i
* 8 + 5];
3397 *a
= 256 * in
[i
* 8 + 6] + in
[i
* 8 + 7];
3399 else return 85; /*error: this function only supports 16-bit input, not palettes*/
3401 return 0; /*no error*/
3405 converts from any color type to 24-bit or 32-bit (later maybe more supported). return value = LodePNG error code
3406 the out buffer must have (w * h * bpp + 7) / 8 bytes, where bpp is the bits per pixel of the output color type
3407 (lodepng_get_bpp) for < 8 bpp images, there may _not_ be padding bits at the end of scanlines.
3409 unsigned lodepng_convert(unsigned char* out
, const unsigned char* in
,
3410 LodePNGColorMode
* mode_out
, LodePNGColorMode
* mode_in
,
3411 unsigned w
, unsigned h
)
3416 size_t numpixels
= w
* h
;
3418 if(lodepng_color_mode_equal(mode_out
, mode_in
))
3420 size_t numbytes
= lodepng_get_raw_size(w
, h
, mode_in
);
3421 for(i
= 0; i
< numbytes
; i
++) out
[i
] = in
[i
];
3425 if(mode_out
->colortype
== LCT_PALETTE
)
3427 size_t palsize
= 1 << mode_out
->bitdepth
;
3428 if(mode_out
->palettesize
< palsize
) palsize
= mode_out
->palettesize
;
3429 color_tree_init(&tree
);
3430 for(i
= 0; i
< palsize
; i
++)
3432 unsigned char* p
= &mode_out
->palette
[i
* 4];
3433 color_tree_add(&tree
, p
[0], p
[1], p
[2], p
[3], i
);
3437 if(mode_in
->bitdepth
== 16 && mode_out
->bitdepth
== 16)
3439 for(i
= 0; i
< numpixels
; i
++)
3441 UINT16 r
= 0, g
= 0, b
= 0, a
= 0;
3442 error
= getPixelColorRGBA16(&r
, &g
, &b
, &a
, in
, i
, mode_in
);
3444 error
= rgba16ToPixel(out
, i
, mode_out
, r
, g
, b
, a
);
3448 else if(mode_out
->bitdepth
== 8 && mode_out
->colortype
== LCT_RGBA
)
3450 error
= getPixelColorsRGBA8(out
, numpixels
, 1, in
, mode_in
);
3452 else if(mode_out
->bitdepth
== 8 && mode_out
->colortype
== LCT_RGB
)
3454 error
= getPixelColorsRGBA8(out
, numpixels
, 0, in
, mode_in
);
3458 unsigned char r
= 0, g
= 0, b
= 0, a
= 0;
3459 for(i
= 0; i
< numpixels
; i
++)
3461 error
= getPixelColorRGBA8(&r
, &g
, &b
, &a
, in
, i
, mode_in
);
3463 error
= rgba8ToPixel(out
, i
, mode_out
, &tree
, r
, g
, b
, a
);
3468 if(mode_out
->colortype
== LCT_PALETTE
)
3470 color_tree_cleanup(&tree
);
3476 #ifdef LODEPNG_COMPILE_ENCODER
3479 typedef struct ColorProfile
3481 unsigned char sixteenbit
; /*needs more than 8 bits per channel*/
3482 unsigned char sixteenbit_done
;
3485 unsigned char colored
; /*not greyscale*/
3486 unsigned char colored_done
;
3488 unsigned char key
; /*a color key is required, or more*/
3489 UINT16 key_r
; /*these values are always in 16-bit bitdepth in the profile*/
3492 unsigned char alpha
; /*alpha channel, or alpha palette, required*/
3493 unsigned char alpha_done
;
3496 ColorTree tree
; /*for listing the counted colors, up to 256*/
3497 unsigned char* palette
; /*size 1024. Remember up to the first 256 RGBA colors*/
3498 unsigned maxnumcolors
; /*if more than that amount counted*/
3499 unsigned char numcolors_done
;
3501 unsigned greybits
; /*amount of bits required for greyscale (1, 2, 4, 8). Does not take 16 bit into account.*/
3502 unsigned char greybits_done
;
3506 static void color_profile_init(ColorProfile
* profile
, LodePNGColorMode
* mode
)
3508 profile
->sixteenbit
= 0;
3509 profile
->sixteenbit_done
= mode
->bitdepth
== 16 ? 0 : 1;
3511 profile
->colored
= 0;
3512 profile
->colored_done
= lodepng_is_greyscale_type(mode
) ? 1 : 0;
3516 profile
->alpha_done
= lodepng_can_have_alpha(mode
) ? 0 : 1;
3518 profile
->numcolors
= 0;
3519 color_tree_init(&profile
->tree
);
3520 profile
->palette
= (unsigned char*)mymalloc(1024);
3521 profile
->maxnumcolors
= 257;
3522 if(lodepng_get_bpp(mode
) <= 8)
3524 int bpp
= lodepng_get_bpp(mode
);
3525 profile
->maxnumcolors
= bpp
== 1 ? 2 : (bpp
== 2 ? 4 : (bpp
== 4 ? 16 : 256));
3527 profile
->numcolors_done
= 0;
3529 profile
->greybits
= 1;
3530 profile
->greybits_done
= lodepng_get_bpp(mode
) == 1 ? 1 : 0;
3533 static void color_profile_cleanup(ColorProfile
* profile
)
3535 color_tree_cleanup(&profile
->tree
);
3536 myfree(profile
->palette
);
3539 /*function used for debug purposes with C++*/
3540 /*void printColorProfile(ColorProfile* p)
3542 std::cout << "sixteenbit: " << (int)p->sixteenbit << std::endl;
3543 std::cout << "sixteenbit_done: " << (int)p->sixteenbit_done << std::endl;
3544 std::cout << "colored: " << (int)p->colored << std::endl;
3545 std::cout << "colored_done: " << (int)p->colored_done << std::endl;
3546 std::cout << "key: " << (int)p->key << std::endl;
3547 std::cout << "key_r: " << (int)p->key_r << std::endl;
3548 std::cout << "key_g: " << (int)p->key_g << std::endl;
3549 std::cout << "key_b: " << (int)p->key_b << std::endl;
3550 std::cout << "alpha: " << (int)p->alpha << std::endl;
3551 std::cout << "alpha_done: " << (int)p->alpha_done << std::endl;
3552 std::cout << "numcolors: " << (int)p->numcolors << std::endl;
3553 std::cout << "maxnumcolors: " << (int)p->maxnumcolors << std::endl;
3554 std::cout << "numcolors_done: " << (int)p->numcolors_done << std::endl;
3555 std::cout << "greybits: " << (int)p->greybits << std::endl;
3556 std::cout << "greybits_done: " << (int)p->greybits_done << std::endl;
3559 /*Returns how many bits needed to represent given value (max 8 bit)*/
3560 unsigned getValueRequiredBits(UINT16 value
)
3562 if(value
== 0 || value
== 255) return 1;
3563 /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3564 if(value
% 17 == 0) return value
% 85 == 0 ? 2 : 4;
3568 /*profile must already have been inited with mode.
3569 It's ok to set some parameters of profile to done already.*/
3570 static unsigned get_color_profile(ColorProfile
* profile
,
3571 const unsigned char* in
, size_t numpixels
,
3572 LodePNGColorMode
* mode
)
3577 if(mode
->bitdepth
== 16)
3579 for(i
= 0; i
< numpixels
; i
++)
3582 error
= getPixelColorRGBA16(&r
, &g
, &b
, &a
, in
, i
, mode
);
3585 /*a color is considered good for 8-bit if the first byte and the second byte are equal,
3586 (so if it's divisible through 257), NOT necessarily if the second byte is 0*/
3587 if(!profile
->sixteenbit_done
3588 && (((r
& 255) != ((r
>> 8) & 255))
3589 || ((g
& 255) != ((g
>> 8) & 255))
3590 || ((b
& 255) != ((b
>> 8) & 255))))
3592 profile
->sixteenbit
= 1;
3593 profile
->sixteenbit_done
= 1;
3594 profile
->greybits_done
= 1; /*greybits is not applicable anymore at 16-bit*/
3595 profile
->numcolors_done
= 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3598 if(!profile
->colored_done
&& (r
!= g
|| r
!= b
))
3600 profile
->colored
= 1;
3601 profile
->colored_done
= 1;
3602 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3605 if(!profile
->alpha_done
&& a
!= 255)
3607 if(a
== 0 && !(profile
->key
&& (r
!= profile
->key_r
|| g
!= profile
->key_g
|| b
!= profile
->key_b
)))
3620 profile
->alpha_done
= 1;
3621 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3625 if(!profile
->greybits_done
)
3627 /*assuming 8-bit r, this test does not care about 16-bit*/
3628 unsigned bits
= getValueRequiredBits(r
);
3629 if(bits
> profile
->greybits
) profile
->greybits
= bits
;
3630 if(profile
->greybits
>= 8) profile
->greybits_done
= 1;
3633 if(!profile
->numcolors_done
)
3635 /*assuming 8-bit rgba, this test does not care about 16-bit*/
3636 if(!color_tree_has(&profile
->tree
, (unsigned char)r
, (unsigned char)g
, (unsigned char)b
, (unsigned char)a
))
3638 color_tree_add(&profile
->tree
, (unsigned char)r
, (unsigned char)g
, (unsigned char)b
, (unsigned char)a
,
3639 profile
->numcolors
);
3640 if(profile
->numcolors
< 256)
3642 unsigned char* p
= profile
->palette
;
3643 unsigned i
= profile
->numcolors
;
3644 p
[i
* 4 + 0] = (unsigned char)r
;
3645 p
[i
* 4 + 1] = (unsigned char)g
;
3646 p
[i
* 4 + 2] = (unsigned char)b
;
3647 p
[i
* 4 + 3] = (unsigned char)a
;
3649 profile
->numcolors
++;
3650 if(profile
->numcolors
>= profile
->maxnumcolors
) profile
->numcolors_done
= 1;
3654 if(profile
->alpha_done
&& profile
->numcolors_done
3655 && profile
->colored_done
&& profile
->sixteenbit_done
&& profile
->greybits_done
)
3663 for(i
= 0; i
< numpixels
; i
++)
3665 unsigned char r
= 0, g
= 0, b
= 0, a
= 0;
3666 error
= getPixelColorRGBA8(&r
, &g
, &b
, &a
, in
, i
, mode
);
3669 if(!profile
->colored_done
&& (r
!= g
|| r
!= b
))
3671 profile
->colored
= 1;
3672 profile
->colored_done
= 1;
3673 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3676 if(!profile
->alpha_done
&& a
!= 255)
3678 if(a
== 0 && !(profile
->key
&& (r
!= profile
->key_r
|| g
!= profile
->key_g
|| b
!= profile
->key_b
)))
3691 profile
->alpha_done
= 1;
3692 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3696 if(!profile
->greybits_done
)
3698 unsigned bits
= getValueRequiredBits(r
);
3699 if(bits
> profile
->greybits
) profile
->greybits
= bits
;
3700 if(profile
->greybits
>= 8) profile
->greybits_done
= 1;
3703 if(!profile
->numcolors_done
)
3705 if(!color_tree_has(&profile
->tree
, r
, g
, b
, a
))
3708 color_tree_add(&profile
->tree
, r
, g
, b
, a
, profile
->numcolors
);
3709 if(profile
->numcolors
< 256)
3711 unsigned char* p
= profile
->palette
;
3712 unsigned i
= profile
->numcolors
;
3718 profile
->numcolors
++;
3719 if(profile
->numcolors
>= profile
->maxnumcolors
) profile
->numcolors_done
= 1;
3723 if(profile
->alpha_done
&& profile
->numcolors_done
&& profile
->colored_done
&& profile
->greybits_done
)
3730 /*make the profile's key always 16-bit for consistency*/
3731 if(mode
->bitdepth
< 16)
3733 /*repeat each byte twice*/
3734 profile
->key_r
*= 257;
3735 profile
->key_g
*= 257;
3736 profile
->key_b
*= 257;
3742 /*updates values of mode with a potentially smaller color model. mode_out should
3743 contain the user chosen color model, but will be overwritten with the new chosen one.*/
3744 static unsigned doAutoChooseColor(LodePNGColorMode
* mode_out
,
3745 const unsigned char* image
, unsigned w
, unsigned h
, LodePNGColorMode
* mode_in
,
3746 LodePNGAutoConvert auto_convert
)
3748 ColorProfile profile
;
3750 int no_nibbles
= auto_convert
== LAC_AUTO_NO_NIBBLES
|| auto_convert
== LAC_AUTO_NO_NIBBLES_NO_PALETTE
;
3751 int no_palette
= auto_convert
== LAC_AUTO_NO_PALETTE
|| auto_convert
== LAC_AUTO_NO_NIBBLES_NO_PALETTE
;
3753 if(auto_convert
== LAC_ALPHA
)
3755 if(mode_out
->colortype
!= LCT_RGBA
&& mode_out
->colortype
!= LCT_GREY_ALPHA
) return 0;
3758 color_profile_init(&profile
, mode_in
);
3759 if(auto_convert
== LAC_ALPHA
)
3761 profile
.colored_done
= 1;
3762 profile
.greybits_done
= 1;
3763 profile
.numcolors_done
= 1;
3764 profile
.sixteenbit_done
= 1;
3766 error
= get_color_profile(&profile
, image
, w
* h
, mode_in
);
3768 if(!error
&& auto_convert
== LAC_ALPHA
)
3772 mode_out
->colortype
= (mode_out
->colortype
== LCT_RGBA
? LCT_RGB
: LCT_GREY
);
3775 else if(!error
&& auto_convert
!= LAC_ALPHA
)
3777 mode_out
->key_defined
= 0;
3779 if(profile
.sixteenbit
)
3781 mode_out
->bitdepth
= 16;
3784 mode_out
->colortype
= profile
.colored
? LCT_RGBA
: LCT_GREY_ALPHA
;
3788 mode_out
->colortype
= profile
.colored
? LCT_RGB
: LCT_GREY
;
3791 mode_out
->key_defined
= 1;
3792 mode_out
->key_r
= profile
.key_r
;
3793 mode_out
->key_g
= profile
.key_g
;
3794 mode_out
->key_b
= profile
.key_b
;
3798 else /*less than 16 bits per channel*/
3800 /*don't add palette overhead if image hasn't got a lot of pixels*/
3801 unsigned n
= profile
.numcolors
;
3802 int palette_ok
= !no_palette
&& n
<= 256 && (n
* 2 < w
* h
);
3803 unsigned palettebits
= n
<= 2 ? 1 : (n
<= 4 ? 2 : (n
<= 16 ? 4 : 8));
3804 int grey_ok
= !profile
.colored
&& !profile
.alpha
; /*grey without alpha, with potentially low bits*/
3805 if(palette_ok
|| grey_ok
)
3807 if(!palette_ok
|| (grey_ok
&& profile
.greybits
<= palettebits
))
3809 mode_out
->colortype
= LCT_GREY
;
3810 mode_out
->bitdepth
= profile
.greybits
;
3813 unsigned keyval
= profile
.key_r
;
3814 keyval
&= (profile
.greybits
- 1); /*same subgroup of bits repeated, so taking right bits is fine*/
3815 mode_out
->key_defined
= 1;
3816 mode_out
->key_r
= keyval
;
3817 mode_out
->key_g
= keyval
;
3818 mode_out
->key_b
= keyval
;
3823 /*fill in the palette*/
3825 unsigned char* p
= profile
.palette
;
3826 for(i
= 0; i
< profile
.numcolors
; i
++)
3828 error
= lodepng_palette_add(mode_out
, p
[i
* 4 + 0], p
[i
* 4 + 1], p
[i
* 4 + 2], p
[i
* 4 + 3]);
3832 mode_out
->colortype
= LCT_PALETTE
;
3833 mode_out
->bitdepth
= palettebits
;
3836 else /*8-bit per channel*/
3838 mode_out
->bitdepth
= 8;
3841 mode_out
->colortype
= profile
.colored
? LCT_RGBA
: LCT_GREY_ALPHA
;
3845 mode_out
->colortype
= profile
.colored
? LCT_RGB
: LCT_GREY
/*LCT_GREY normally won't occur, already done earlier*/;
3848 mode_out
->key_defined
= 1;
3849 mode_out
->key_r
= profile
.key_r
% 256;
3850 mode_out
->key_g
= profile
.key_g
% 256;
3851 mode_out
->key_b
= profile
.key_b
% 256;
3858 color_profile_cleanup(&profile
);
3860 if(mode_out
->colortype
== LCT_PALETTE
&& mode_in
->palettesize
== mode_out
->palettesize
)
3862 /*In this case keep the palette order of the input, so that the user can choose an optimal one*/
3864 for(i
= 0; i
< mode_in
->palettesize
* 4; i
++)
3866 mode_out
->palette
[i
] = mode_in
->palette
[i
];
3870 if(no_nibbles
&& mode_out
->bitdepth
< 8)
3872 /*palette can keep its small amount of colors, as long as no indices use it*/
3873 mode_out
->bitdepth
= 8;
3879 #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3881 // My own absolute value implementation, since it doesn't seem to be part of
3882 // either GNU-EFI or TianoCore EDK2, but the compiler complains if I use the
3883 // function name "abs()"....
3884 short myabs(short orig
) {
3892 Paeth predicter, used by PNG filter type 4
3893 The parameters are of type short, but should come from unsigned chars, the shorts
3894 are only needed to make the paeth calculation correct.
3896 static unsigned char paethPredictor(short a
, short b
, short c
)
3898 short pa
= myabs(b
- c
);
3899 short pb
= myabs(a
- c
);
3900 short pc
= myabs(a
+ b
- c
- c
);
3902 if(pc
< pa
&& pc
< pb
) return (unsigned char)c
;
3903 else if(pb
< pa
) return (unsigned char)b
;
3904 else return (unsigned char)a
;
3907 /*shared values used by multiple Adam7 related functions*/
3909 static const unsigned ADAM7_IX
[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3910 static const unsigned ADAM7_IY
[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3911 static const unsigned ADAM7_DX
[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3912 static const unsigned ADAM7_DY
[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3915 Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3916 passw: output containing the width of the 7 passes
3917 passh: output containing the height of the 7 passes
3918 filter_passstart: output containing the index of the start and end of each
3919 reduced image with filter bytes
3920 padded_passstart output containing the index of the start and end of each
3921 reduced image when without filter bytes but with padded scanlines
3922 passstart: output containing the index of the start and end of each reduced
3923 image without padding between scanlines, but still padding between the images
3924 w, h: width and height of non-interlaced image
3926 "padded" is only relevant if bpp is less than 8 and a scanline or image does not
3929 static void Adam7_getpassvalues(unsigned passw
[7], unsigned passh
[7], size_t filter_passstart
[8],
3930 size_t padded_passstart
[8], size_t passstart
[8], unsigned w
, unsigned h
, unsigned bpp
)
3932 /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3935 /*calculate width and height in pixels of each pass*/
3936 for(i
= 0; i
< 7; i
++)
3938 passw
[i
] = (w
+ ADAM7_DX
[i
] - ADAM7_IX
[i
] - 1) / ADAM7_DX
[i
];
3939 passh
[i
] = (h
+ ADAM7_DY
[i
] - ADAM7_IY
[i
] - 1) / ADAM7_DY
[i
];
3940 if(passw
[i
] == 0) passh
[i
] = 0;
3941 if(passh
[i
] == 0) passw
[i
] = 0;
3944 filter_passstart
[0] = padded_passstart
[0] = passstart
[0] = 0;
3945 for(i
= 0; i
< 7; i
++)
3947 /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3948 filter_passstart
[i
+ 1] = filter_passstart
[i
]
3949 + ((passw
[i
] && passh
[i
]) ? passh
[i
] * (1 + (passw
[i
] * bpp
+ 7) / 8) : 0);
3950 /*bits padded if needed to fill full byte at end of each scanline*/
3951 padded_passstart
[i
+ 1] = padded_passstart
[i
] + passh
[i
] * ((passw
[i
] * bpp
+ 7) / 8);
3952 /*only padded at end of reduced image*/
3953 passstart
[i
+ 1] = passstart
[i
] + (passh
[i
] * passw
[i
] * bpp
+ 7) / 8;
3957 #ifdef LODEPNG_COMPILE_DECODER
3959 /* ////////////////////////////////////////////////////////////////////////// */
3960 /* / PNG Decoder / */
3961 /* ////////////////////////////////////////////////////////////////////////// */
3963 /*read the information from the header and store it in the LodePNGInfo. return value is error*/
3964 unsigned lodepng_inspect(unsigned* w
, unsigned* h
, LodePNGState
* state
,
3965 const unsigned char* in
, size_t insize
)
3967 LodePNGInfo
* info
= &state
->info_png
;
3968 if(insize
== 0 || in
== 0)
3970 CERROR_RETURN_ERROR(state
->error
, 48); /*error: the given data is empty*/
3974 CERROR_RETURN_ERROR(state
->error
, 27); /*error: the data length is smaller than the length of a PNG header*/
3977 /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3978 lodepng_info_cleanup(info
);
3979 lodepng_info_init(info
);
3981 if(in
[0] != 137 || in
[1] != 80 || in
[2] != 78 || in
[3] != 71
3982 || in
[4] != 13 || in
[5] != 10 || in
[6] != 26 || in
[7] != 10)
3984 CERROR_RETURN_ERROR(state
->error
, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3986 if(in
[12] != 'I' || in
[13] != 'H' || in
[14] != 'D' || in
[15] != 'R')
3988 CERROR_RETURN_ERROR(state
->error
, 29); /*error: it doesn't start with a IHDR chunk!*/
3991 /*read the values given in the header*/
3992 *w
= lodepng_read32bitInt(&in
[16]);
3993 *h
= lodepng_read32bitInt(&in
[20]);
3994 info
->color
.bitdepth
= in
[24];
3995 info
->color
.colortype
= (LodePNGColorType
)in
[25];
3996 info
->compression_method
= in
[26];
3997 info
->filter_method
= in
[27];
3998 info
->interlace_method
= in
[28];
4000 if(!state
->decoder
.ignore_crc
)
4002 unsigned CRC
= lodepng_read32bitInt(&in
[29]);
4003 unsigned checksum
= lodepng_crc32(&in
[12], 17);
4006 CERROR_RETURN_ERROR(state
->error
, 57); /*invalid CRC*/
4010 /*error: only compression method 0 is allowed in the specification*/
4011 if(info
->compression_method
!= 0) CERROR_RETURN_ERROR(state
->error
, 32);
4012 /*error: only filter method 0 is allowed in the specification*/
4013 if(info
->filter_method
!= 0) CERROR_RETURN_ERROR(state
->error
, 33);
4014 /*error: only interlace methods 0 and 1 exist in the specification*/
4015 if(info
->interlace_method
> 1) CERROR_RETURN_ERROR(state
->error
, 34);
4017 state
->error
= checkColorValidity(info
->color
.colortype
, info
->color
.bitdepth
);
4018 return state
->error
;
4021 static unsigned unfilterScanline(unsigned char* recon
, const unsigned char* scanline
, const unsigned char* precon
,
4022 size_t bytewidth
, unsigned char filterType
, size_t length
)
4025 For PNG filter method 0
4026 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
4027 the filter works byte per byte (bytewidth = 1)
4028 precon is the previous unfiltered scanline, recon the result, scanline the current one
4029 the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
4030 recon and scanline MAY be the same memory address! precon must be disjoint.
4037 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
];
4040 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
];
4041 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + recon
[i
- bytewidth
];
4046 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
] + precon
[i
];
4050 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
];
4056 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
] + precon
[i
] / 2;
4057 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + ((recon
[i
- bytewidth
] + precon
[i
]) / 2);
4061 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
];
4062 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + recon
[i
- bytewidth
] / 2;
4068 for(i
= 0; i
< bytewidth
; i
++)
4070 recon
[i
] = (scanline
[i
] + precon
[i
]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
4072 for(i
= bytewidth
; i
< length
; i
++)
4074 recon
[i
] = (scanline
[i
] + paethPredictor(recon
[i
- bytewidth
], precon
[i
], precon
[i
- bytewidth
]));
4079 for(i
= 0; i
< bytewidth
; i
++)
4081 recon
[i
] = scanline
[i
];
4083 for(i
= bytewidth
; i
< length
; i
++)
4085 /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
4086 recon
[i
] = (scanline
[i
] + recon
[i
- bytewidth
]);
4090 default: return 36; /*error: unexisting filter type given*/
4095 static unsigned unfilter(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
4098 For PNG filter method 0
4099 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
4100 out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
4101 w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
4102 in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
4106 unsigned char* prevline
= 0;
4108 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
4109 size_t bytewidth
= (bpp
+ 7) / 8;
4110 size_t linebytes
= (w
* bpp
+ 7) / 8;
4112 for(y
= 0; y
< h
; y
++)
4114 size_t outindex
= linebytes
* y
;
4115 size_t inindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
4116 unsigned char filterType
= in
[inindex
];
4118 CERROR_TRY_RETURN(unfilterScanline(&out
[outindex
], &in
[inindex
+ 1], prevline
, bytewidth
, filterType
, linebytes
));
4120 prevline
= &out
[outindex
];
4127 in: Adam7 interlaced image, with no padding bits between scanlines, but between
4128 reduced images so that each reduced image starts at a byte.
4129 out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4131 out has the following size in bits: w * h * bpp.
4132 in is possibly bigger due to padding bits between reduced images.
4133 out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4134 (because that's likely a little bit faster)
4135 NOTE: comments about padding bits are only relevant if bpp < 8
4137 static void Adam7_deinterlace(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
4139 unsigned passw
[7], passh
[7];
4140 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
4143 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
4147 for(i
= 0; i
< 7; i
++)
4150 size_t bytewidth
= bpp
/ 8;
4151 for(y
= 0; y
< passh
[i
]; y
++)
4152 for(x
= 0; x
< passw
[i
]; x
++)
4154 size_t pixelinstart
= passstart
[i
] + (y
* passw
[i
] + x
) * bytewidth
;
4155 size_t pixeloutstart
= ((ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * w
+ ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bytewidth
;
4156 for(b
= 0; b
< bytewidth
; b
++)
4158 out
[pixeloutstart
+ b
] = in
[pixelinstart
+ b
];
4163 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4165 for(i
= 0; i
< 7; i
++)
4168 unsigned ilinebits
= bpp
* passw
[i
];
4169 unsigned olinebits
= bpp
* w
;
4170 size_t obp
, ibp
; /*bit pointers (for out and in buffer)*/
4171 for(y
= 0; y
< passh
[i
]; y
++)
4172 for(x
= 0; x
< passw
[i
]; x
++)
4174 ibp
= (8 * passstart
[i
]) + (y
* ilinebits
+ x
* bpp
);
4175 obp
= (ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * olinebits
+ (ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bpp
;
4176 for(b
= 0; b
< bpp
; b
++)
4178 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
4179 /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4180 setBitOfReversedStream0(&obp
, out
, bit
);
4187 static void removePaddingBits(unsigned char* out
, const unsigned char* in
,
4188 size_t olinebits
, size_t ilinebits
, unsigned h
)
4191 After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4192 to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4193 for the Adam7 code, the color convert code and the output to the user.
4194 in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4195 have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4196 also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4197 only useful if (ilinebits - olinebits) is a value in the range 1..7
4200 size_t diff
= ilinebits
- olinebits
;
4201 size_t ibp
= 0, obp
= 0; /*input and output bit pointers*/
4202 for(y
= 0; y
< h
; y
++)
4205 for(x
= 0; x
< olinebits
; x
++)
4207 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
4208 setBitOfReversedStream(&obp
, out
, bit
);
4214 /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4215 the IDAT chunks (with filter index bytes and possible padding bits)
4216 return value is error*/
4217 static unsigned postProcessScanlines(unsigned char* out
, unsigned char* in
,
4218 unsigned w
, unsigned h
, const LodePNGInfo
* info_png
)
4221 This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4223 *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4224 *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4225 NOTE: the in buffer will be overwritten with intermediate data!
4227 unsigned bpp
= lodepng_get_bpp(&info_png
->color
);
4228 if(bpp
== 0) return 31; /*error: invalid colortype*/
4230 if(info_png
->interlace_method
== 0)
4232 if(bpp
< 8 && w
* bpp
!= ((w
* bpp
+ 7) / 8) * 8)
4234 CERROR_TRY_RETURN(unfilter(in
, in
, w
, h
, bpp
));
4235 removePaddingBits(out
, in
, w
* bpp
, ((w
* bpp
+ 7) / 8) * 8, h
);
4237 /*we can immediatly filter into the out buffer, no other steps needed*/
4238 else CERROR_TRY_RETURN(unfilter(out
, in
, w
, h
, bpp
));
4240 else /*interlace_method is 1 (Adam7)*/
4242 unsigned passw
[7], passh
[7]; size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
4245 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
4247 for(i
= 0; i
< 7; i
++)
4249 CERROR_TRY_RETURN(unfilter(&in
[padded_passstart
[i
]], &in
[filter_passstart
[i
]], passw
[i
], passh
[i
], bpp
));
4250 /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4251 move bytes instead of bits or move not at all*/
4254 /*remove padding bits in scanlines; after this there still may be padding
4255 bits between the different reduced images: each reduced image still starts nicely at a byte*/
4256 removePaddingBits(&in
[passstart
[i
]], &in
[padded_passstart
[i
]], passw
[i
] * bpp
,
4257 ((passw
[i
] * bpp
+ 7) / 8) * 8, passh
[i
]);
4261 Adam7_deinterlace(out
, in
, w
, h
, bpp
);
4267 static unsigned readChunk_PLTE(LodePNGColorMode
* color
, const unsigned char* data
, size_t chunkLength
)
4269 unsigned pos
= 0, i
;
4270 if(color
->palette
) myfree(color
->palette
);
4271 color
->palettesize
= chunkLength
/ 3;
4272 color
->palette
= (unsigned char*)mymalloc(4 * color
->palettesize
);
4273 if(!color
->palette
&& color
->palettesize
)
4275 color
->palettesize
= 0;
4276 return 83; /*alloc fail*/
4278 if(color
->palettesize
> 256) return 38; /*error: palette too big*/
4280 for(i
= 0; i
< color
->palettesize
; i
++)
4282 color
->palette
[4 * i
+ 0] = data
[pos
++]; /*R*/
4283 color
->palette
[4 * i
+ 1] = data
[pos
++]; /*G*/
4284 color
->palette
[4 * i
+ 2] = data
[pos
++]; /*B*/
4285 color
->palette
[4 * i
+ 3] = 255; /*alpha*/
4291 static unsigned readChunk_tRNS(LodePNGColorMode
* color
, const unsigned char* data
, size_t chunkLength
)
4294 if(color
->colortype
== LCT_PALETTE
)
4296 /*error: more alpha values given than there are palette entries*/
4297 if(chunkLength
> color
->palettesize
) return 38;
4299 for(i
= 0; i
< chunkLength
; i
++) color
->palette
[4 * i
+ 3] = data
[i
];
4301 else if(color
->colortype
== LCT_GREY
)
4303 /*error: this chunk must be 2 bytes for greyscale image*/
4304 if(chunkLength
!= 2) return 30;
4306 color
->key_defined
= 1;
4307 color
->key_r
= color
->key_g
= color
->key_b
= 256 * data
[0] + data
[1];
4309 else if(color
->colortype
== LCT_RGB
)
4311 /*error: this chunk must be 6 bytes for RGB image*/
4312 if(chunkLength
!= 6) return 41;
4314 color
->key_defined
= 1;
4315 color
->key_r
= 256 * data
[0] + data
[1];
4316 color
->key_g
= 256 * data
[2] + data
[3];
4317 color
->key_b
= 256 * data
[4] + data
[5];
4319 else return 42; /*error: tRNS chunk not allowed for other color models*/
4325 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4326 /*background color chunk (bKGD)*/
4327 static unsigned readChunk_bKGD(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4329 if(info
->color
.colortype
== LCT_PALETTE
)
4331 /*error: this chunk must be 1 byte for indexed color image*/
4332 if(chunkLength
!= 1) return 43;
4334 info
->background_defined
= 1;
4335 info
->background_r
= info
->background_g
= info
->background_b
= data
[0];
4337 else if(info
->color
.colortype
== LCT_GREY
|| info
->color
.colortype
== LCT_GREY_ALPHA
)
4339 /*error: this chunk must be 2 bytes for greyscale image*/
4340 if(chunkLength
!= 2) return 44;
4342 info
->background_defined
= 1;
4343 info
->background_r
= info
->background_g
= info
->background_b
4344 = 256 * data
[0] + data
[1];
4346 else if(info
->color
.colortype
== LCT_RGB
|| info
->color
.colortype
== LCT_RGBA
)
4348 /*error: this chunk must be 6 bytes for greyscale image*/
4349 if(chunkLength
!= 6) return 45;
4351 info
->background_defined
= 1;
4352 info
->background_r
= 256 * data
[0] + data
[1];
4353 info
->background_g
= 256 * data
[2] + data
[3];
4354 info
->background_b
= 256 * data
[4] + data
[5];
4360 /*text chunk (tEXt)*/
4361 static unsigned readChunk_tEXt(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4364 char *key
= 0, *str
= 0;
4367 while(!error
) /*not really a while loop, only used to break on error*/
4369 unsigned length
, string2_begin
;
4372 while(length
< chunkLength
&& data
[length
] != 0) length
++;
4373 /*even though it's not allowed by the standard, no error is thrown if
4374 there's no null termination char, if the text is empty*/
4375 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4377 key
= (char*)mymalloc(length
+ 1);
4378 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4381 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4383 string2_begin
= length
+ 1; /*skip keyword null terminator*/
4385 length
= chunkLength
< string2_begin
? 0 : chunkLength
- string2_begin
;
4386 str
= (char*)mymalloc(length
+ 1);
4387 if(!str
) CERROR_BREAK(error
, 83); /*alloc fail*/
4390 for(i
= 0; i
< length
; i
++) str
[i
] = data
[string2_begin
+ i
];
4392 error
= lodepng_add_text(info
, key
, str
);
4403 /*compressed text chunk (zTXt)*/
4404 static unsigned readChunk_zTXt(LodePNGInfo
* info
, const LodePNGDecompressSettings
* zlibsettings
,
4405 const unsigned char* data
, size_t chunkLength
)
4410 unsigned length
, string2_begin
;
4414 ucvector_init(&decoded
);
4416 while(!error
) /*not really a while loop, only used to break on error*/
4418 for(length
= 0; length
< chunkLength
&& data
[length
] != 0; length
++) ;
4419 if(length
+ 2 >= chunkLength
) CERROR_BREAK(error
, 75); /*no null termination, corrupt?*/
4420 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4422 key
= (char*)mymalloc(length
+ 1);
4423 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4426 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4428 if(data
[length
+ 1] != 0) CERROR_BREAK(error
, 72); /*the 0 byte indicating compression must be 0*/
4430 string2_begin
= length
+ 2;
4431 if(string2_begin
> chunkLength
) CERROR_BREAK(error
, 75); /*no null termination, corrupt?*/
4433 length
= chunkLength
- string2_begin
;
4434 /*will fail if zlib error, e.g. if length is too small*/
4435 error
= zlib_decompress(&decoded
.data
, &decoded
.size
,
4436 (unsigned char*)(&data
[string2_begin
]),
4437 length
, zlibsettings
);
4439 ucvector_push_back(&decoded
, 0);
4441 error
= lodepng_add_text(info
, key
, (char*)decoded
.data
);
4447 ucvector_cleanup(&decoded
);
4452 /*international text chunk (iTXt)*/
4453 static unsigned readChunk_iTXt(LodePNGInfo
* info
, const LodePNGDecompressSettings
* zlibsettings
,
4454 const unsigned char* data
, size_t chunkLength
)
4459 unsigned length
, begin
, compressed
;
4460 char *key
= 0, *langtag
= 0, *transkey
= 0;
4462 ucvector_init(&decoded
);
4464 while(!error
) /*not really a while loop, only used to break on error*/
4466 /*Quick check if the chunk length isn't too small. Even without check
4467 it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4468 if(chunkLength
< 5) CERROR_BREAK(error
, 30); /*iTXt chunk too short*/
4471 for(length
= 0; length
< chunkLength
&& data
[length
] != 0; length
++) ;
4472 if(length
+ 3 >= chunkLength
) CERROR_BREAK(error
, 75); /*no null termination char, corrupt?*/
4473 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4475 key
= (char*)mymalloc(length
+ 1);
4476 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4479 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4481 /*read the compression method*/
4482 compressed
= data
[length
+ 1];
4483 if(data
[length
+ 2] != 0) CERROR_BREAK(error
, 72); /*the 0 byte indicating compression must be 0*/
4485 /*even though it's not allowed by the standard, no error is thrown if
4486 there's no null termination char, if the text is empty for the next 3 texts*/
4488 /*read the langtag*/
4491 for(i
= begin
; i
< chunkLength
&& data
[i
] != 0; i
++) length
++;
4493 langtag
= (char*)mymalloc(length
+ 1);
4494 if(!langtag
) CERROR_BREAK(error
, 83); /*alloc fail*/
4496 langtag
[length
] = 0;
4497 for(i
= 0; i
< length
; i
++) langtag
[i
] = data
[begin
+ i
];
4499 /*read the transkey*/
4500 begin
+= length
+ 1;
4502 for(i
= begin
; i
< chunkLength
&& data
[i
] != 0; i
++) length
++;
4504 transkey
= (char*)mymalloc(length
+ 1);
4505 if(!transkey
) CERROR_BREAK(error
, 83); /*alloc fail*/
4507 transkey
[length
] = 0;
4508 for(i
= 0; i
< length
; i
++) transkey
[i
] = data
[begin
+ i
];
4510 /*read the actual text*/
4511 begin
+= length
+ 1;
4513 length
= chunkLength
< begin
? 0 : chunkLength
- begin
;
4517 /*will fail if zlib error, e.g. if length is too small*/
4518 error
= zlib_decompress(&decoded
.data
, &decoded
.size
,
4519 (unsigned char*)(&data
[begin
]),
4520 length
, zlibsettings
);
4522 if(decoded
.allocsize
< decoded
.size
) decoded
.allocsize
= decoded
.size
;
4523 ucvector_push_back(&decoded
, 0);
4527 if(!ucvector_resize(&decoded
, length
+ 1)) CERROR_BREAK(error
, 83 /*alloc fail*/);
4529 decoded
.data
[length
] = 0;
4530 for(i
= 0; i
< length
; i
++) decoded
.data
[i
] = data
[begin
+ i
];
4533 error
= lodepng_add_itext(info
, key
, langtag
, transkey
, (char*)decoded
.data
);
4541 ucvector_cleanup(&decoded
);
4546 static unsigned readChunk_tIME(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4548 if(chunkLength
!= 7) return 73; /*invalid tIME chunk size*/
4550 info
->time_defined
= 1;
4551 info
->time
.year
= 256 * data
[0] + data
[+ 1];
4552 info
->time
.month
= data
[2];
4553 info
->time
.day
= data
[3];
4554 info
->time
.hour
= data
[4];
4555 info
->time
.minute
= data
[5];
4556 info
->time
.second
= data
[6];
4561 static unsigned readChunk_pHYs(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4563 if(chunkLength
!= 9) return 74; /*invalid pHYs chunk size*/
4565 info
->phys_defined
= 1;
4566 info
->phys_x
= 16777216 * data
[0] + 65536 * data
[1] + 256 * data
[2] + data
[3];
4567 info
->phys_y
= 16777216 * data
[4] + 65536 * data
[5] + 256 * data
[6] + data
[7];
4568 info
->phys_unit
= data
[8];
4572 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4574 /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4575 static void decodeGeneric(unsigned char** out
, unsigned* w
, unsigned* h
,
4576 LodePNGState
* state
,
4577 const unsigned char* in
, size_t insize
)
4579 unsigned char IEND
= 0;
4580 const unsigned char* chunk
;
4582 ucvector idat
; /*the data from idat chunks*/
4584 /*for unknown chunk order*/
4585 unsigned unknown
= 0;
4586 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4587 unsigned critical_pos
= 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4588 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4590 /*provide some proper output values if error will happen*/
4593 state
->error
= lodepng_inspect(w
, h
, state
, in
, insize
); /*reads header and resets other parameters in state->info_png*/
4594 if(state
->error
) return;
4596 ucvector_init(&idat
);
4597 chunk
= &in
[33]; /*first byte of the first chunk after the header*/
4599 /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4600 IDAT data is put at the start of the in buffer*/
4601 while(!IEND
&& !state
->error
)
4603 unsigned chunkLength
;
4604 const unsigned char* data
; /*the data in the chunk*/
4606 /*error: size of the in buffer too small to contain next chunk*/
4607 if((size_t)((chunk
- in
) + 12) > insize
|| chunk
< in
) CERROR_BREAK(state
->error
, 30);
4609 /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4610 chunkLength
= lodepng_chunk_length(chunk
);
4611 /*error: chunk length larger than the max PNG chunk size*/
4612 if(chunkLength
> 2147483647) CERROR_BREAK(state
->error
, 63);
4614 if((size_t)((chunk
- in
) + chunkLength
+ 12) > insize
|| (chunk
+ chunkLength
+ 12) < in
)
4616 CERROR_BREAK(state
->error
, 64); /*error: size of the in buffer too small to contain next chunk*/
4619 data
= lodepng_chunk_data_const(chunk
);
4621 /*IDAT chunk, containing compressed image data*/
4622 if(lodepng_chunk_type_equals(chunk
, "IDAT"))
4624 size_t oldsize
= idat
.size
;
4625 if(!ucvector_resize(&idat
, oldsize
+ chunkLength
)) CERROR_BREAK(state
->error
, 83 /*alloc fail*/);
4626 for(i
= 0; i
< chunkLength
; i
++) idat
.data
[oldsize
+ i
] = data
[i
];
4627 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4629 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4632 else if(lodepng_chunk_type_equals(chunk
, "IEND"))
4636 /*palette chunk (PLTE)*/
4637 else if(lodepng_chunk_type_equals(chunk
, "PLTE"))
4639 state
->error
= readChunk_PLTE(&state
->info_png
.color
, data
, chunkLength
);
4640 if(state
->error
) break;
4641 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4643 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4645 /*palette transparency chunk (tRNS)*/
4646 else if(lodepng_chunk_type_equals(chunk
, "tRNS"))
4648 state
->error
= readChunk_tRNS(&state
->info_png
.color
, data
, chunkLength
);
4649 if(state
->error
) break;
4651 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4652 /*background color chunk (bKGD)*/
4653 else if(lodepng_chunk_type_equals(chunk
, "bKGD"))
4655 state
->error
= readChunk_bKGD(&state
->info_png
, data
, chunkLength
);
4656 if(state
->error
) break;
4658 /*text chunk (tEXt)*/
4659 else if(lodepng_chunk_type_equals(chunk
, "tEXt"))
4661 if(state
->decoder
.read_text_chunks
)
4663 state
->error
= readChunk_tEXt(&state
->info_png
, data
, chunkLength
);
4664 if(state
->error
) break;
4667 /*compressed text chunk (zTXt)*/
4668 else if(lodepng_chunk_type_equals(chunk
, "zTXt"))
4670 if(state
->decoder
.read_text_chunks
)
4672 state
->error
= readChunk_zTXt(&state
->info_png
, &state
->decoder
.zlibsettings
, data
, chunkLength
);
4673 if(state
->error
) break;
4676 /*international text chunk (iTXt)*/
4677 else if(lodepng_chunk_type_equals(chunk
, "iTXt"))
4679 if(state
->decoder
.read_text_chunks
)
4681 state
->error
= readChunk_iTXt(&state
->info_png
, &state
->decoder
.zlibsettings
, data
, chunkLength
);
4682 if(state
->error
) break;
4685 else if(lodepng_chunk_type_equals(chunk
, "tIME"))
4687 state
->error
= readChunk_tIME(&state
->info_png
, data
, chunkLength
);
4688 if(state
->error
) break;
4690 else if(lodepng_chunk_type_equals(chunk
, "pHYs"))
4692 state
->error
= readChunk_pHYs(&state
->info_png
, data
, chunkLength
);
4693 if(state
->error
) break;
4695 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4696 else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4698 /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4699 if(!lodepng_chunk_ancillary(chunk
)) CERROR_BREAK(state
->error
, 69);
4702 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4703 if(state
->decoder
.remember_unknown_chunks
)
4705 state
->error
= lodepng_chunk_append(&state
->info_png
.unknown_chunks_data
[critical_pos
- 1],
4706 &state
->info_png
.unknown_chunks_size
[critical_pos
- 1], chunk
);
4707 if(state
->error
) break;
4709 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4712 if(!state
->decoder
.ignore_crc
&& !unknown
) /*check CRC if wanted, only on known chunk types*/
4714 if(lodepng_chunk_check_crc(chunk
)) CERROR_BREAK(state
->error
, 57); /*invalid CRC*/
4717 if(!IEND
) chunk
= lodepng_chunk_next_const(chunk
);
4723 ucvector_init(&scanlines
);
4725 /*maximum final image length is already reserved in the vector's length - this is not really necessary*/
4726 if(!ucvector_resize(&scanlines
, lodepng_get_raw_size(*w
, *h
, &state
->info_png
.color
) + *h
))
4728 state
->error
= 83; /*alloc fail*/
4732 /*decompress with the Zlib decompressor*/
4733 state
->error
= zlib_decompress(&scanlines
.data
, &scanlines
.size
, idat
.data
,
4734 idat
.size
, &state
->decoder
.zlibsettings
);
4740 ucvector_init(&outv
);
4741 if(!ucvector_resizev(&outv
,
4742 lodepng_get_raw_size(*w
, *h
, &state
->info_png
.color
), 0)) state
->error
= 83; /*alloc fail*/
4743 if(!state
->error
) state
->error
= postProcessScanlines(outv
.data
, scanlines
.data
, *w
, *h
, &state
->info_png
);
4746 ucvector_cleanup(&scanlines
);
4749 ucvector_cleanup(&idat
);
4752 unsigned lodepng_decode(unsigned char** out
, unsigned* w
, unsigned* h
,
4753 LodePNGState
* state
,
4754 const unsigned char* in
, size_t insize
)
4757 decodeGeneric(out
, w
, h
, state
, in
, insize
);
4758 if(state
->error
) return state
->error
;
4759 if(!state
->decoder
.color_convert
|| lodepng_color_mode_equal(&state
->info_raw
, &state
->info_png
.color
))
4761 /*same color type, no copying or converting of data needed*/
4762 /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4763 the raw image has to the end user*/
4764 if(!state
->decoder
.color_convert
)
4766 state
->error
= lodepng_color_mode_copy(&state
->info_raw
, &state
->info_png
.color
);
4767 if(state
->error
) return state
->error
;
4772 /*color conversion needed; sort of copy of the data*/
4773 unsigned char* data
= *out
;
4776 /*TODO: check if this works according to the statement in the documentation: "The converter can convert
4777 from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4778 if(!(state
->info_raw
.colortype
== LCT_RGB
|| state
->info_raw
.colortype
== LCT_RGBA
)
4779 && !(state
->info_raw
.bitdepth
== 8))
4781 return 56; /*unsupported color mode conversion*/
4784 outsize
= lodepng_get_raw_size(*w
, *h
, &state
->info_raw
);
4785 *out
= (unsigned char*)mymalloc(outsize
);
4788 state
->error
= 83; /*alloc fail*/
4790 else state
->error
= lodepng_convert(*out
, data
, &state
->info_raw
, &state
->info_png
.color
, *w
, *h
);
4793 return state
->error
;
4796 unsigned lodepng_decode_memory(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
,
4797 size_t insize
, LodePNGColorType colortype
, unsigned bitdepth
)
4801 lodepng_state_init(&state
);
4802 state
.info_raw
.colortype
= colortype
;
4803 state
.info_raw
.bitdepth
= bitdepth
;
4804 error
= lodepng_decode(out
, w
, h
, &state
, in
, insize
);
4805 lodepng_state_cleanup(&state
);
4809 unsigned lodepng_decode32(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
, size_t insize
)
4811 return lodepng_decode_memory(out
, w
, h
, in
, insize
, LCT_RGBA
, 8);
4814 unsigned lodepng_decode24(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
, size_t insize
)
4816 return lodepng_decode_memory(out
, w
, h
, in
, insize
, LCT_RGB
, 8);
4819 #ifdef LODEPNG_COMPILE_DISK
4820 unsigned lodepng_decode_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
,
4821 LodePNGColorType colortype
, unsigned bitdepth
)
4823 unsigned char* buffer
;
4826 error
= lodepng_load_file(&buffer
, &buffersize
, filename
);
4827 if(!error
) error
= lodepng_decode_memory(out
, w
, h
, buffer
, buffersize
, colortype
, bitdepth
);
4832 unsigned lodepng_decode32_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
)
4834 return lodepng_decode_file(out
, w
, h
, filename
, LCT_RGBA
, 8);
4837 unsigned lodepng_decode24_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
)
4839 return lodepng_decode_file(out
, w
, h
, filename
, LCT_RGB
, 8);
4841 #endif /*LODEPNG_COMPILE_DISK*/
4843 void lodepng_decoder_settings_init(LodePNGDecoderSettings
* settings
)
4845 settings
->color_convert
= 1;
4846 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4847 settings
->read_text_chunks
= 1;
4848 settings
->remember_unknown_chunks
= 0;
4849 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4850 settings
->ignore_crc
= 0;
4851 lodepng_decompress_settings_init(&settings
->zlibsettings
);
4854 #endif /*LODEPNG_COMPILE_DECODER*/
4856 #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4858 void lodepng_state_init(LodePNGState
* state
)
4860 #ifdef LODEPNG_COMPILE_DECODER
4861 lodepng_decoder_settings_init(&state
->decoder
);
4862 #endif /*LODEPNG_COMPILE_DECODER*/
4863 #ifdef LODEPNG_COMPILE_ENCODER
4864 lodepng_encoder_settings_init(&state
->encoder
);
4865 #endif /*LODEPNG_COMPILE_ENCODER*/
4866 lodepng_color_mode_init(&state
->info_raw
);
4867 lodepng_info_init(&state
->info_png
);
4871 void lodepng_state_cleanup(LodePNGState
* state
)
4873 lodepng_color_mode_cleanup(&state
->info_raw
);
4874 lodepng_info_cleanup(&state
->info_png
);
4877 void lodepng_state_copy(LodePNGState
* dest
, const LodePNGState
* source
)
4879 lodepng_state_cleanup(dest
);
4881 lodepng_color_mode_init(&dest
->info_raw
);
4882 lodepng_info_init(&dest
->info_png
);
4883 dest
->error
= lodepng_color_mode_copy(&dest
->info_raw
, &source
->info_raw
); if(dest
->error
) return;
4884 dest
->error
= lodepng_info_copy(&dest
->info_png
, &source
->info_png
); if(dest
->error
) return;
4887 #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4889 #ifdef LODEPNG_COMPILE_ENCODER
4891 /* ////////////////////////////////////////////////////////////////////////// */
4892 /* / PNG Encoder / */
4893 /* ////////////////////////////////////////////////////////////////////////// */
4895 /*chunkName must be string of 4 characters*/
4896 static unsigned addChunk(ucvector
* out
, const char* chunkName
, const unsigned char* data
, size_t length
)
4898 CERROR_TRY_RETURN(lodepng_chunk_create(&out
->data
, &out
->size
, (unsigned)length
, chunkName
, data
));
4899 out
->allocsize
= out
->size
; /*fix the allocsize again*/
4903 static void writeSignature(ucvector
* out
)
4905 /*8 bytes PNG signature, aka the magic bytes*/
4906 ucvector_push_back(out
, 137);
4907 ucvector_push_back(out
, 80);
4908 ucvector_push_back(out
, 78);
4909 ucvector_push_back(out
, 71);
4910 ucvector_push_back(out
, 13);
4911 ucvector_push_back(out
, 10);
4912 ucvector_push_back(out
, 26);
4913 ucvector_push_back(out
, 10);
4916 static unsigned addChunk_IHDR(ucvector
* out
, unsigned w
, unsigned h
,
4917 LodePNGColorType colortype
, unsigned bitdepth
, unsigned interlace_method
)
4921 ucvector_init(&header
);
4923 lodepng_add32bitInt(&header
, w
); /*width*/
4924 lodepng_add32bitInt(&header
, h
); /*height*/
4925 ucvector_push_back(&header
, (unsigned char)bitdepth
); /*bit depth*/
4926 ucvector_push_back(&header
, (unsigned char)colortype
); /*color type*/
4927 ucvector_push_back(&header
, 0); /*compression method*/
4928 ucvector_push_back(&header
, 0); /*filter method*/
4929 ucvector_push_back(&header
, interlace_method
); /*interlace method*/
4931 error
= addChunk(out
, "IHDR", header
.data
, header
.size
);
4932 ucvector_cleanup(&header
);
4937 static unsigned addChunk_PLTE(ucvector
* out
, const LodePNGColorMode
* info
)
4942 ucvector_init(&PLTE
);
4943 for(i
= 0; i
< info
->palettesize
* 4; i
++)
4945 /*add all channels except alpha channel*/
4946 if(i
% 4 != 3) ucvector_push_back(&PLTE
, info
->palette
[i
]);
4948 error
= addChunk(out
, "PLTE", PLTE
.data
, PLTE
.size
);
4949 ucvector_cleanup(&PLTE
);
4954 static unsigned addChunk_tRNS(ucvector
* out
, const LodePNGColorMode
* info
)
4959 ucvector_init(&tRNS
);
4960 if(info
->colortype
== LCT_PALETTE
)
4962 size_t amount
= info
->palettesize
;
4963 /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4964 for(i
= info
->palettesize
; i
> 0; i
--)
4966 if(info
->palette
[4 * (i
- 1) + 3] == 255) amount
--;
4969 /*add only alpha channel*/
4970 for(i
= 0; i
< amount
; i
++) ucvector_push_back(&tRNS
, info
->palette
[4 * i
+ 3]);
4972 else if(info
->colortype
== LCT_GREY
)
4974 if(info
->key_defined
)
4976 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
/ 256));
4977 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
% 256));
4980 else if(info
->colortype
== LCT_RGB
)
4982 if(info
->key_defined
)
4984 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
/ 256));
4985 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
% 256));
4986 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_g
/ 256));
4987 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_g
% 256));
4988 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_b
/ 256));
4989 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_b
% 256));
4993 error
= addChunk(out
, "tRNS", tRNS
.data
, tRNS
.size
);
4994 ucvector_cleanup(&tRNS
);
4999 static unsigned addChunk_IDAT(ucvector
* out
, const unsigned char* data
, size_t datasize
,
5000 LodePNGCompressSettings
* zlibsettings
)
5005 /*compress with the Zlib compressor*/
5006 ucvector_init(&zlibdata
);
5007 error
= zlib_compress(&zlibdata
.data
, &zlibdata
.size
, data
, datasize
, zlibsettings
);
5008 if(!error
) error
= addChunk(out
, "IDAT", zlibdata
.data
, zlibdata
.size
);
5009 ucvector_cleanup(&zlibdata
);
5014 static unsigned addChunk_IEND(ucvector
* out
)
5017 error
= addChunk(out
, "IEND", 0, 0);
5021 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5023 static unsigned addChunk_tEXt(ucvector
* out
, const char* keyword
, const char* textstring
)
5028 ucvector_init(&text
);
5029 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&text
, (unsigned char)keyword
[i
]);
5030 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5031 ucvector_push_back(&text
, 0); /*0 termination char*/
5032 for(i
= 0; textstring
[i
] != 0; i
++) ucvector_push_back(&text
, (unsigned char)textstring
[i
]);
5033 error
= addChunk(out
, "tEXt", text
.data
, text
.size
);
5034 ucvector_cleanup(&text
);
5039 static unsigned addChunk_zTXt(ucvector
* out
, const char* keyword
, const char* textstring
,
5040 LodePNGCompressSettings
* zlibsettings
)
5043 ucvector data
, compressed
;
5044 size_t i
, textsize
= MyStrlen(textstring
);
5046 ucvector_init(&data
);
5047 ucvector_init(&compressed
);
5048 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)keyword
[i
]);
5049 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5050 ucvector_push_back(&data
, 0); /*0 termination char*/
5051 ucvector_push_back(&data
, 0); /*compression method: 0*/
5053 error
= zlib_compress(&compressed
.data
, &compressed
.size
,
5054 (unsigned char*)textstring
, textsize
, zlibsettings
);
5057 for(i
= 0; i
< compressed
.size
; i
++) ucvector_push_back(&data
, compressed
.data
[i
]);
5058 error
= addChunk(out
, "zTXt", data
.data
, data
.size
);
5061 ucvector_cleanup(&compressed
);
5062 ucvector_cleanup(&data
);
5066 static unsigned addChunk_iTXt(ucvector
* out
, unsigned compressed
, const char* keyword
, const char* langtag
,
5067 const char* transkey
, const char* textstring
, LodePNGCompressSettings
* zlibsettings
)
5071 size_t i
, textsize
= MyStrlen(textstring
);
5073 ucvector_init(&data
);
5075 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)keyword
[i
]);
5076 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5077 ucvector_push_back(&data
, 0); /*null termination char*/
5078 ucvector_push_back(&data
, compressed
? 1 : 0); /*compression flag*/
5079 ucvector_push_back(&data
, 0); /*compression method*/
5080 for(i
= 0; langtag
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)langtag
[i
]);
5081 ucvector_push_back(&data
, 0); /*null termination char*/
5082 for(i
= 0; transkey
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)transkey
[i
]);
5083 ucvector_push_back(&data
, 0); /*null termination char*/
5087 ucvector compressed_data
;
5088 ucvector_init(&compressed_data
);
5089 error
= zlib_compress(&compressed_data
.data
, &compressed_data
.size
,
5090 (unsigned char*)textstring
, textsize
, zlibsettings
);
5093 for(i
= 0; i
< compressed_data
.size
; i
++) ucvector_push_back(&data
, compressed_data
.data
[i
]);
5095 ucvector_cleanup(&compressed_data
);
5097 else /*not compressed*/
5099 for(i
= 0; textstring
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)textstring
[i
]);
5102 if(!error
) error
= addChunk(out
, "iTXt", data
.data
, data
.size
);
5103 ucvector_cleanup(&data
);
5107 static unsigned addChunk_bKGD(ucvector
* out
, const LodePNGInfo
* info
)
5111 ucvector_init(&bKGD
);
5112 if(info
->color
.colortype
== LCT_GREY
|| info
->color
.colortype
== LCT_GREY_ALPHA
)
5114 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
/ 256));
5115 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256));
5117 else if(info
->color
.colortype
== LCT_RGB
|| info
->color
.colortype
== LCT_RGBA
)
5119 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
/ 256));
5120 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256));
5121 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_g
/ 256));
5122 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_g
% 256));
5123 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_b
/ 256));
5124 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_b
% 256));
5126 else if(info
->color
.colortype
== LCT_PALETTE
)
5128 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256)); /*palette index*/
5131 error
= addChunk(out
, "bKGD", bKGD
.data
, bKGD
.size
);
5132 ucvector_cleanup(&bKGD
);
5137 static unsigned addChunk_tIME(ucvector
* out
, const LodePNGTime
* time
)
5140 unsigned char* data
= (unsigned char*)mymalloc(7);
5141 if(!data
) return 83; /*alloc fail*/
5142 data
[0] = (unsigned char)(time
->year
/ 256);
5143 data
[1] = (unsigned char)(time
->year
% 256);
5144 data
[2] = time
->month
;
5145 data
[3] = time
->day
;
5146 data
[4] = time
->hour
;
5147 data
[5] = time
->minute
;
5148 data
[6] = time
->second
;
5149 error
= addChunk(out
, "tIME", data
, 7);
5154 static unsigned addChunk_pHYs(ucvector
* out
, const LodePNGInfo
* info
)
5158 ucvector_init(&data
);
5160 lodepng_add32bitInt(&data
, info
->phys_x
);
5161 lodepng_add32bitInt(&data
, info
->phys_y
);
5162 ucvector_push_back(&data
, info
->phys_unit
);
5164 error
= addChunk(out
, "pHYs", data
.data
, data
.size
);
5165 ucvector_cleanup(&data
);
5170 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5172 static void filterScanline(unsigned char* out
, const unsigned char* scanline
, const unsigned char* prevline
,
5173 size_t length
, size_t bytewidth
, unsigned char filterType
)
5179 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
];
5184 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5185 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
];
5189 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5190 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
];
5196 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
] - prevline
[i
];
5200 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
];
5206 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
] - prevline
[i
] / 2;
5207 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - ((scanline
[i
- bytewidth
] + prevline
[i
]) / 2);
5211 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5212 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
] / 2;
5218 /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5219 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = (scanline
[i
] - prevline
[i
]);
5220 for(i
= bytewidth
; i
< length
; i
++)
5222 out
[i
] = (scanline
[i
] - paethPredictor(scanline
[i
- bytewidth
], prevline
[i
], prevline
[i
- bytewidth
]));
5227 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5228 /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5229 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = (scanline
[i
] - scanline
[i
- bytewidth
]);
5232 default: return; /*unexisting filter type given*/
5236 /* log2 approximation. A slight bit faster than std::log. */
5237 static float flog2(float f
)
5240 while(f
> 32) { result
+= 4; f
/= 16; }
5241 while(f
> 2) { result
++; f
/= 2; }
5242 return result
+ 1.442695f
* (f
* f
* f
/ 3 - 3 * f
* f
/ 2 + 3 * f
- 1.83333f
);
5245 static unsigned filter(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
,
5246 const LodePNGColorMode
* info
, const LodePNGEncoderSettings
* settings
)
5249 For PNG filter method 0
5250 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5251 the scanlines with 1 extra byte per scanline
5254 unsigned bpp
= lodepng_get_bpp(info
);
5255 /*the width of a scanline in bytes, not including the filter type*/
5256 size_t linebytes
= (w
* bpp
+ 7) / 8;
5257 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5258 size_t bytewidth
= (bpp
+ 7) / 8;
5259 const unsigned char* prevline
= 0;
5262 LodePNGFilterStrategy strategy
= settings
->filter_strategy
;
5265 There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5266 * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5267 use fixed filtering, with the filter None).
5268 * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5269 not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5270 all five filters and select the filter that produces the smallest sum of absolute values per row.
5271 This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5273 If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5274 but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5277 if(settings
->filter_palette_zero
&&
5278 (info
->colortype
== LCT_PALETTE
|| info
->bitdepth
< 8)) strategy
= LFS_ZERO
;
5280 if(bpp
== 0) return 31; /*error: invalid color type*/
5282 if(strategy
== LFS_ZERO
)
5284 for(y
= 0; y
< h
; y
++)
5286 size_t outindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
5287 size_t inindex
= linebytes
* y
;
5288 out
[outindex
] = 0; /*filter type byte*/
5289 filterScanline(&out
[outindex
+ 1], &in
[inindex
], prevline
, linebytes
, bytewidth
, 0);
5290 prevline
= &in
[inindex
];
5293 else if(strategy
== LFS_MINSUM
)
5295 /*adaptive filtering*/
5297 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5298 size_t smallest
= 0;
5299 unsigned type
, bestType
= 0;
5301 for(type
= 0; type
< 5; type
++)
5303 ucvector_init(&attempt
[type
]);
5304 if(!ucvector_resize(&attempt
[type
], linebytes
)) return 83; /*alloc fail*/
5309 for(y
= 0; y
< h
; y
++)
5311 /*try the 5 filter types*/
5312 for(type
= 0; type
< 5; type
++)
5314 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5316 /*calculate the sum of the result*/
5320 for(x
= 0; x
< linebytes
; x
++) sum
[type
] += (unsigned char)(attempt
[type
].data
[x
]);
5324 for(x
= 0; x
< linebytes
; x
++)
5326 /*For differences, each byte should be treated as signed, values above 127 are negative
5327 (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5328 This means filtertype 0 is almost never chosen, but that is justified.*/
5329 signed char s
= (signed char)(attempt
[type
].data
[x
]);
5330 sum
[type
] += s
< 0 ? -s
: s
;
5334 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5335 if(type
== 0 || sum
[type
] < smallest
)
5338 smallest
= sum
[type
];
5342 prevline
= &in
[y
* linebytes
];
5344 /*now fill the out values*/
5345 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5346 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5350 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5352 else if(strategy
== LFS_ENTROPY
)
5355 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5357 unsigned type
, bestType
= 0;
5358 unsigned count
[256];
5360 for(type
= 0; type
< 5; type
++)
5362 ucvector_init(&attempt
[type
]);
5363 if(!ucvector_resize(&attempt
[type
], linebytes
)) return 83; /*alloc fail*/
5366 for(y
= 0; y
< h
; y
++)
5368 /*try the 5 filter types*/
5369 for(type
= 0; type
< 5; type
++)
5371 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5372 for(x
= 0; x
< 256; x
++) count
[x
] = 0;
5373 for(x
= 0; x
< linebytes
; x
++) count
[attempt
[type
].data
[x
]]++;
5374 count
[type
]++; /*the filter type itself is part of the scanline*/
5376 for(x
= 0; x
< 256; x
++)
5378 float p
= count
[x
] / (float)(linebytes
+ 1);
5379 sum
[type
] += count
[x
] == 0 ? 0 : flog2(1 / p
) * p
;
5381 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5382 if(type
== 0 || sum
[type
] < smallest
)
5385 smallest
= sum
[type
];
5389 prevline
= &in
[y
* linebytes
];
5391 /*now fill the out values*/
5392 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5393 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5396 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5398 else if(strategy
== LFS_PREDEFINED
)
5400 for(y
= 0; y
< h
; y
++)
5402 size_t outindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
5403 size_t inindex
= linebytes
* y
;
5404 unsigned type
= settings
->predefined_filters
[y
];
5405 out
[outindex
] = type
; /*filter type byte*/
5406 filterScanline(&out
[outindex
+ 1], &in
[inindex
], prevline
, linebytes
, bytewidth
, type
);
5407 prevline
= &in
[inindex
];
5410 else if(strategy
== LFS_BRUTE_FORCE
)
5412 /*brute force filter chooser.
5413 deflate the scanline after every filter attempt to see which one deflates best.
5414 This is very slow and gives only slightly smaller, sometimes even larger, result*/
5416 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5417 size_t smallest
= 0;
5418 unsigned type
= 0, bestType
= 0;
5419 unsigned char* dummy
;
5420 LodePNGCompressSettings zlibsettings
= settings
->zlibsettings
;
5421 /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5422 to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5423 better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5424 cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5425 zlibsettings
.btype
= 1;
5426 /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5427 images only, so disable it*/
5428 zlibsettings
.custom_zlib
= 0;
5429 zlibsettings
.custom_deflate
= 0;
5430 for(type
= 0; type
< 5; type
++)
5432 ucvector_init(&attempt
[type
]);
5433 ucvector_resize(&attempt
[type
], linebytes
); /*todo: give error if resize failed*/
5435 for(y
= 0; y
< h
; y
++) /*try the 5 filter types*/
5437 for(type
= 0; type
< 5; type
++)
5439 unsigned testsize
= attempt
[type
].size
;
5440 /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5442 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5445 zlib_compress(&dummy
, &size
[type
], attempt
[type
].data
, testsize
, &zlibsettings
);
5447 /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5448 if(type
== 0 || size
[type
] < smallest
)
5451 smallest
= size
[type
];
5454 prevline
= &in
[y
* linebytes
];
5455 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5456 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5458 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5460 else return 88; /* unknown filter strategy */
5465 static void addPaddingBits(unsigned char* out
, const unsigned char* in
,
5466 size_t olinebits
, size_t ilinebits
, unsigned h
)
5468 /*The opposite of the removePaddingBits function
5469 olinebits must be >= ilinebits*/
5471 size_t diff
= olinebits
- ilinebits
;
5472 size_t obp
= 0, ibp
= 0; /*bit pointers*/
5473 for(y
= 0; y
< h
; y
++)
5476 for(x
= 0; x
< ilinebits
; x
++)
5478 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
5479 setBitOfReversedStream(&obp
, out
, bit
);
5481 /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5482 "Use of uninitialised value of size ###" warning from valgrind*/
5483 for(x
= 0; x
< diff
; x
++) setBitOfReversedStream(&obp
, out
, 0);
5488 in: non-interlaced image with size w*h
5489 out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5490 no padding bits between scanlines, but between reduced images so that each
5491 reduced image starts at a byte.
5493 there are no padding bits, not between scanlines, not between reduced images
5494 in has the following size in bits: w * h * bpp.
5495 out is possibly bigger due to padding bits between reduced images
5496 NOTE: comments about padding bits are only relevant if bpp < 8
5498 static void Adam7_interlace(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
5500 unsigned passw
[7], passh
[7];
5501 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
5504 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
5508 for(i
= 0; i
< 7; i
++)
5511 size_t bytewidth
= bpp
/ 8;
5512 for(y
= 0; y
< passh
[i
]; y
++)
5513 for(x
= 0; x
< passw
[i
]; x
++)
5515 size_t pixelinstart
= ((ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * w
+ ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bytewidth
;
5516 size_t pixeloutstart
= passstart
[i
] + (y
* passw
[i
] + x
) * bytewidth
;
5517 for(b
= 0; b
< bytewidth
; b
++)
5519 out
[pixeloutstart
+ b
] = in
[pixelinstart
+ b
];
5524 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5526 for(i
= 0; i
< 7; i
++)
5529 unsigned ilinebits
= bpp
* passw
[i
];
5530 unsigned olinebits
= bpp
* w
;
5531 size_t obp
, ibp
; /*bit pointers (for out and in buffer)*/
5532 for(y
= 0; y
< passh
[i
]; y
++)
5533 for(x
= 0; x
< passw
[i
]; x
++)
5535 ibp
= (ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * olinebits
+ (ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bpp
;
5536 obp
= (8 * passstart
[i
]) + (y
* ilinebits
+ x
* bpp
);
5537 for(b
= 0; b
< bpp
; b
++)
5539 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
5540 setBitOfReversedStream(&obp
, out
, bit
);
5547 /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5548 return value is error**/
5549 static unsigned preProcessScanlines(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
5550 unsigned w
, unsigned h
,
5551 const LodePNGInfo
* info_png
, const LodePNGEncoderSettings
* settings
)
5554 This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5555 *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5556 *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5558 unsigned bpp
= lodepng_get_bpp(&info_png
->color
);
5561 if(info_png
->interlace_method
== 0)
5563 *outsize
= h
+ (h
* ((w
* bpp
+ 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5564 *out
= (unsigned char*)mymalloc(*outsize
);
5565 if(!(*out
) && (*outsize
)) error
= 83; /*alloc fail*/
5569 /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5570 if(bpp
< 8 && w
* bpp
!= ((w
* bpp
+ 7) / 8) * 8)
5572 unsigned char* padded
= (unsigned char*)mymalloc(h
* ((w
* bpp
+ 7) / 8));
5573 if(!padded
) error
= 83; /*alloc fail*/
5576 addPaddingBits(padded
, in
, ((w
* bpp
+ 7) / 8) * 8, w
* bpp
, h
);
5577 error
= filter(*out
, padded
, w
, h
, &info_png
->color
, settings
);
5583 /*we can immediatly filter into the out buffer, no other steps needed*/
5584 error
= filter(*out
, in
, w
, h
, &info_png
->color
, settings
);
5588 else /*interlace_method is 1 (Adam7)*/
5590 unsigned passw
[7], passh
[7];
5591 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
5592 unsigned char* adam7
;
5594 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
5596 *outsize
= filter_passstart
[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5597 *out
= (unsigned char*)mymalloc(*outsize
);
5598 if(!(*out
)) error
= 83; /*alloc fail*/
5600 adam7
= (unsigned char*)mymalloc(passstart
[7]);
5601 if(!adam7
&& passstart
[7]) error
= 83; /*alloc fail*/
5607 Adam7_interlace(adam7
, in
, w
, h
, bpp
);
5608 for(i
= 0; i
< 7; i
++)
5612 unsigned char* padded
= (unsigned char*)mymalloc(padded_passstart
[i
+ 1] - padded_passstart
[i
]);
5613 if(!padded
) ERROR_BREAK(83); /*alloc fail*/
5614 addPaddingBits(padded
, &adam7
[passstart
[i
]],
5615 ((passw
[i
] * bpp
+ 7) / 8) * 8, passw
[i
] * bpp
, passh
[i
]);
5616 error
= filter(&(*out
)[filter_passstart
[i
]], padded
,
5617 passw
[i
], passh
[i
], &info_png
->color
, settings
);
5622 error
= filter(&(*out
)[filter_passstart
[i
]], &adam7
[padded_passstart
[i
]],
5623 passw
[i
], passh
[i
], &info_png
->color
, settings
);
5637 palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5638 returns 0 if the palette is opaque,
5639 returns 1 if the palette has a single color with alpha 0 ==> color key
5640 returns 2 if the palette is semi-translucent.
5642 static unsigned getPaletteTranslucency(const unsigned char* palette
, size_t palettesize
)
5645 unsigned r
= 0, g
= 0, b
= 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5646 for(i
= 0; i
< palettesize
; i
++)
5648 if(!key
&& palette
[4 * i
+ 3] == 0)
5650 r
= palette
[4 * i
+ 0]; g
= palette
[4 * i
+ 1]; b
= palette
[4 * i
+ 2];
5652 i
= (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5654 else if(palette
[4 * i
+ 3] != 255) return 2;
5655 /*when key, no opaque RGB may have key's RGB*/
5656 else if(key
&& r
== palette
[i
* 4 + 0] && g
== palette
[i
* 4 + 1] && b
== palette
[i
* 4 + 2]) return 2;
5661 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5662 static unsigned addUnknownChunks(ucvector
* out
, unsigned char* data
, size_t datasize
)
5664 unsigned char* inchunk
= data
;
5665 while((size_t)(inchunk
- data
) < datasize
)
5667 CERROR_TRY_RETURN(lodepng_chunk_append(&out
->data
, &out
->size
, inchunk
));
5668 out
->allocsize
= out
->size
; /*fix the allocsize again*/
5669 inchunk
= lodepng_chunk_next(inchunk
);
5673 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5675 unsigned lodepng_encode(unsigned char** out
, size_t* outsize
,
5676 const unsigned char* image
, unsigned w
, unsigned h
,
5677 LodePNGState
* state
)
5681 unsigned char* data
= 0; /*uncompressed version of the IDAT chunk data*/
5682 size_t datasize
= 0;
5684 /*provide some proper output values if error will happen*/
5689 lodepng_info_init(&info
);
5690 lodepng_info_copy(&info
, &state
->info_png
);
5692 if((info
.color
.colortype
== LCT_PALETTE
|| state
->encoder
.force_palette
)
5693 && (info
.color
.palettesize
== 0 || info
.color
.palettesize
> 256))
5695 state
->error
= 68; /*invalid palette size, it is only allowed to be 1-256*/
5696 return state
->error
;
5699 if(state
->encoder
.auto_convert
!= LAC_NO
)
5701 state
->error
= doAutoChooseColor(&info
.color
, image
, w
, h
, &state
->info_raw
,
5702 state
->encoder
.auto_convert
);
5704 if(state
->error
) return state
->error
;
5706 if(state
->encoder
.zlibsettings
.windowsize
> 32768)
5708 CERROR_RETURN_ERROR(state
->error
, 60); /*error: windowsize larger than allowed*/
5710 if(state
->encoder
.zlibsettings
.btype
> 2)
5712 CERROR_RETURN_ERROR(state
->error
, 61); /*error: unexisting btype*/
5714 if(state
->info_png
.interlace_method
> 1)
5716 CERROR_RETURN_ERROR(state
->error
, 71); /*error: unexisting interlace mode*/
5719 state
->error
= checkColorValidity(info
.color
.colortype
, info
.color
.bitdepth
);
5720 if(state
->error
) return state
->error
; /*error: unexisting color type given*/
5721 state
->error
= checkColorValidity(state
->info_raw
.colortype
, state
->info_raw
.bitdepth
);
5722 if(state
->error
) return state
->error
; /*error: unexisting color type given*/
5724 if(!lodepng_color_mode_equal(&state
->info_raw
, &info
.color
))
5726 unsigned char* converted
;
5727 size_t size
= (w
* h
* lodepng_get_bpp(&info
.color
) + 7) / 8;
5729 converted
= (unsigned char*)mymalloc(size
);
5730 if(!converted
&& size
) state
->error
= 83; /*alloc fail*/
5733 state
->error
= lodepng_convert(converted
, image
, &info
.color
, &state
->info_raw
, w
, h
);
5735 if(!state
->error
) preProcessScanlines(&data
, &datasize
, converted
, w
, h
, &info
, &state
->encoder
);
5738 else preProcessScanlines(&data
, &datasize
, image
, w
, h
, &info
, &state
->encoder
);
5740 ucvector_init(&outv
);
5741 while(!state
->error
) /*while only executed once, to break on error*/
5743 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5745 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5746 /*write signature and chunks*/
5747 writeSignature(&outv
);
5749 addChunk_IHDR(&outv
, w
, h
, info
.color
.colortype
, info
.color
.bitdepth
, info
.interlace_method
);
5750 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5751 /*unknown chunks between IHDR and PLTE*/
5752 if(info
.unknown_chunks_data
[0])
5754 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[0], info
.unknown_chunks_size
[0]);
5755 if(state
->error
) break;
5757 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5759 if(info
.color
.colortype
== LCT_PALETTE
)
5761 addChunk_PLTE(&outv
, &info
.color
);
5763 if(state
->encoder
.force_palette
&& (info
.color
.colortype
== LCT_RGB
|| info
.color
.colortype
== LCT_RGBA
))
5765 addChunk_PLTE(&outv
, &info
.color
);
5768 if(info
.color
.colortype
== LCT_PALETTE
&& getPaletteTranslucency(info
.color
.palette
, info
.color
.palettesize
) != 0)
5770 addChunk_tRNS(&outv
, &info
.color
);
5772 if((info
.color
.colortype
== LCT_GREY
|| info
.color
.colortype
== LCT_RGB
) && info
.color
.key_defined
)
5774 addChunk_tRNS(&outv
, &info
.color
);
5776 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5777 /*bKGD (must come between PLTE and the IDAt chunks*/
5778 if(info
.background_defined
) addChunk_bKGD(&outv
, &info
);
5779 /*pHYs (must come before the IDAT chunks)*/
5780 if(info
.phys_defined
) addChunk_pHYs(&outv
, &info
);
5782 /*unknown chunks between PLTE and IDAT*/
5783 if(info
.unknown_chunks_data
[1])
5785 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[1], info
.unknown_chunks_size
[1]);
5786 if(state
->error
) break;
5788 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5789 /*IDAT (multiple IDAT chunks must be consecutive)*/
5790 state
->error
= addChunk_IDAT(&outv
, data
, datasize
, &state
->encoder
.zlibsettings
);
5791 if(state
->error
) break;
5792 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5794 if(info
.time_defined
) addChunk_tIME(&outv
, &info
.time
);
5795 /*tEXt and/or zTXt*/
5796 for(i
= 0; i
< info
.text_num
; i
++)
5798 if(MyStrlen(info
.text_keys
[i
]) > 79)
5800 state
->error
= 66; /*text chunk too large*/
5803 if(MyStrlen(info
.text_keys
[i
]) < 1)
5805 state
->error
= 67; /*text chunk too small*/
5808 if(state
->encoder
.text_compression
)
5809 addChunk_zTXt(&outv
, info
.text_keys
[i
], info
.text_strings
[i
], &state
->encoder
.zlibsettings
);
5811 addChunk_tEXt(&outv
, info
.text_keys
[i
], info
.text_strings
[i
]);
5813 /*LodePNG version id in text chunk*/
5814 if(state
->encoder
.add_id
)
5816 unsigned alread_added_id_text
= 0;
5817 for(i
= 0; i
< info
.text_num
; i
++)
5819 if(!strcmp(info
.text_keys
[i
], "LodePNG"))
5821 alread_added_id_text
= 1;
5825 if(alread_added_id_text
== 0)
5826 addChunk_tEXt(&outv
, "LodePNG", VERSION_STRING
); /*it's shorter as tEXt than as zTXt chunk*/
5829 for(i
= 0; i
< info
.itext_num
; i
++)
5831 if(MyStrlen(info
.itext_keys
[i
]) > 79)
5833 state
->error
= 66; /*text chunk too large*/
5836 if(MyStrlen(info
.itext_keys
[i
]) < 1)
5838 state
->error
= 67; /*text chunk too small*/
5841 addChunk_iTXt(&outv
, state
->encoder
.text_compression
,
5842 info
.itext_keys
[i
], info
.itext_langtags
[i
], info
.itext_transkeys
[i
], info
.itext_strings
[i
],
5843 &state
->encoder
.zlibsettings
);
5846 /*unknown chunks between IDAT and IEND*/
5847 if(info
.unknown_chunks_data
[2])
5849 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[2], info
.unknown_chunks_size
[2]);
5850 if(state
->error
) break;
5852 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5854 addChunk_IEND(&outv
);
5856 break; /*this isn't really a while loop; no error happened so break out now!*/
5859 lodepng_info_cleanup(&info
);
5861 /*instead of cleaning the vector up, give it to the output*/
5863 *outsize
= outv
.size
;
5865 return state
->error
;
5868 unsigned lodepng_encode_memory(unsigned char** out
, size_t* outsize
, const unsigned char* image
,
5869 unsigned w
, unsigned h
, LodePNGColorType colortype
, unsigned bitdepth
)
5873 lodepng_state_init(&state
);
5874 state
.info_raw
.colortype
= colortype
;
5875 state
.info_raw
.bitdepth
= bitdepth
;
5876 state
.info_png
.color
.colortype
= colortype
;
5877 state
.info_png
.color
.bitdepth
= bitdepth
;
5878 lodepng_encode(out
, outsize
, image
, w
, h
, &state
);
5879 error
= state
.error
;
5880 lodepng_state_cleanup(&state
);
5884 unsigned lodepng_encode32(unsigned char** out
, size_t* outsize
, const unsigned char* image
, unsigned w
, unsigned h
)
5886 return lodepng_encode_memory(out
, outsize
, image
, w
, h
, LCT_RGBA
, 8);
5889 unsigned lodepng_encode24(unsigned char** out
, size_t* outsize
, const unsigned char* image
, unsigned w
, unsigned h
)
5891 return lodepng_encode_memory(out
, outsize
, image
, w
, h
, LCT_RGB
, 8);
5894 #ifdef LODEPNG_COMPILE_DISK
5895 unsigned lodepng_encode_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
,
5896 LodePNGColorType colortype
, unsigned bitdepth
)
5898 unsigned char* buffer
;
5900 unsigned error
= lodepng_encode_memory(&buffer
, &buffersize
, image
, w
, h
, colortype
, bitdepth
);
5901 if(!error
) error
= lodepng_save_file(buffer
, buffersize
, filename
);
5906 unsigned lodepng_encode32_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
)
5908 return lodepng_encode_file(filename
, image
, w
, h
, LCT_RGBA
, 8);
5911 unsigned lodepng_encode24_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
)
5913 return lodepng_encode_file(filename
, image
, w
, h
, LCT_RGB
, 8);
5915 #endif /*LODEPNG_COMPILE_DISK*/
5917 void lodepng_encoder_settings_init(LodePNGEncoderSettings
* settings
)
5919 lodepng_compress_settings_init(&settings
->zlibsettings
);
5920 settings
->filter_palette_zero
= 1;
5921 settings
->filter_strategy
= LFS_MINSUM
;
5922 settings
->auto_convert
= LAC_AUTO
;
5923 settings
->force_palette
= 0;
5924 settings
->predefined_filters
= 0;
5925 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5926 settings
->add_id
= 0;
5927 settings
->text_compression
= 1;
5928 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5931 #endif /*LODEPNG_COMPILE_ENCODER*/
5932 #endif /*LODEPNG_COMPILE_PNG*/
5934 #ifdef LODEPNG_COMPILE_ERROR_TEXT
5936 This returns the description of a numerical error code in English. This is also
5937 the documentation of all the error codes.
5939 const CHAR16
* lodepng_error_text(unsigned code
)
5943 case 0: return L
"no error, everything went ok";
5944 case 1: return L
"nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5945 case 10: return L
"end of input memory reached without huffman end code"; /*while huffman decoding*/
5946 case 11: return L
"error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5947 case 13: return L
"problem while processing dynamic deflate block";
5948 case 14: return L
"problem while processing dynamic deflate block";
5949 case 15: return L
"problem while processing dynamic deflate block";
5950 case 16: return L
"unexisting code while processing dynamic deflate block";
5951 case 17: return L
"end of out buffer memory reached while inflating";
5952 case 18: return L
"invalid distance code while inflating";
5953 case 19: return L
"end of out buffer memory reached while inflating";
5954 case 20: return L
"invalid deflate block BTYPE encountered while decoding";
5955 case 21: return L
"NLEN is not ones complement of LEN in a deflate block";
5956 /*end of out buffer memory reached while inflating:
5957 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5958 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5959 happen in a normal, well encoded, PNG image.*/
5960 case 22: return L
"end of out buffer memory reached while inflating";
5961 case 23: return L
"end of in buffer memory reached while inflating";
5962 case 24: return L
"invalid FCHECK in zlib header";
5963 case 25: return L
"invalid compression method in zlib header";
5964 case 26: return L
"FDICT encountered in zlib header while it's not used for PNG";
5965 case 27: return L
"PNG file is smaller than a PNG header";
5966 /*Checks the magic file header, the first 8 bytes of the PNG file*/
5967 case 28: return L
"incorrect PNG signature, it's no PNG or corrupted";
5968 case 29: return L
"first chunk is not the header chunk";
5969 case 30: return L
"chunk length too large, chunk broken off at end of file";
5970 case 31: return L
"illegal PNG color type or bpp";
5971 case 32: return L
"illegal PNG compression method";
5972 case 33: return L
"illegal PNG filter method";
5973 case 34: return L
"illegal PNG interlace method";
5974 case 35: return L
"chunk length of a chunk is too large or the chunk too small";
5975 case 36: return L
"illegal PNG filter type encountered";
5976 case 37: return L
"illegal bit depth for this color type given";
5977 case 38: return L
"the palette is too big"; /*more than 256 colors*/
5978 case 39: return L
"more palette alpha values given in tRNS chunk than there are colors in the palette";
5979 case 40: return L
"tRNS chunk has wrong size for greyscale image";
5980 case 41: return L
"tRNS chunk has wrong size for RGB image";
5981 case 42: return L
"tRNS chunk appeared while it was not allowed for this color type";
5982 case 43: return L
"bKGD chunk has wrong size for palette image";
5983 case 44: return L
"bKGD chunk has wrong size for greyscale image";
5984 case 45: return L
"bKGD chunk has wrong size for RGB image";
5985 /*Is the palette too small?*/
5986 case 46: return L
"a value in indexed image is larger than the palette size (bitdepth = 8)";
5987 /*Is the palette too small?*/
5988 case 47: return L
"a value in indexed image is larger than the palette size (bitdepth < 8)";
5989 /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/
5990 case 48: return L
"empty input or file doesn't exist";
5991 case 49: return L
"jumped past memory while generating dynamic huffman tree";
5992 case 50: return L
"jumped past memory while generating dynamic huffman tree";
5993 case 51: return L
"jumped past memory while inflating huffman block";
5994 case 52: return L
"jumped past memory while inflating";
5995 case 53: return L
"size of zlib data too small";
5996 case 54: return L
"repeat symbol in tree while there was no value symbol yet";
5997 /*jumped past tree while generating huffman tree, this could be when the
5998 tree will have more leaves than symbols after generating it out of the
5999 given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
6000 case 55: return L
"jumped past tree while generating huffman tree";
6001 case 56: return L
"given output image colortype or bitdepth not supported for color conversion";
6002 case 57: return L
"invalid CRC encountered (checking CRC can be disabled)";
6003 case 58: return L
"invalid ADLER32 encountered (checking ADLER32 can be disabled)";
6004 case 59: return L
"requested color conversion not supported";
6005 case 60: return L
"invalid window size given in the settings of the encoder (must be 0-32768)";
6006 case 61: return L
"invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
6007 /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
6008 case 62: return L
"conversion from color to greyscale not supported";
6009 case 63: return L
"length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
6010 /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
6011 case 64: return L
"the length of the END symbol 256 in the Huffman tree is 0";
6012 case 66: return L
"the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
6013 case 67: return L
"the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
6014 case 68: return L
"tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
6015 case 69: return L
"unknown chunk type with 'critical' flag encountered by the decoder";
6016 case 71: return L
"unexisting interlace mode given to encoder (must be 0 or 1)";
6017 case 72: return L
"while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
6018 case 73: return L
"invalid tIME chunk size";
6019 case 74: return L
"invalid pHYs chunk size";
6020 /*length could be wrong, or data chopped off*/
6021 case 75: return L
"no null termination char found while decoding text chunk";
6022 case 76: return L
"iTXt chunk too short to contain required bytes";
6023 case 77: return L
"integer overflow in buffer size";
6024 case 78: return L
"failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
6025 case 79: return L
"failed to open file for writing";
6026 case 80: return L
"tried creating a tree of 0 symbols";
6027 case 81: return L
"lazy matching at pos 0 is impossible";
6028 case 82: return L
"color conversion to palette requested while a color isn't in palette";
6029 case 83: return L
"memory allocation failed";
6030 case 84: return L
"given image too small to contain all pixels to be encoded";
6031 case 85: return L
"internal color conversion bug";
6032 case 86: return L
"impossible offset in lz77 encoding (internal bug)";
6033 case 87: return L
"must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
6034 case 88: return L
"invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
6035 case 89: return L
"text chunk keyword too short or long: must have size 1-79";
6037 return L
"unknown error code";
6039 #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
6041 /* ////////////////////////////////////////////////////////////////////////// */
6042 /* ////////////////////////////////////////////////////////////////////////// */
6043 /* // C++ Wrapper // */
6044 /* ////////////////////////////////////////////////////////////////////////// */
6045 /* ////////////////////////////////////////////////////////////////////////// */
6048 #ifdef LODEPNG_COMPILE_CPP
6052 #ifdef LODEPNG_COMPILE_DISK
6053 void load_file(std::vector
<unsigned char>& buffer
, const std::string
& filename
)
6055 std::ifstream
file(filename
.c_str(), std::ios::in
|std::ios::binary
|std::ios::ate
);
6058 std::streamsize size
= 0;
6059 if(file
.seekg(0, std::ios::end
).good()) size
= file
.tellg();
6060 if(file
.seekg(0, std::ios::beg
).good()) size
-= file
.tellg();
6062 /*read contents of the file into the vector*/
6063 buffer
.resize(size_t(size
));
6064 if(size
> 0) file
.read((char*)(&buffer
[0]), size
);
6067 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
6068 void save_file(const std::vector
<unsigned char>& buffer
, const std::string
& filename
)
6070 std::ofstream
file(filename
.c_str(), std::ios::out
|std::ios::binary
);
6071 file
.write(buffer
.empty() ? 0 : (char*)&buffer
[0], std::streamsize(buffer
.size()));
6073 #endif //LODEPNG_COMPILE_DISK
6075 #ifdef LODEPNG_COMPILE_ZLIB
6076 #ifdef LODEPNG_COMPILE_DECODER
6077 unsigned decompress(std::vector
<unsigned char>& out
, const unsigned char* in
, size_t insize
,
6078 const LodePNGDecompressSettings
& settings
)
6080 unsigned char* buffer
= 0;
6081 size_t buffersize
= 0;
6082 unsigned error
= zlib_decompress(&buffer
, &buffersize
, in
, insize
, &settings
);
6085 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6091 unsigned decompress(std::vector
<unsigned char>& out
, const std::vector
<unsigned char>& in
,
6092 const LodePNGDecompressSettings
& settings
)
6094 return decompress(out
, in
.empty() ? 0 : &in
[0], in
.size(), settings
);
6096 #endif //LODEPNG_COMPILE_DECODER
6098 #ifdef LODEPNG_COMPILE_ENCODER
6099 unsigned compress(std::vector
<unsigned char>& out
, const unsigned char* in
, size_t insize
,
6100 const LodePNGCompressSettings
& settings
)
6102 unsigned char* buffer
= 0;
6103 size_t buffersize
= 0;
6104 unsigned error
= zlib_compress(&buffer
, &buffersize
, in
, insize
, &settings
);
6107 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6113 unsigned compress(std::vector
<unsigned char>& out
, const std::vector
<unsigned char>& in
,
6114 const LodePNGCompressSettings
& settings
)
6116 return compress(out
, in
.empty() ? 0 : &in
[0], in
.size(), settings
);
6118 #endif //LODEPNG_COMPILE_ENCODER
6119 #endif //LODEPNG_COMPILE_ZLIB
6122 #ifdef LODEPNG_COMPILE_PNG
6126 lodepng_state_init(this);
6129 State::State(const State
& other
)
6131 lodepng_state_init(this);
6132 lodepng_state_copy(this, &other
);
6137 lodepng_state_cleanup(this);
6140 State
& State::operator=(const State
& other
)
6142 lodepng_state_copy(this, &other
);
6146 #ifdef LODEPNG_COMPILE_DECODER
6148 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
, const unsigned char* in
,
6149 size_t insize
, LodePNGColorType colortype
, unsigned bitdepth
)
6151 unsigned char* buffer
;
6152 unsigned error
= lodepng_decode_memory(&buffer
, &w
, &h
, in
, insize
, colortype
, bitdepth
);
6153 if(buffer
&& !error
)
6156 state
.info_raw
.colortype
= colortype
;
6157 state
.info_raw
.bitdepth
= bitdepth
;
6158 size_t buffersize
= lodepng_get_raw_size(w
, h
, &state
.info_raw
);
6159 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6165 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6166 const std::vector
<unsigned char>& in
, LodePNGColorType colortype
, unsigned bitdepth
)
6168 return decode(out
, w
, h
, in
.empty() ? 0 : &in
[0], (unsigned)in
.size(), colortype
, bitdepth
);
6171 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6173 const unsigned char* in
, size_t insize
)
6175 unsigned char* buffer
;
6176 unsigned error
= lodepng_decode(&buffer
, &w
, &h
, &state
, in
, insize
);
6177 if(buffer
&& !error
)
6179 size_t buffersize
= lodepng_get_raw_size(w
, h
, &state
.info_raw
);
6180 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6186 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6188 const std::vector
<unsigned char>& in
)
6190 return decode(out
, w
, h
, state
, in
.empty() ? 0 : &in
[0], in
.size());
6193 #ifdef LODEPNG_COMPILE_DISK
6194 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
, const std::string
& filename
,
6195 LodePNGColorType colortype
, unsigned bitdepth
)
6197 std::vector
<unsigned char> buffer
;
6198 load_file(buffer
, filename
);
6199 return decode(out
, w
, h
, buffer
, colortype
, bitdepth
);
6201 #endif //LODEPNG_COMPILE_DECODER
6202 #endif //LODEPNG_COMPILE_DISK
6204 #ifdef LODEPNG_COMPILE_ENCODER
6205 unsigned encode(std::vector
<unsigned char>& out
, const unsigned char* in
, unsigned w
, unsigned h
,
6206 LodePNGColorType colortype
, unsigned bitdepth
)
6208 unsigned char* buffer
;
6210 unsigned error
= lodepng_encode_memory(&buffer
, &buffersize
, in
, w
, h
, colortype
, bitdepth
);
6213 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6219 unsigned encode(std::vector
<unsigned char>& out
,
6220 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6221 LodePNGColorType colortype
, unsigned bitdepth
)
6223 if(lodepng_get_raw_size_lct(w
, h
, colortype
, bitdepth
) > in
.size()) return 84;
6224 return encode(out
, in
.empty() ? 0 : &in
[0], w
, h
, colortype
, bitdepth
);
6227 unsigned encode(std::vector
<unsigned char>& out
,
6228 const unsigned char* in
, unsigned w
, unsigned h
,
6231 unsigned char* buffer
;
6233 unsigned error
= lodepng_encode(&buffer
, &buffersize
, in
, w
, h
, &state
);
6236 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6242 unsigned encode(std::vector
<unsigned char>& out
,
6243 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6246 if(lodepng_get_raw_size(w
, h
, &state
.info_raw
) > in
.size()) return 84;
6247 return encode(out
, in
.empty() ? 0 : &in
[0], w
, h
, state
);
6250 #ifdef LODEPNG_COMPILE_DISK
6251 unsigned encode(const std::string
& filename
,
6252 const unsigned char* in
, unsigned w
, unsigned h
,
6253 LodePNGColorType colortype
, unsigned bitdepth
)
6255 std::vector
<unsigned char> buffer
;
6256 unsigned error
= encode(buffer
, in
, w
, h
, colortype
, bitdepth
);
6257 if(!error
) save_file(buffer
, filename
);
6261 unsigned encode(const std::string
& filename
,
6262 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6263 LodePNGColorType colortype
, unsigned bitdepth
)
6265 if(lodepng_get_raw_size_lct(w
, h
, colortype
, bitdepth
) > in
.size()) return 84;
6266 return encode(filename
, in
.empty() ? 0 : &in
[0], w
, h
, colortype
, bitdepth
);
6268 #endif //LODEPNG_COMPILE_DISK
6269 #endif //LODEPNG_COMPILE_ENCODER
6270 #endif //LODEPNG_COMPILE_PNG
6271 } //namespace lodepng
6272 #endif /*LODEPNG_COMPILE_CPP*/
6275 typedef struct _lode_color
{
6282 EG_IMAGE
* egDecodePNG(IN UINT8
*FileData
, IN UINTN FileDataLength
, IN UINTN IconSize
, IN BOOLEAN WantAlpha
) {
6283 EG_IMAGE
*NewImage
= NULL
;
6284 unsigned Error
, Width
, Height
;
6285 EG_PIXEL
*PixelData
;
6286 lode_color
*LodeData
;
6289 Error
= lodepng_decode_memory((unsigned char **) &PixelData
, &Width
, &Height
, (unsigned char*) FileData
,
6290 (size_t) FileDataLength
, LCT_RGBA
, 8);
6296 // allocate image structure and buffer
6297 NewImage
= egCreateImage(Width
, Height
, WantAlpha
);
6298 if ((NewImage
== NULL
) || (NewImage
->Width
!= Width
) || (NewImage
->Height
!= Height
))
6301 LodeData
= (lode_color
*) PixelData
;
6302 for (i
= 0; i
< (NewImage
->Height
* NewImage
->Width
); i
++) {
6303 NewImage
->PixelData
[i
].r
= LodeData
[i
].red
;
6304 NewImage
->PixelData
[i
].g
= LodeData
[i
].green
;
6305 NewImage
->PixelData
[i
].b
= LodeData
[i
].blue
;
6307 NewImage
->PixelData
[i
].a
= LodeData
[i
].alpha
;
6312 } // EG_IMAGE * egDecodePNG()