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 // EFI's equivalent of realloc requires the original buffer's size as an
70 // input parameter, which the standard libc realloc does not require. Thus,
71 // I've modified mymalloc() to allocate more memory to store this data,
72 // and myrealloc() can then read it when required. Because the size is
73 // stored at the start of the allocated area, these functions are NOT
74 // interchangeable with the standard EFI functions; memory allocated via
75 // mymalloc() should be freed via myfree(), and myfree() should NOT be
76 // used with memory allocated via AllocatePool() or AllocateZeroPool()!
78 static void *mymalloc(size_t size
) {
81 ptr
= AllocateZeroPool(size
+ sizeof(size_t));
83 *(size_t *) ptr
= size
;
84 return ((size_t *) ptr
) + 1;
90 static void myfree (void *ptr
) {
92 ptr
= (void *) (((size_t *) ptr
) - 1);
97 static size_t report_size(void *ptr
) {
99 return * (((size_t *) ptr
) - 1);
104 static void *myrealloc(void *ptr
, size_t new_size
) {
108 new_pool
= mymalloc(new_size
);
109 if (new_pool
&& ptr
) {
110 old_size
= report_size(ptr
);
111 CopyMem(new_pool
, ptr
, (old_size
< new_size
) ? old_size
: new_size
);
116 // Finds length of ASCII string, which MUST be NULL-terminated.
117 int MyStrlen(const char *InString
) {
121 while (InString
[Length
] != '\0')
127 /* ////////////////////////////////////////////////////////////////////////// */
128 /* ////////////////////////////////////////////////////////////////////////// */
129 /* // Tools for C, and common code for PNG and Zlib. // */
130 /* ////////////////////////////////////////////////////////////////////////// */
131 /* ////////////////////////////////////////////////////////////////////////// */
134 Often in case of an error a value is assigned to a variable and then it breaks
135 out of a loop (to go to the cleanup phase of a function). This macro does that.
136 It makes the error handling code shorter and more readable.
138 Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
140 #define CERROR_BREAK(errorvar, code)\
146 /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
147 #define ERROR_BREAK(code) CERROR_BREAK(error, code)
149 /*Set error var to the error code, and return it.*/
150 #define CERROR_RETURN_ERROR(errorvar, code)\
156 /*Try the code, if it returns error, also return the error.*/
157 #define CERROR_TRY_RETURN(call)\
159 unsigned error = call;\
160 if(error) return error;\
164 About uivector, ucvector and string:
165 -All of them wrap dynamic arrays or text strings in a similar way.
166 -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
167 -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
168 -They're not used in the interface, only internally in this file as static functions.
169 -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
172 #ifdef LODEPNG_COMPILE_ZLIB
173 /*dynamic vector of unsigned ints*/
175 typedef struct uivector
178 size_t size
; /*size in number of unsigned longs*/
179 size_t allocsize
; /*allocated size in bytes*/
182 static void uivector_cleanup(void* p
)
184 ((uivector
*)p
)->size
= ((uivector
*)p
)->allocsize
= 0;
185 myfree(((uivector
*)p
)->data
);
186 ((uivector
*)p
)->data
= NULL
;
189 /*returns 1 if success, 0 if failure ==> nothing done*/
190 static unsigned uivector_resize(uivector
* p
, size_t size
)
192 if(size
* sizeof(unsigned) > p
->allocsize
)
194 size_t newsize
= size
* sizeof(unsigned) * 2;
195 void* data
= myrealloc(p
->data
, newsize
);
198 p
->allocsize
= newsize
;
199 p
->data
= (unsigned*)data
;
208 /*resize and give all new elements the value*/
209 static unsigned uivector_resizev(uivector
* p
, size_t size
, unsigned value
)
211 size_t oldsize
= p
->size
, i
;
212 if(!uivector_resize(p
, size
)) return 0;
213 for(i
= oldsize
; i
< size
; i
++) p
->data
[i
] = value
;
217 static void uivector_init(uivector
* p
)
220 p
->size
= p
->allocsize
= 0;
223 #ifdef LODEPNG_COMPILE_ENCODER
224 /*returns 1 if success, 0 if failure ==> nothing done*/
225 static unsigned uivector_push_back(uivector
* p
, unsigned c
)
227 if(!uivector_resize(p
, p
->size
+ 1)) return 0;
228 p
->data
[p
->size
- 1] = c
;
232 /*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/
233 static unsigned uivector_copy(uivector
* p
, const uivector
* q
)
236 if(!uivector_resize(p
, q
->size
)) return 0;
237 for(i
= 0; i
< q
->size
; i
++) p
->data
[i
] = q
->data
[i
];
241 static void uivector_swap(uivector
* p
, uivector
* q
)
245 tmp
= p
->size
; p
->size
= q
->size
; q
->size
= tmp
;
246 tmp
= p
->allocsize
; p
->allocsize
= q
->allocsize
; q
->allocsize
= tmp
;
247 tmpp
= p
->data
; p
->data
= q
->data
; q
->data
= tmpp
;
249 #endif /*LODEPNG_COMPILE_ENCODER*/
250 #endif /*LODEPNG_COMPILE_ZLIB*/
252 /* /////////////////////////////////////////////////////////////////////////// */
254 /*dynamic vector of unsigned chars*/
255 typedef struct ucvector
258 size_t size
; /*used size*/
259 size_t allocsize
; /*allocated size*/
262 /*returns 1 if success, 0 if failure ==> nothing done*/
263 static unsigned ucvector_resize(ucvector
* p
, size_t size
)
265 if(size
* sizeof(unsigned char) > p
->allocsize
)
267 size_t newsize
= size
* sizeof(unsigned char) * 2;
268 void* data
= myrealloc(p
->data
, newsize
);
271 p
->allocsize
= newsize
;
272 p
->data
= (unsigned char*)data
;
275 else return 0; /*error: not enough memory*/
281 #ifdef LODEPNG_COMPILE_PNG
283 static void ucvector_cleanup(void* p
)
285 ((ucvector
*)p
)->size
= ((ucvector
*)p
)->allocsize
= 0;
286 myfree(((ucvector
*)p
)->data
);
287 ((ucvector
*)p
)->data
= NULL
;
290 static void ucvector_init(ucvector
* p
)
293 p
->size
= p
->allocsize
= 0;
296 #ifdef LODEPNG_COMPILE_DECODER
297 /*resize and give all new elements the value*/
298 static unsigned ucvector_resizev(ucvector
* p
, size_t size
, unsigned char value
)
300 size_t oldsize
= p
->size
, i
;
301 if(!ucvector_resize(p
, size
)) return 0;
302 for(i
= oldsize
; i
< size
; i
++) p
->data
[i
] = value
;
305 #endif /*LODEPNG_COMPILE_DECODER*/
306 #endif /*LODEPNG_COMPILE_PNG*/
308 #ifdef LODEPNG_COMPILE_ZLIB
309 /*you can both convert from vector to buffer&size and vica versa. If you use
310 init_buffer to take over a buffer and size, it is not needed to use cleanup*/
311 static void ucvector_init_buffer(ucvector
* p
, unsigned char* buffer
, size_t size
)
314 p
->allocsize
= p
->size
= size
;
316 #endif /*LODEPNG_COMPILE_ZLIB*/
318 #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
319 /*returns 1 if success, 0 if failure ==> nothing done*/
320 static unsigned ucvector_push_back(ucvector
* p
, unsigned char c
)
322 if(!ucvector_resize(p
, p
->size
+ 1)) return 0;
323 p
->data
[p
->size
- 1] = c
;
326 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
329 /* ////////////////////////////////////////////////////////////////////////// */
331 #ifdef LODEPNG_COMPILE_PNG
332 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
333 /*returns 1 if success, 0 if failure ==> nothing done*/
334 static unsigned string_resize(char** out
, size_t size
)
336 char* data
= (char*)myrealloc(*out
, size
+ 1);
339 data
[size
] = 0; /*null termination char*/
345 /*init a {char*, size_t} pair for use as string*/
346 static void string_init(char** out
)
349 string_resize(out
, 0);
352 /*free the above pair again*/
353 static void string_cleanup(char** out
)
359 static void string_set(char** out
, const char* in
)
361 size_t insize
= MyStrlen(in
), i
= 0;
362 if(string_resize(out
, insize
))
364 for(i
= 0; i
< insize
; i
++)
370 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
371 #endif /*LODEPNG_COMPILE_PNG*/
373 /* ////////////////////////////////////////////////////////////////////////// */
375 unsigned lodepng_read32bitInt(const unsigned char* buffer
)
377 return (buffer
[0] << 24) | (buffer
[1] << 16) | (buffer
[2] << 8) | buffer
[3];
380 #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
381 /*buffer must have at least 4 allocated bytes available*/
382 static void lodepng_set32bitInt(unsigned char* buffer
, unsigned value
)
384 buffer
[0] = (unsigned char)((value
>> 24) & 0xff);
385 buffer
[1] = (unsigned char)((value
>> 16) & 0xff);
386 buffer
[2] = (unsigned char)((value
>> 8) & 0xff);
387 buffer
[3] = (unsigned char)((value
) & 0xff);
389 #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
391 #ifdef LODEPNG_COMPILE_ENCODER
392 static void lodepng_add32bitInt(ucvector
* buffer
, unsigned value
)
394 ucvector_resize(buffer
, buffer
->size
+ 4); /*todo: give error if resize failed*/
395 lodepng_set32bitInt(&buffer
->data
[buffer
->size
- 4], value
);
397 #endif /*LODEPNG_COMPILE_ENCODER*/
399 /* ////////////////////////////////////////////////////////////////////////// */
401 /* ////////////////////////////////////////////////////////////////////////// */
403 #ifdef LODEPNG_COMPILE_DISK
405 unsigned lodepng_load_file(unsigned char** out
, size_t* outsize
, const char* filename
)
410 /*provide some proper output values if error will happen*/
414 file
= fopen(filename
, "rb");
418 fseek(file
, 0 , SEEK_END
);
422 /*read contents of the file into the vector*/
424 *out
= (unsigned char*)mymalloc((size_t)size
);
425 if(size
&& (*out
)) (*outsize
) = fread(*out
, 1, (size_t)size
, file
);
428 if(!(*out
) && size
) return 83; /*the above malloc failed*/
432 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
433 unsigned lodepng_save_file(const unsigned char* buffer
, size_t buffersize
, const char* filename
)
436 file
= fopen(filename
, "wb" );
438 fwrite((char*)buffer
, 1 , buffersize
, file
);
443 #endif /*LODEPNG_COMPILE_DISK*/
445 /* ////////////////////////////////////////////////////////////////////////// */
446 /* ////////////////////////////////////////////////////////////////////////// */
447 /* // End of common code and tools. Begin of Zlib related code. // */
448 /* ////////////////////////////////////////////////////////////////////////// */
449 /* ////////////////////////////////////////////////////////////////////////// */
451 #ifdef LODEPNG_COMPILE_ZLIB
452 #ifdef LODEPNG_COMPILE_ENCODER
453 /*TODO: this ignores potential out of memory errors*/
454 static void addBitToStream(size_t* bitpointer
, ucvector
* bitstream
, unsigned char bit
)
456 /*add a new byte at the end*/
457 if((*bitpointer
) % 8 == 0) ucvector_push_back(bitstream
, (unsigned char)0);
458 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
459 (bitstream
->data
[bitstream
->size
- 1]) |= (bit
<< ((*bitpointer
) & 0x7));
463 static void addBitsToStream(size_t* bitpointer
, ucvector
* bitstream
, unsigned value
, size_t nbits
)
466 for(i
= 0; i
< nbits
; i
++) addBitToStream(bitpointer
, bitstream
, (unsigned char)((value
>> i
) & 1));
469 static void addBitsToStreamReversed(size_t* bitpointer
, ucvector
* bitstream
, unsigned value
, size_t nbits
)
472 for(i
= 0; i
< nbits
; i
++) addBitToStream(bitpointer
, bitstream
, (unsigned char)((value
>> (nbits
- 1 - i
)) & 1));
474 #endif /*LODEPNG_COMPILE_ENCODER*/
476 #ifdef LODEPNG_COMPILE_DECODER
478 #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
480 static unsigned char readBitFromStream(size_t* bitpointer
, const unsigned char* bitstream
)
482 unsigned char result
= (unsigned char)(READBIT(*bitpointer
, bitstream
));
487 static unsigned readBitsFromStream(size_t* bitpointer
, const unsigned char* bitstream
, size_t nbits
)
489 unsigned result
= 0, i
;
490 for(i
= 0; i
< nbits
; i
++)
492 result
+= ((unsigned)READBIT(*bitpointer
, bitstream
)) << i
;
497 #endif /*LODEPNG_COMPILE_DECODER*/
499 /* ////////////////////////////////////////////////////////////////////////// */
500 /* / Deflate - Huffman / */
501 /* ////////////////////////////////////////////////////////////////////////// */
503 #define FIRST_LENGTH_CODE_INDEX 257
504 #define LAST_LENGTH_CODE_INDEX 285
505 /*256 literals, the end code, some length codes, and 2 unused codes*/
506 #define NUM_DEFLATE_CODE_SYMBOLS 288
507 /*the distance codes have their own symbols, 30 used, 2 unused*/
508 #define NUM_DISTANCE_SYMBOLS 32
509 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
510 #define NUM_CODE_LENGTH_CODES 19
512 /*the base lengths represented by codes 257-285*/
513 static const unsigned LENGTHBASE
[29]
514 = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
515 67, 83, 99, 115, 131, 163, 195, 227, 258};
517 /*the extra bits used by codes 257-285 (added to base length)*/
518 static const unsigned LENGTHEXTRA
[29]
519 = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
520 4, 4, 4, 4, 5, 5, 5, 5, 0};
522 /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
523 static const unsigned DISTANCEBASE
[30]
524 = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
525 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
527 /*the extra bits of backwards distances (added to base)*/
528 static const unsigned DISTANCEEXTRA
[30]
529 = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
530 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
532 /*the order in which "code length alphabet code lengths" are stored, out of this
533 the huffman tree of the dynamic huffman tree lengths is generated*/
534 static const unsigned CLCL_ORDER
[NUM_CODE_LENGTH_CODES
]
535 = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
537 /* ////////////////////////////////////////////////////////////////////////// */
540 Huffman tree struct, containing multiple representations of the tree
543 typedef struct HuffmanTree
547 unsigned* lengths
; /*the lengths of the codes of the 1d-tree*/
548 unsigned maxbitlen
; /*maximum number of bits a single code can get*/
549 unsigned numcodes
; /*number of symbols in the alphabet = number of codes*/
552 /*function used for debug purposes to draw the tree in ascii art with C++*/
553 /*#include <iostream>
554 static void HuffmanTree_draw(HuffmanTree* tree)
556 std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
557 for(size_t i = 0; i < tree->tree1d.size; i++)
559 if(tree->lengths.data[i])
560 std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
562 std::cout << std::endl;
565 static void HuffmanTree_init(HuffmanTree
* tree
)
572 static void HuffmanTree_cleanup(HuffmanTree
* tree
)
574 myfree(tree
->tree2d
);
575 myfree(tree
->tree1d
);
576 myfree(tree
->lengths
);
579 /*the tree representation used by the decoder. return value is error*/
580 static unsigned HuffmanTree_make2DTree(HuffmanTree
* tree
)
582 unsigned nodefilled
= 0; /*up to which node it is filled*/
583 unsigned treepos
= 0; /*position in the tree (1 of the numcodes columns)*/
586 tree
->tree2d
= (unsigned*)mymalloc(tree
->numcodes
* 2 * sizeof(unsigned));
587 if(!tree
->tree2d
) return 83; /*alloc fail*/
590 convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
591 uninited, a value >= numcodes is an address to another bit, a value < numcodes
592 is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
593 many columns as codes - 1.
594 A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
595 Here, the internal nodes are stored (what their 0 and 1 option point to).
596 There is only memory for such good tree currently, if there are more nodes
597 (due to too long length codes), error 55 will happen
599 for(n
= 0; n
< tree
->numcodes
* 2; n
++)
601 tree
->tree2d
[n
] = 32767; /*32767 here means the tree2d isn't filled there yet*/
604 for(n
= 0; n
< tree
->numcodes
; n
++) /*the codes*/
606 for(i
= 0; i
< tree
->lengths
[n
]; i
++) /*the bits for this code*/
608 unsigned char bit
= (unsigned char)((tree
->tree1d
[n
] >> (tree
->lengths
[n
] - i
- 1)) & 1);
609 if(treepos
> tree
->numcodes
- 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/
610 if(tree
->tree2d
[2 * treepos
+ bit
] == 32767) /*not yet filled in*/
612 if(i
+ 1 == tree
->lengths
[n
]) /*last bit*/
614 tree
->tree2d
[2 * treepos
+ bit
] = n
; /*put the current code in it*/
619 /*put address of the next step in here, first that address has to be found of course
620 (it's just nodefilled + 1)...*/
622 /*addresses encoded with numcodes added to it*/
623 tree
->tree2d
[2 * treepos
+ bit
] = nodefilled
+ tree
->numcodes
;
624 treepos
= nodefilled
;
627 else treepos
= tree
->tree2d
[2 * treepos
+ bit
] - tree
->numcodes
;
631 for(n
= 0; n
< tree
->numcodes
* 2; n
++)
633 if(tree
->tree2d
[n
] == 32767) tree
->tree2d
[n
] = 0; /*remove possible remaining 32767's*/
640 Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
641 numcodes, lengths and maxbitlen must already be filled in correctly. return
644 static unsigned HuffmanTree_makeFromLengths2(HuffmanTree
* tree
)
648 unsigned bits
, n
, error
= 0;
650 uivector_init(&blcount
);
651 uivector_init(&nextcode
);
653 tree
->tree1d
= (unsigned*)mymalloc(tree
->numcodes
* sizeof(unsigned));
654 if(!tree
->tree1d
) error
= 83; /*alloc fail*/
656 if(!uivector_resizev(&blcount
, tree
->maxbitlen
+ 1, 0)
657 || !uivector_resizev(&nextcode
, tree
->maxbitlen
+ 1, 0))
658 error
= 83; /*alloc fail*/
662 /*step 1: count number of instances of each code length*/
663 for(bits
= 0; bits
< tree
->numcodes
; bits
++) blcount
.data
[tree
->lengths
[bits
]]++;
664 /*step 2: generate the nextcode values*/
665 for(bits
= 1; bits
<= tree
->maxbitlen
; bits
++)
667 nextcode
.data
[bits
] = (nextcode
.data
[bits
- 1] + blcount
.data
[bits
- 1]) << 1;
669 /*step 3: generate all the codes*/
670 for(n
= 0; n
< tree
->numcodes
; n
++)
672 if(tree
->lengths
[n
] != 0) tree
->tree1d
[n
] = nextcode
.data
[tree
->lengths
[n
]]++;
676 uivector_cleanup(&blcount
);
677 uivector_cleanup(&nextcode
);
679 if(!error
) return HuffmanTree_make2DTree(tree
);
684 given the code lengths (as stored in the PNG file), generate the tree as defined
685 by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
686 return value is error.
688 static unsigned HuffmanTree_makeFromLengths(HuffmanTree
* tree
, const unsigned* bitlen
,
689 size_t numcodes
, unsigned maxbitlen
)
692 tree
->lengths
= (unsigned*)mymalloc(numcodes
* sizeof(unsigned));
693 if(!tree
->lengths
) return 83; /*alloc fail*/
694 for(i
= 0; i
< numcodes
; i
++) tree
->lengths
[i
] = bitlen
[i
];
695 tree
->numcodes
= (unsigned)numcodes
; /*number of symbols*/
696 tree
->maxbitlen
= maxbitlen
;
697 return HuffmanTree_makeFromLengths2(tree
);
700 #ifdef LODEPNG_COMPILE_ENCODER
703 A coin, this is the terminology used for the package-merge algorithm and the
704 coin collector's problem. This is used to generate the huffman tree.
705 A coin can be multiple coins (when they're merged)
710 float weight
; /*the sum of all weights in this coin*/
713 static void coin_init(Coin
* c
)
715 uivector_init(&c
->symbols
);
718 /*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/
719 static void coin_cleanup(void* c
)
721 uivector_cleanup(&((Coin
*)c
)->symbols
);
724 static void coin_copy(Coin
* c1
, const Coin
* c2
)
726 c1
->weight
= c2
->weight
;
727 uivector_copy(&c1
->symbols
, &c2
->symbols
);
730 static void add_coins(Coin
* c1
, const Coin
* c2
)
733 for(i
= 0; i
< c2
->symbols
.size
; i
++) uivector_push_back(&c1
->symbols
, c2
->symbols
.data
[i
]);
734 c1
->weight
+= c2
->weight
;
737 static void init_coins(Coin
* coins
, size_t num
)
740 for(i
= 0; i
< num
; i
++) coin_init(&coins
[i
]);
743 static void cleanup_coins(Coin
* coins
, size_t num
)
746 for(i
= 0; i
< num
; i
++) coin_cleanup(&coins
[i
]);
750 This uses a simple combsort to sort the data. This function is not critical for
751 overall encoding speed and the data amount isn't that large.
753 static void sort_coins(Coin
* data
, size_t amount
)
756 unsigned char swapped
= 0;
757 while((gap
> 1) || swapped
)
760 gap
= (gap
* 10) / 13; /*shrink factor 1.3*/
761 if(gap
== 9 || gap
== 10) gap
= 11; /*combsort11*/
764 for(i
= 0; i
< amount
- gap
; i
++)
767 if(data
[j
].weight
< data
[i
].weight
)
769 float temp
= data
[j
].weight
; data
[j
].weight
= data
[i
].weight
; data
[i
].weight
= temp
;
770 uivector_swap(&data
[i
].symbols
, &data
[j
].symbols
);
777 static unsigned append_symbol_coins(Coin
* coins
, const unsigned* frequencies
, unsigned numcodes
, size_t sum
)
780 unsigned j
= 0; /*index of present symbols*/
781 for(i
= 0; i
< numcodes
; i
++)
783 if(frequencies
[i
] != 0) /*only include symbols that are present*/
785 coins
[j
].weight
= frequencies
[i
] / (float)sum
;
786 uivector_push_back(&coins
[j
].symbols
, i
);
793 unsigned lodepng_huffman_code_lengths(unsigned* lengths
, const unsigned* frequencies
,
794 size_t numcodes
, unsigned maxbitlen
)
797 size_t sum
= 0, numpresent
= 0;
799 Coin
* coins
; /*the coins of the currently calculated row*/
800 Coin
* prev_row
; /*the previous row of coins*/
804 if(numcodes
== 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
806 for(i
= 0; i
< numcodes
; i
++)
808 if(frequencies
[i
] > 0)
811 sum
+= frequencies
[i
];
815 for(i
= 0; i
< numcodes
; i
++) lengths
[i
] = 0;
817 /*ensure at least two present symbols. There should be at least one symbol
818 according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To
819 make these work as well ensure there are at least two symbols. The
820 Package-Merge code below also doesn't work correctly if there's only one
821 symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
824 lengths
[0] = lengths
[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
826 else if(numpresent
== 1)
828 for(i
= 0; i
< numcodes
; i
++)
833 lengths
[i
== 0 ? 1 : 0] = 1;
840 /*Package-Merge algorithm represented by coin collector's problem
841 For every symbol, maxbitlen coins will be created*/
843 coinmem
= numpresent
* 2; /*max amount of coins needed with the current algo*/
844 coins
= (Coin
*)mymalloc(sizeof(Coin
) * coinmem
);
845 prev_row
= (Coin
*)mymalloc(sizeof(Coin
) * coinmem
);
846 if(!coins
|| !prev_row
) return 83; /*alloc fail*/
847 init_coins(coins
, coinmem
);
848 init_coins(prev_row
, coinmem
);
850 /*first row, lowest denominator*/
851 error
= append_symbol_coins(coins
, frequencies
, numcodes
, sum
);
852 numcoins
= numpresent
;
853 sort_coins(coins
, numcoins
);
856 unsigned numprev
= 0;
857 for(j
= 1; j
<= maxbitlen
&& !error
; j
++) /*each of the remaining rows*/
861 /*swap prev_row and coins, and their amounts*/
862 tempcoins
= prev_row
; prev_row
= coins
; coins
= tempcoins
;
863 tempnum
= numprev
; numprev
= numcoins
; numcoins
= tempnum
;
865 cleanup_coins(coins
, numcoins
);
866 init_coins(coins
, numcoins
);
870 /*fill in the merged coins of the previous row*/
871 for(i
= 0; i
+ 1 < numprev
; i
+= 2)
873 /*merge prev_row[i] and prev_row[i + 1] into new coin*/
874 Coin
* coin
= &coins
[numcoins
++];
875 coin_copy(coin
, &prev_row
[i
]);
876 add_coins(coin
, &prev_row
[i
+ 1]);
878 /*fill in all the original symbols again*/
881 error
= append_symbol_coins(coins
+ numcoins
, frequencies
, numcodes
, sum
);
882 numcoins
+= numpresent
;
884 sort_coins(coins
, numcoins
);
890 /*calculate the lenghts of each symbol, as the amount of times a coin of each symbol is used*/
891 for(i
= 0; i
< numpresent
- 1; i
++)
893 Coin
* coin
= &coins
[i
];
894 for(j
= 0; j
< coin
->symbols
.size
; j
++) lengths
[coin
->symbols
.data
[j
]]++;
898 cleanup_coins(coins
, coinmem
);
900 cleanup_coins(prev_row
, coinmem
);
907 /*Create the Huffman tree given the symbol frequencies*/
908 static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree
* tree
, const unsigned* frequencies
,
909 size_t mincodes
, size_t numcodes
, unsigned maxbitlen
)
912 while(!frequencies
[numcodes
- 1] && numcodes
> mincodes
) numcodes
--; /*trim zeroes*/
913 tree
->maxbitlen
= maxbitlen
;
914 tree
->numcodes
= (unsigned)numcodes
; /*number of symbols*/
915 tree
->lengths
= (unsigned*)myrealloc(tree
->lengths
, numcodes
* sizeof(unsigned));
916 if(!tree
->lengths
) return 83; /*alloc fail*/
917 /*initialize all lengths to 0*/
918 SetMem(tree
->lengths
, numcodes
* sizeof(unsigned), 0);
920 error
= lodepng_huffman_code_lengths(tree
->lengths
, frequencies
, numcodes
, maxbitlen
);
921 if(!error
) error
= HuffmanTree_makeFromLengths2(tree
);
925 static unsigned HuffmanTree_getCode(const HuffmanTree
* tree
, unsigned index
)
927 return tree
->tree1d
[index
];
930 static unsigned HuffmanTree_getLength(const HuffmanTree
* tree
, unsigned index
)
932 return tree
->lengths
[index
];
934 #endif /*LODEPNG_COMPILE_ENCODER*/
936 /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
937 static unsigned generateFixedLitLenTree(HuffmanTree
* tree
)
939 unsigned i
, error
= 0;
940 unsigned* bitlen
= (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS
* sizeof(unsigned));
941 if(!bitlen
) return 83; /*alloc fail*/
943 /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
944 for(i
= 0; i
<= 143; i
++) bitlen
[i
] = 8;
945 for(i
= 144; i
<= 255; i
++) bitlen
[i
] = 9;
946 for(i
= 256; i
<= 279; i
++) bitlen
[i
] = 7;
947 for(i
= 280; i
<= 287; i
++) bitlen
[i
] = 8;
949 error
= HuffmanTree_makeFromLengths(tree
, bitlen
, NUM_DEFLATE_CODE_SYMBOLS
, 15);
955 /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
956 static unsigned generateFixedDistanceTree(HuffmanTree
* tree
)
958 unsigned i
, error
= 0;
959 unsigned* bitlen
= (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS
* sizeof(unsigned));
960 if(!bitlen
) return 83; /*alloc fail*/
962 /*there are 32 distance codes, but 30-31 are unused*/
963 for(i
= 0; i
< NUM_DISTANCE_SYMBOLS
; i
++) bitlen
[i
] = 5;
964 error
= HuffmanTree_makeFromLengths(tree
, bitlen
, NUM_DISTANCE_SYMBOLS
, 15);
970 #ifdef LODEPNG_COMPILE_DECODER
973 returns the code, or (unsigned)(-1) if error happened
974 inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
976 static unsigned huffmanDecodeSymbol(const unsigned char* in
, size_t* bp
,
977 const HuffmanTree
* codetree
, size_t inbitlength
)
979 unsigned treepos
= 0, ct
;
982 if(*bp
>= inbitlength
) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
984 decode the symbol from the tree. The "readBitFromStream" code is inlined in
985 the expression below because this is the biggest bottleneck while decoding
987 ct
= codetree
->tree2d
[(treepos
<< 1) + READBIT(*bp
, in
)];
989 if(ct
< codetree
->numcodes
) return ct
; /*the symbol is decoded, return it*/
990 else treepos
= ct
- codetree
->numcodes
; /*symbol not yet decoded, instead move tree position*/
992 if(treepos
>= codetree
->numcodes
) return (unsigned)(-1); /*error: it appeared outside the codetree*/
995 #endif /*LODEPNG_COMPILE_DECODER*/
997 #ifdef LODEPNG_COMPILE_DECODER
999 /* ////////////////////////////////////////////////////////////////////////// */
1000 /* / Inflator (Decompressor) / */
1001 /* ////////////////////////////////////////////////////////////////////////// */
1003 /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
1004 static void getTreeInflateFixed(HuffmanTree
* tree_ll
, HuffmanTree
* tree_d
)
1006 /*TODO: check for out of memory errors*/
1007 generateFixedLitLenTree(tree_ll
);
1008 generateFixedDistanceTree(tree_d
);
1011 /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
1012 static unsigned getTreeInflateDynamic(HuffmanTree
* tree_ll
, HuffmanTree
* tree_d
,
1013 const unsigned char* in
, size_t* bp
, size_t inlength
)
1015 /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
1017 unsigned n
, HLIT
, HDIST
, HCLEN
, i
;
1018 size_t inbitlength
= inlength
* 8;
1020 /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
1021 unsigned* bitlen_ll
= 0; /*lit,len code lengths*/
1022 unsigned* bitlen_d
= 0; /*dist code lengths*/
1023 /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
1024 unsigned* bitlen_cl
= 0;
1025 HuffmanTree tree_cl
; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
1027 if((*bp
) >> 3 >= inlength
- 2) return 49; /*error: the bit pointer is or will go past the memory*/
1029 /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
1030 HLIT
= readBitsFromStream(bp
, in
, 5) + 257;
1031 /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
1032 HDIST
= readBitsFromStream(bp
, in
, 5) + 1;
1033 /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
1034 HCLEN
= readBitsFromStream(bp
, in
, 4) + 4;
1036 HuffmanTree_init(&tree_cl
);
1040 /*read the code length codes out of 3 * (amount of code length codes) bits*/
1042 bitlen_cl
= (unsigned*)mymalloc(NUM_CODE_LENGTH_CODES
* sizeof(unsigned));
1043 if(!bitlen_cl
) ERROR_BREAK(83 /*alloc fail*/);
1045 for(i
= 0; i
< NUM_CODE_LENGTH_CODES
; i
++)
1047 if(i
< HCLEN
) bitlen_cl
[CLCL_ORDER
[i
]] = readBitsFromStream(bp
, in
, 3);
1048 else bitlen_cl
[CLCL_ORDER
[i
]] = 0; /*if not, it must stay 0*/
1051 error
= HuffmanTree_makeFromLengths(&tree_cl
, bitlen_cl
, NUM_CODE_LENGTH_CODES
, 7);
1054 /*now we can use this tree to read the lengths for the tree that this function will return*/
1055 bitlen_ll
= (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS
* sizeof(unsigned));
1056 bitlen_d
= (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS
* sizeof(unsigned));
1057 if(!bitlen_ll
|| !bitlen_d
) ERROR_BREAK(83 /*alloc fail*/);
1058 for(i
= 0; i
< NUM_DEFLATE_CODE_SYMBOLS
; i
++) bitlen_ll
[i
] = 0;
1059 for(i
= 0; i
< NUM_DISTANCE_SYMBOLS
; i
++) bitlen_d
[i
] = 0;
1061 /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1063 while(i
< HLIT
+ HDIST
)
1065 unsigned code
= huffmanDecodeSymbol(in
, bp
, &tree_cl
, inbitlength
);
1066 if(code
<= 15) /*a length code*/
1068 if(i
< HLIT
) bitlen_ll
[i
] = code
;
1069 else bitlen_d
[i
- HLIT
] = code
;
1072 else if(code
== 16) /*repeat previous*/
1074 unsigned replength
= 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1075 unsigned value
; /*set value to the previous code*/
1077 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1078 if (i
== 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1080 replength
+= readBitsFromStream(bp
, in
, 2);
1082 if(i
< HLIT
+ 1) value
= bitlen_ll
[i
- 1];
1083 else value
= bitlen_d
[i
- HLIT
- 1];
1084 /*repeat this value in the next lengths*/
1085 for(n
= 0; n
< replength
; n
++)
1087 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1088 if(i
< HLIT
) bitlen_ll
[i
] = value
;
1089 else bitlen_d
[i
- HLIT
] = value
;
1093 else if(code
== 17) /*repeat "0" 3-10 times*/
1095 unsigned replength
= 3; /*read in the bits that indicate repeat length*/
1096 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1098 replength
+= readBitsFromStream(bp
, in
, 3);
1100 /*repeat this value in the next lengths*/
1101 for(n
= 0; n
< replength
; n
++)
1103 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1105 if(i
< HLIT
) bitlen_ll
[i
] = 0;
1106 else bitlen_d
[i
- HLIT
] = 0;
1110 else if(code
== 18) /*repeat "0" 11-138 times*/
1112 unsigned replength
= 11; /*read in the bits that indicate repeat length*/
1113 if(*bp
>= inbitlength
) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1115 replength
+= readBitsFromStream(bp
, in
, 7);
1117 /*repeat this value in the next lengths*/
1118 for(n
= 0; n
< replength
; n
++)
1120 if(i
>= HLIT
+ HDIST
) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1122 if(i
< HLIT
) bitlen_ll
[i
] = 0;
1123 else bitlen_d
[i
- HLIT
] = 0;
1127 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1129 if(code
== (unsigned)(-1))
1131 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1132 (10=no endcode, 11=wrong jump outside of tree)*/
1133 error
= (*bp
) > inbitlength
? 10 : 11;
1135 else error
= 16; /*unexisting code, this can never happen*/
1141 if(bitlen_ll
[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1143 /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1144 error
= HuffmanTree_makeFromLengths(tree_ll
, bitlen_ll
, NUM_DEFLATE_CODE_SYMBOLS
, 15);
1146 error
= HuffmanTree_makeFromLengths(tree_d
, bitlen_d
, NUM_DISTANCE_SYMBOLS
, 15);
1148 break; /*end of error-while*/
1154 HuffmanTree_cleanup(&tree_cl
);
1159 /*inflate a block with dynamic of fixed Huffman tree*/
1160 static unsigned inflateHuffmanBlock(ucvector
* out
, const unsigned char* in
, size_t* bp
,
1161 size_t* pos
, size_t inlength
, unsigned btype
)
1164 HuffmanTree tree_ll
; /*the huffman tree for literal and length codes*/
1165 HuffmanTree tree_d
; /*the huffman tree for distance codes*/
1166 size_t inbitlength
= inlength
* 8;
1168 HuffmanTree_init(&tree_ll
);
1169 HuffmanTree_init(&tree_d
);
1171 if(btype
== 1) getTreeInflateFixed(&tree_ll
, &tree_d
);
1172 else if(btype
== 2) error
= getTreeInflateDynamic(&tree_ll
, &tree_d
, in
, bp
, inlength
);
1174 while(!error
) /*decode all symbols until end reached, breaks at end code*/
1176 /*code_ll is literal, length or end code*/
1177 unsigned code_ll
= huffmanDecodeSymbol(in
, bp
, &tree_ll
, inbitlength
);
1178 if(code_ll
<= 255) /*literal symbol*/
1180 if((*pos
) >= out
->size
)
1182 /*reserve more room at once*/
1183 if(!ucvector_resize(out
, ((*pos
) + 1) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1185 out
->data
[(*pos
)] = (unsigned char)(code_ll
);
1188 else if(code_ll
>= FIRST_LENGTH_CODE_INDEX
&& code_ll
<= LAST_LENGTH_CODE_INDEX
) /*length code*/
1190 unsigned code_d
, distance
;
1191 unsigned numextrabits_l
, numextrabits_d
; /*extra bits for length and distance*/
1192 size_t start
, forward
, backward
, length
;
1194 /*part 1: get length base*/
1195 length
= LENGTHBASE
[code_ll
- FIRST_LENGTH_CODE_INDEX
];
1197 /*part 2: get extra bits and add the value of that to length*/
1198 numextrabits_l
= LENGTHEXTRA
[code_ll
- FIRST_LENGTH_CODE_INDEX
];
1199 if(*bp
>= inbitlength
) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1200 length
+= readBitsFromStream(bp
, in
, numextrabits_l
);
1202 /*part 3: get distance code*/
1203 code_d
= huffmanDecodeSymbol(in
, bp
, &tree_d
, inbitlength
);
1206 if(code_ll
== (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1208 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1209 (10=no endcode, 11=wrong jump outside of tree)*/
1210 error
= (*bp
) > inlength
* 8 ? 10 : 11;
1212 else error
= 18; /*error: invalid distance code (30-31 are never used)*/
1215 distance
= DISTANCEBASE
[code_d
];
1217 /*part 4: get extra bits from distance*/
1218 numextrabits_d
= DISTANCEEXTRA
[code_d
];
1219 if(*bp
>= inbitlength
) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1221 distance
+= readBitsFromStream(bp
, in
, numextrabits_d
);
1223 /*part 5: fill in all the out[n] values based on the length and dist*/
1225 if(distance
> start
) ERROR_BREAK(52); /*too long backward distance*/
1226 backward
= start
- distance
;
1227 if((*pos
) + length
>= out
->size
)
1229 /*reserve more room at once*/
1230 if(!ucvector_resize(out
, ((*pos
) + length
) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1233 for(forward
= 0; forward
< length
; forward
++)
1235 out
->data
[(*pos
)] = out
->data
[backward
];
1238 if(backward
>= start
) backward
= start
- distance
;
1241 else if(code_ll
== 256)
1243 break; /*end code, break the loop*/
1245 else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1247 /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1248 (10=no endcode, 11=wrong jump outside of tree)*/
1249 error
= (*bp
) > inlength
* 8 ? 10 : 11;
1254 HuffmanTree_cleanup(&tree_ll
);
1255 HuffmanTree_cleanup(&tree_d
);
1260 static unsigned inflateNoCompression(ucvector
* out
, const unsigned char* in
, size_t* bp
, size_t* pos
, size_t inlength
)
1262 /*go to first boundary of byte*/
1264 unsigned LEN
, NLEN
, n
, error
= 0;
1265 while(((*bp
) & 0x7) != 0) (*bp
)++;
1266 p
= (*bp
) / 8; /*byte position*/
1268 /*read LEN (2 bytes) and NLEN (2 bytes)*/
1269 if(p
>= inlength
- 4) return 52; /*error, bit pointer will jump past memory*/
1270 LEN
= in
[p
] + 256 * in
[p
+ 1]; p
+= 2;
1271 NLEN
= in
[p
] + 256 * in
[p
+ 1]; p
+= 2;
1273 /*check if 16-bit NLEN is really the one's complement of LEN*/
1274 if(LEN
+ NLEN
!= 65535) return 21; /*error: NLEN is not one's complement of LEN*/
1276 if((*pos
) + LEN
>= out
->size
)
1278 if(!ucvector_resize(out
, (*pos
) + LEN
)) return 83; /*alloc fail*/
1281 /*read the literal data: LEN bytes are now stored in the out buffer*/
1282 if(p
+ LEN
> inlength
) return 23; /*error: reading outside of in buffer*/
1283 for(n
= 0; n
< LEN
; n
++) out
->data
[(*pos
)++] = in
[p
++];
1290 static unsigned lodepng_inflatev(ucvector
* out
,
1291 const unsigned char* in
, size_t insize
,
1292 const LodePNGDecompressSettings
* settings
)
1294 /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1296 unsigned BFINAL
= 0;
1297 size_t pos
= 0; /*byte position in the out buffer*/
1306 if(bp
+ 2 >= insize
* 8) return 52; /*error, bit pointer will jump past memory*/
1307 BFINAL
= readBitFromStream(&bp
, in
);
1308 BTYPE
= 1 * readBitFromStream(&bp
, in
);
1309 BTYPE
+= 2 * readBitFromStream(&bp
, in
);
1311 if(BTYPE
== 3) return 20; /*error: invalid BTYPE*/
1312 else if(BTYPE
== 0) error
= inflateNoCompression(out
, in
, &bp
, &pos
, insize
); /*no compression*/
1313 else error
= inflateHuffmanBlock(out
, in
, &bp
, &pos
, insize
, BTYPE
); /*compression, BTYPE 01 or 10*/
1315 if(error
) return error
;
1318 /*Only now we know the true size of out, resize it to that*/
1319 if(!ucvector_resize(out
, pos
)) error
= 83; /*alloc fail*/
1324 unsigned lodepng_inflate(unsigned char** out
, size_t* outsize
,
1325 const unsigned char* in
, size_t insize
,
1326 const LodePNGDecompressSettings
* settings
)
1330 ucvector_init_buffer(&v
, *out
, *outsize
);
1331 error
= lodepng_inflatev(&v
, in
, insize
, settings
);
1337 static unsigned inflate(unsigned char** out
, size_t* outsize
,
1338 const unsigned char* in
, size_t insize
,
1339 const LodePNGDecompressSettings
* settings
)
1341 if(settings
->custom_inflate
)
1343 return settings
->custom_inflate(out
, outsize
, in
, insize
, settings
);
1347 return lodepng_inflate(out
, outsize
, in
, insize
, settings
);
1351 #endif /*LODEPNG_COMPILE_DECODER*/
1353 #ifdef LODEPNG_COMPILE_ENCODER
1355 /* ////////////////////////////////////////////////////////////////////////// */
1356 /* / Deflator (Compressor) / */
1357 /* ////////////////////////////////////////////////////////////////////////// */
1359 static const size_t MAX_SUPPORTED_DEFLATE_LENGTH
= 258;
1361 /*bitlen is the size in bits of the code*/
1362 static void addHuffmanSymbol(size_t* bp
, ucvector
* compressed
, unsigned code
, unsigned bitlen
)
1364 addBitsToStreamReversed(bp
, compressed
, code
, bitlen
);
1367 /*search the index in the array, that has the largest value smaller than or equal to the given value,
1368 given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1369 static size_t searchCodeIndex(const unsigned* array
, size_t array_size
, size_t value
)
1371 /*linear search implementation*/
1372 /*for(size_t i = 1; i < array_size; i++) if(array[i] > value) return i - 1;
1373 return array_size - 1;*/
1375 /*binary search implementation (not that much faster) (precondition: array_size > 0)*/
1377 size_t right
= array_size
- 1;
1378 while(left
<= right
)
1380 size_t mid
= (left
+ right
) / 2;
1381 if(array
[mid
] <= value
) left
= mid
+ 1; /*the value to find is more to the right*/
1382 else if(array
[mid
- 1] > value
) right
= mid
- 1; /*the value to find is more to the left*/
1383 else return mid
- 1;
1385 return array_size
- 1;
1388 static void addLengthDistance(uivector
* values
, size_t length
, size_t distance
)
1390 /*values in encoded vector are those used by deflate:
1391 0-255: literal bytes
1393 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1396 unsigned length_code
= (unsigned)searchCodeIndex(LENGTHBASE
, 29, length
);
1397 unsigned extra_length
= (unsigned)(length
- LENGTHBASE
[length_code
]);
1398 unsigned dist_code
= (unsigned)searchCodeIndex(DISTANCEBASE
, 30, distance
);
1399 unsigned extra_distance
= (unsigned)(distance
- DISTANCEBASE
[dist_code
]);
1401 uivector_push_back(values
, length_code
+ FIRST_LENGTH_CODE_INDEX
);
1402 uivector_push_back(values
, extra_length
);
1403 uivector_push_back(values
, dist_code
);
1404 uivector_push_back(values
, extra_distance
);
1407 static const unsigned HASH_NUM_VALUES
= 65536;
1408 static const unsigned HASH_NUM_CHARACTERS
= 3;
1409 static const unsigned HASH_SHIFT
= 2;
1411 The HASH_NUM_CHARACTERS value is used to make encoding faster by using longer
1412 sequences to generate a hash value from the stream bytes. Setting it to 3
1413 gives exactly the same compression as the brute force method, since deflate's
1414 run length encoding starts with lengths of 3. Setting it to higher values,
1415 like 6, can make the encoding faster (not always though!), but will cause the
1416 encoding to miss any length between 3 and this value, so that the compression
1417 may be worse (but this can vary too depending on the image, sometimes it is
1418 even a bit better instead).
1419 The HASH_NUM_VALUES is the amount of unique possible hash values that
1420 combinations of bytes can give, the higher it is the more memory is needed, but
1421 if it's too low the advantage of hashing is gone.
1427 int* head
; /*hash value to head circular pos*/
1428 int* val
; /*circular pos to hash value*/
1429 /*circular pos to prev circular pos*/
1434 static unsigned hash_init(Hash
* hash
, unsigned windowsize
)
1437 hash
->head
= (int*)mymalloc(sizeof(int) * HASH_NUM_VALUES
);
1438 hash
->val
= (int*)mymalloc(sizeof(int) * windowsize
);
1439 hash
->chain
= (UINT16
*)mymalloc(sizeof(UINT16
) * windowsize
);
1440 hash
->zeros
= (UINT16
*)mymalloc(sizeof(UINT16
) * windowsize
);
1442 if(!hash
->head
|| !hash
->val
|| !hash
->chain
|| !hash
->zeros
) return 83; /*alloc fail*/
1444 /*initialize hash table*/
1445 for(i
= 0; i
< HASH_NUM_VALUES
; i
++) hash
->head
[i
] = -1;
1446 for(i
= 0; i
< windowsize
; i
++) hash
->val
[i
] = -1;
1447 for(i
= 0; i
< windowsize
; i
++) hash
->chain
[i
] = i
; /*same value as index indicates uninitialized*/
1452 static void hash_cleanup(Hash
* hash
)
1456 myfree(hash
->chain
);
1457 myfree(hash
->zeros
);
1460 static unsigned getHash(const unsigned char* data
, size_t size
, size_t pos
)
1462 unsigned result
= 0;
1464 if(pos
>= size
) return 0;
1465 amount
= HASH_NUM_CHARACTERS
;
1466 if(pos
+ amount
>= size
) amount
= size
- pos
;
1467 for(i
= 0; i
< amount
; i
++) result
^= (data
[pos
+ i
] << (i
* HASH_SHIFT
));
1468 return result
% HASH_NUM_VALUES
;
1471 static unsigned countZeros(const unsigned char* data
, size_t size
, size_t pos
)
1473 const unsigned char* start
= data
+ pos
;
1474 const unsigned char* end
= start
+ MAX_SUPPORTED_DEFLATE_LENGTH
;
1475 if(end
> data
+ size
) end
= data
+ size
;
1477 while (data
!= end
&& *data
== 0) data
++;
1478 /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1479 return (unsigned)(data
- start
);
1482 static void updateHashChain(Hash
* hash
, size_t pos
, int hashval
, unsigned windowsize
)
1484 unsigned wpos
= pos
% windowsize
;
1485 hash
->val
[wpos
] = hashval
;
1486 if(hash
->head
[hashval
] != -1) hash
->chain
[wpos
] = hash
->head
[hashval
];
1487 hash
->head
[hashval
] = wpos
;
1491 LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1492 is in the form of unsigned integers with codes representing for example literal bytes, or
1493 length/distance pairs.
1494 It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1495 sliding window (of windowsize) is used, and all past bytes in that window can be used as
1496 the "dictionary". A brute force search through all possible distances would be slow, and
1497 this hash technique is one out of several ways to speed this up.
1499 static unsigned encodeLZ77(uivector
* out
, Hash
* hash
,
1500 const unsigned char* in
, size_t inpos
, size_t insize
, unsigned windowsize
,
1501 unsigned minmatch
, unsigned nicematch
, unsigned lazymatching
)
1503 UINT16 numzeros
= 0;
1504 int usezeros
= windowsize
>= 8192; /*for small window size, the 'max chain length' optimization does a better job*/
1505 unsigned pos
, i
, error
= 0;
1506 /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1507 unsigned maxchainlength
= windowsize
>= 8192 ? windowsize
: windowsize
/ 8;
1508 unsigned maxlazymatch
= windowsize
>= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH
: 64;
1512 unsigned offset
; /*the offset represents the distance in LZ77 terminology*/
1515 unsigned lazylength
= 0, lazyoffset
= 0;
1517 unsigned current_offset
, current_length
;
1518 const unsigned char *lastptr
, *foreptr
, *backptr
;
1519 UINT16 hashpos
, prevpos
;
1521 for(pos
= inpos
; pos
< insize
; pos
++)
1523 size_t wpos
= pos
% windowsize
; /*position for in 'circular' hash buffers*/
1525 hashval
= getHash(in
, insize
, pos
);
1526 updateHashChain(hash
, pos
, hashval
, windowsize
);
1528 if(usezeros
&& hashval
== 0)
1530 numzeros
= countZeros(in
, insize
, pos
);
1531 hash
->zeros
[wpos
] = numzeros
;
1534 /*the length and offset found for the current position*/
1538 prevpos
= hash
->head
[hashval
];
1539 hashpos
= hash
->chain
[prevpos
];
1541 lastptr
= &in
[insize
< pos
+ MAX_SUPPORTED_DEFLATE_LENGTH
? insize
: pos
+ MAX_SUPPORTED_DEFLATE_LENGTH
];
1543 /*search for the longest string*/
1544 if(hash
->val
[wpos
] == (int)hashval
)
1546 unsigned chainlength
= 0;
1549 /*stop when went completely around the circular buffer*/
1550 if(prevpos
< wpos
&& hashpos
> prevpos
&& hashpos
<= wpos
) break;
1551 if(prevpos
> wpos
&& (hashpos
<= wpos
|| hashpos
> prevpos
)) break;
1552 if(chainlength
++ >= maxchainlength
) break;
1554 current_offset
= hashpos
<= wpos
? wpos
- hashpos
: wpos
- hashpos
+ windowsize
;
1555 if(current_offset
> 0)
1557 /*test the next characters*/
1559 backptr
= &in
[pos
- current_offset
];
1561 /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1562 if(usezeros
&& hashval
== 0 && hash
->val
[hashpos
] == 0 /*hashval[hashpos] may be out of date*/)
1564 UINT16 skip
= hash
->zeros
[hashpos
];
1565 if(skip
> numzeros
) skip
= numzeros
;
1570 /* multiple checks at once per array bounds check */
1571 while(foreptr
!= lastptr
&& *backptr
== *foreptr
) /*maximum supported length by deflate is max length*/
1576 current_length
= (unsigned)(foreptr
- &in
[pos
]);
1578 if(current_length
> length
)
1580 length
= current_length
; /*the longest length*/
1581 offset
= current_offset
; /*the offset that is related to this longest length*/
1582 /*jump out once a length of max length is found (speed gain)*/
1583 if(current_length
>= nicematch
|| current_length
== MAX_SUPPORTED_DEFLATE_LENGTH
) break;
1587 if(hashpos
== hash
->chain
[hashpos
]) break;
1590 hashpos
= hash
->chain
[hashpos
];
1596 if(!lazy
&& length
>= 3 && length
<= maxlazymatch
&& length
< MAX_SUPPORTED_DEFLATE_LENGTH
)
1599 lazylength
= length
;
1600 lazyoffset
= offset
;
1601 continue; /*try the next byte*/
1606 if(pos
== 0) ERROR_BREAK(81);
1607 if(length
> lazylength
+ 1)
1609 /*push the previous character as literal*/
1610 if(!uivector_push_back(out
, in
[pos
- 1])) ERROR_BREAK(83 /*alloc fail*/);
1614 length
= lazylength
;
1615 offset
= lazyoffset
;
1616 hash
->head
[hashval
] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1621 if(length
>= 3 && offset
> windowsize
) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1623 /**encode it as length/distance pair or literal value**/
1624 if(length
< 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1626 if(!uivector_push_back(out
, in
[pos
])) ERROR_BREAK(83 /*alloc fail*/);
1628 else if(length
< minmatch
|| (length
== 3 && offset
> 4096))
1630 /*compensate for the fact that longer offsets have more extra bits, a
1631 length of only 3 may be not worth it then*/
1632 if(!uivector_push_back(out
, in
[pos
])) ERROR_BREAK(83 /*alloc fail*/);
1636 addLengthDistance(out
, length
, offset
);
1637 for(i
= 1; i
< length
; i
++)
1640 hashval
= getHash(in
, insize
, pos
);
1641 updateHashChain(hash
, pos
, hashval
, windowsize
);
1642 if(usezeros
&& hashval
== 0)
1644 hash
->zeros
[pos
% windowsize
] = countZeros(in
, insize
, pos
);
1649 } /*end of the loop through each character of input*/
1650 } /*end of "if(!error)"*/
1655 /* /////////////////////////////////////////////////////////////////////////// */
1657 static unsigned deflateNoCompression(ucvector
* out
, const unsigned char* data
, size_t datasize
)
1659 /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1660 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1662 size_t i
, j
, numdeflateblocks
= (datasize
+ 65534) / 65535;
1663 unsigned datapos
= 0;
1664 for(i
= 0; i
< numdeflateblocks
; i
++)
1666 unsigned BFINAL
, BTYPE
, LEN
, NLEN
;
1667 unsigned char firstbyte
;
1669 BFINAL
= (i
== numdeflateblocks
- 1);
1672 firstbyte
= (unsigned char)(BFINAL
+ ((BTYPE
& 1) << 1) + ((BTYPE
& 2) << 1));
1673 ucvector_push_back(out
, firstbyte
);
1676 if(datasize
- datapos
< 65535) LEN
= (unsigned)datasize
- datapos
;
1679 ucvector_push_back(out
, (unsigned char)(LEN
% 256));
1680 ucvector_push_back(out
, (unsigned char)(LEN
/ 256));
1681 ucvector_push_back(out
, (unsigned char)(NLEN
% 256));
1682 ucvector_push_back(out
, (unsigned char)(NLEN
/ 256));
1684 /*Decompressed data*/
1685 for(j
= 0; j
< 65535 && datapos
< datasize
; j
++)
1687 ucvector_push_back(out
, data
[datapos
++]);
1695 write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1696 tree_ll: the tree for lit and len codes.
1697 tree_d: the tree for distance codes.
1699 static void writeLZ77data(size_t* bp
, ucvector
* out
, const uivector
* lz77_encoded
,
1700 const HuffmanTree
* tree_ll
, const HuffmanTree
* tree_d
)
1703 for(i
= 0; i
< lz77_encoded
->size
; i
++)
1705 unsigned val
= lz77_encoded
->data
[i
];
1706 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(tree_ll
, val
), HuffmanTree_getLength(tree_ll
, val
));
1707 if(val
> 256) /*for a length code, 3 more things have to be added*/
1709 unsigned length_index
= val
- FIRST_LENGTH_CODE_INDEX
;
1710 unsigned n_length_extra_bits
= LENGTHEXTRA
[length_index
];
1711 unsigned length_extra_bits
= lz77_encoded
->data
[++i
];
1713 unsigned distance_code
= lz77_encoded
->data
[++i
];
1715 unsigned distance_index
= distance_code
;
1716 unsigned n_distance_extra_bits
= DISTANCEEXTRA
[distance_index
];
1717 unsigned distance_extra_bits
= lz77_encoded
->data
[++i
];
1719 addBitsToStream(bp
, out
, length_extra_bits
, n_length_extra_bits
);
1720 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(tree_d
, distance_code
),
1721 HuffmanTree_getLength(tree_d
, distance_code
));
1722 addBitsToStream(bp
, out
, distance_extra_bits
, n_distance_extra_bits
);
1727 /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1728 static unsigned deflateDynamic(ucvector
* out
, size_t* bp
, Hash
* hash
,
1729 const unsigned char* data
, size_t datapos
, size_t dataend
,
1730 const LodePNGCompressSettings
* settings
, int final
)
1735 A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1736 literal bytes and length/distance pairs. This is then huffman compressed with
1737 two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1738 another huffman tree is used for the dist values ("d"). These two trees are
1739 stored using their code lengths, and to compress even more these code lengths
1740 are also run-length encoded and huffman compressed. This gives a huffman tree
1741 of code lengths "cl". The code lenghts used to describe this third tree are
1742 the code length code lengths ("clcl").
1745 /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1746 uivector lz77_encoded
;
1747 HuffmanTree tree_ll
; /*tree for lit,len values*/
1748 HuffmanTree tree_d
; /*tree for distance codes*/
1749 HuffmanTree tree_cl
; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1750 uivector frequencies_ll
; /*frequency of lit,len codes*/
1751 uivector frequencies_d
; /*frequency of dist codes*/
1752 uivector frequencies_cl
; /*frequency of code length codes*/
1753 uivector bitlen_lld
; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1754 uivector bitlen_lld_e
; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1755 /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1756 (these are written as is in the file, it would be crazy to compress these using yet another huffman
1757 tree that needs to be represented by yet another set of code lengths)*/
1759 size_t datasize
= dataend
- datapos
;
1762 Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1763 bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1764 bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1765 bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1768 unsigned BFINAL
= final
;
1769 size_t numcodes_ll
, numcodes_d
, i
;
1770 unsigned HLIT
, HDIST
, HCLEN
;
1772 uivector_init(&lz77_encoded
);
1773 HuffmanTree_init(&tree_ll
);
1774 HuffmanTree_init(&tree_d
);
1775 HuffmanTree_init(&tree_cl
);
1776 uivector_init(&frequencies_ll
);
1777 uivector_init(&frequencies_d
);
1778 uivector_init(&frequencies_cl
);
1779 uivector_init(&bitlen_lld
);
1780 uivector_init(&bitlen_lld_e
);
1781 uivector_init(&bitlen_cl
);
1783 /*This while loop never loops due to a break at the end, it is here to
1784 allow breaking out of it to the cleanup phase on error conditions.*/
1787 if(settings
->use_lz77
)
1789 error
= encodeLZ77(&lz77_encoded
, hash
, data
, datapos
, dataend
, settings
->windowsize
,
1790 settings
->minmatch
, settings
->nicematch
, settings
->lazymatching
);
1795 if(!uivector_resize(&lz77_encoded
, datasize
)) ERROR_BREAK(83 /*alloc fail*/);
1796 for(i
= datapos
; i
< dataend
; i
++) lz77_encoded
.data
[i
] = data
[i
]; /*no LZ77, but still will be Huffman compressed*/
1799 if(!uivector_resizev(&frequencies_ll
, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
1800 if(!uivector_resizev(&frequencies_d
, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
1802 /*Count the frequencies of lit, len and dist codes*/
1803 for(i
= 0; i
< lz77_encoded
.size
; i
++)
1805 unsigned symbol
= lz77_encoded
.data
[i
];
1806 frequencies_ll
.data
[symbol
]++;
1809 unsigned dist
= lz77_encoded
.data
[i
+ 2];
1810 frequencies_d
.data
[dist
]++;
1814 frequencies_ll
.data
[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1816 /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1817 error
= HuffmanTree_makeFromFrequencies(&tree_ll
, frequencies_ll
.data
, 257, frequencies_ll
.size
, 15);
1819 /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1820 error
= HuffmanTree_makeFromFrequencies(&tree_d
, frequencies_d
.data
, 2, frequencies_d
.size
, 15);
1823 numcodes_ll
= tree_ll
.numcodes
; if(numcodes_ll
> 286) numcodes_ll
= 286;
1824 numcodes_d
= tree_d
.numcodes
; if(numcodes_d
> 30) numcodes_d
= 30;
1825 /*store the code lengths of both generated trees in bitlen_lld*/
1826 for(i
= 0; i
< numcodes_ll
; i
++) uivector_push_back(&bitlen_lld
, HuffmanTree_getLength(&tree_ll
, (unsigned)i
));
1827 for(i
= 0; i
< numcodes_d
; i
++) uivector_push_back(&bitlen_lld
, HuffmanTree_getLength(&tree_d
, (unsigned)i
));
1829 /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1830 17 (3-10 zeroes), 18 (11-138 zeroes)*/
1831 for(i
= 0; i
< (unsigned)bitlen_lld
.size
; i
++)
1833 unsigned j
= 0; /*amount of repititions*/
1834 while(i
+ j
+ 1 < (unsigned)bitlen_lld
.size
&& bitlen_lld
.data
[i
+ j
+ 1] == bitlen_lld
.data
[i
]) j
++;
1836 if(bitlen_lld
.data
[i
] == 0 && j
>= 2) /*repeat code for zeroes*/
1838 j
++; /*include the first zero*/
1839 if(j
<= 10) /*repeat code 17 supports max 10 zeroes*/
1841 uivector_push_back(&bitlen_lld_e
, 17);
1842 uivector_push_back(&bitlen_lld_e
, j
- 3);
1844 else /*repeat code 18 supports max 138 zeroes*/
1846 if(j
> 138) j
= 138;
1847 uivector_push_back(&bitlen_lld_e
, 18);
1848 uivector_push_back(&bitlen_lld_e
, j
- 11);
1852 else if(j
>= 3) /*repeat code for value other than zero*/
1855 unsigned num
= j
/ 6, rest
= j
% 6;
1856 uivector_push_back(&bitlen_lld_e
, bitlen_lld
.data
[i
]);
1857 for(k
= 0; k
< num
; k
++)
1859 uivector_push_back(&bitlen_lld_e
, 16);
1860 uivector_push_back(&bitlen_lld_e
, 6 - 3);
1864 uivector_push_back(&bitlen_lld_e
, 16);
1865 uivector_push_back(&bitlen_lld_e
, rest
- 3);
1870 else /*too short to benefit from repeat code*/
1872 uivector_push_back(&bitlen_lld_e
, bitlen_lld
.data
[i
]);
1876 /*generate tree_cl, the huffmantree of huffmantrees*/
1878 if(!uivector_resizev(&frequencies_cl
, NUM_CODE_LENGTH_CODES
, 0)) ERROR_BREAK(83 /*alloc fail*/);
1879 for(i
= 0; i
< bitlen_lld_e
.size
; i
++)
1881 frequencies_cl
.data
[bitlen_lld_e
.data
[i
]]++;
1882 /*after a repeat code come the bits that specify the number of repetitions,
1883 those don't need to be in the frequencies_cl calculation*/
1884 if(bitlen_lld_e
.data
[i
] >= 16) i
++;
1887 error
= HuffmanTree_makeFromFrequencies(&tree_cl
, frequencies_cl
.data
,
1888 frequencies_cl
.size
, frequencies_cl
.size
, 7);
1891 if(!uivector_resize(&bitlen_cl
, tree_cl
.numcodes
)) ERROR_BREAK(83 /*alloc fail*/);
1892 for(i
= 0; i
< tree_cl
.numcodes
; i
++)
1894 /*lenghts of code length tree is in the order as specified by deflate*/
1895 bitlen_cl
.data
[i
] = HuffmanTree_getLength(&tree_cl
, CLCL_ORDER
[i
]);
1897 while(bitlen_cl
.data
[bitlen_cl
.size
- 1] == 0 && bitlen_cl
.size
> 4)
1899 /*remove zeros at the end, but minimum size must be 4*/
1900 if(!uivector_resize(&bitlen_cl
, bitlen_cl
.size
- 1)) ERROR_BREAK(83 /*alloc fail*/);
1905 Write everything into the output
1907 After the BFINAL and BTYPE, the dynamic block consists out of the following:
1908 - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1909 - (HCLEN+4)*3 bits code lengths of code length alphabet
1910 - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
1911 alphabet, + possible repetition codes 16, 17, 18)
1912 - HDIST + 1 code lengths of distance alphabet (encoded using the code length
1913 alphabet, + possible repetition codes 16, 17, 18)
1918 /*Write block type*/
1919 addBitToStream(bp
, out
, BFINAL
);
1920 addBitToStream(bp
, out
, 0); /*first bit of BTYPE "dynamic"*/
1921 addBitToStream(bp
, out
, 1); /*second bit of BTYPE "dynamic"*/
1923 /*write the HLIT, HDIST and HCLEN values*/
1924 HLIT
= (unsigned)(numcodes_ll
- 257);
1925 HDIST
= (unsigned)(numcodes_d
- 1);
1926 HCLEN
= (unsigned)bitlen_cl
.size
- 4;
1927 /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
1928 while(!bitlen_cl
.data
[HCLEN
+ 4 - 1] && HCLEN
> 0) HCLEN
--;
1929 addBitsToStream(bp
, out
, HLIT
, 5);
1930 addBitsToStream(bp
, out
, HDIST
, 5);
1931 addBitsToStream(bp
, out
, HCLEN
, 4);
1933 /*write the code lenghts of the code length alphabet*/
1934 for(i
= 0; i
< HCLEN
+ 4; i
++) addBitsToStream(bp
, out
, bitlen_cl
.data
[i
], 3);
1936 /*write the lenghts of the lit/len AND the dist alphabet*/
1937 for(i
= 0; i
< bitlen_lld_e
.size
; i
++)
1939 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_cl
, bitlen_lld_e
.data
[i
]),
1940 HuffmanTree_getLength(&tree_cl
, bitlen_lld_e
.data
[i
]));
1941 /*extra bits of repeat codes*/
1942 if(bitlen_lld_e
.data
[i
] == 16) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 2);
1943 else if(bitlen_lld_e
.data
[i
] == 17) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 3);
1944 else if(bitlen_lld_e
.data
[i
] == 18) addBitsToStream(bp
, out
, bitlen_lld_e
.data
[++i
], 7);
1947 /*write the compressed data symbols*/
1948 writeLZ77data(bp
, out
, &lz77_encoded
, &tree_ll
, &tree_d
);
1949 /*error: the length of the end code 256 must be larger than 0*/
1950 if(HuffmanTree_getLength(&tree_ll
, 256) == 0) ERROR_BREAK(64);
1952 /*write the end code*/
1953 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, 256), HuffmanTree_getLength(&tree_ll
, 256));
1955 break; /*end of error-while*/
1959 uivector_cleanup(&lz77_encoded
);
1960 HuffmanTree_cleanup(&tree_ll
);
1961 HuffmanTree_cleanup(&tree_d
);
1962 HuffmanTree_cleanup(&tree_cl
);
1963 uivector_cleanup(&frequencies_ll
);
1964 uivector_cleanup(&frequencies_d
);
1965 uivector_cleanup(&frequencies_cl
);
1966 uivector_cleanup(&bitlen_lld_e
);
1967 uivector_cleanup(&bitlen_lld
);
1968 uivector_cleanup(&bitlen_cl
);
1973 static unsigned deflateFixed(ucvector
* out
, size_t* bp
, Hash
* hash
,
1974 const unsigned char* data
,
1975 size_t datapos
, size_t dataend
,
1976 const LodePNGCompressSettings
* settings
, int final
)
1978 HuffmanTree tree_ll
; /*tree for literal values and length codes*/
1979 HuffmanTree tree_d
; /*tree for distance codes*/
1981 unsigned BFINAL
= final
;
1985 HuffmanTree_init(&tree_ll
);
1986 HuffmanTree_init(&tree_d
);
1988 generateFixedLitLenTree(&tree_ll
);
1989 generateFixedDistanceTree(&tree_d
);
1991 addBitToStream(bp
, out
, BFINAL
);
1992 addBitToStream(bp
, out
, 1); /*first bit of BTYPE*/
1993 addBitToStream(bp
, out
, 0); /*second bit of BTYPE*/
1995 if(settings
->use_lz77
) /*LZ77 encoded*/
1997 uivector lz77_encoded
;
1998 uivector_init(&lz77_encoded
);
1999 error
= encodeLZ77(&lz77_encoded
, hash
, data
, datapos
, dataend
, settings
->windowsize
,
2000 settings
->minmatch
, settings
->nicematch
, settings
->lazymatching
);
2001 if(!error
) writeLZ77data(bp
, out
, &lz77_encoded
, &tree_ll
, &tree_d
);
2002 uivector_cleanup(&lz77_encoded
);
2004 else /*no LZ77, but still will be Huffman compressed*/
2006 for(i
= datapos
; i
< dataend
; i
++)
2008 addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, data
[i
]), HuffmanTree_getLength(&tree_ll
, data
[i
]));
2012 if(!error
) addHuffmanSymbol(bp
, out
, HuffmanTree_getCode(&tree_ll
, 256), HuffmanTree_getLength(&tree_ll
, 256));
2015 HuffmanTree_cleanup(&tree_ll
);
2016 HuffmanTree_cleanup(&tree_d
);
2021 static unsigned lodepng_deflatev(ucvector
* out
, const unsigned char* in
, size_t insize
,
2022 const LodePNGCompressSettings
* settings
)
2025 size_t i
, blocksize
, numdeflateblocks
;
2026 size_t bp
= 0; /*the bit pointer*/
2029 if(settings
->btype
> 2) return 61;
2030 else if(settings
->btype
== 0) return deflateNoCompression(out
, in
, insize
);
2031 else if(settings
->btype
== 1) blocksize
= insize
;
2032 else /*if(settings->btype == 2)*/
2034 blocksize
= insize
/ 8 + 8;
2035 if(blocksize
< 65535) blocksize
= 65535;
2038 numdeflateblocks
= (insize
+ blocksize
- 1) / blocksize
;
2039 if(numdeflateblocks
== 0) numdeflateblocks
= 1;
2041 error
= hash_init(&hash
, settings
->windowsize
);
2042 if(error
) return error
;
2044 for(i
= 0; i
< numdeflateblocks
&& !error
; i
++)
2046 int final
= i
== numdeflateblocks
- 1;
2047 size_t start
= i
* blocksize
;
2048 size_t end
= start
+ blocksize
;
2049 if(end
> insize
) end
= insize
;
2051 if(settings
->btype
== 1) error
= deflateFixed(out
, &bp
, &hash
, in
, start
, end
, settings
, final
);
2052 else if(settings
->btype
== 2) error
= deflateDynamic(out
, &bp
, &hash
, in
, start
, end
, settings
, final
);
2055 hash_cleanup(&hash
);
2060 unsigned lodepng_deflate(unsigned char** out
, size_t* outsize
,
2061 const unsigned char* in
, size_t insize
,
2062 const LodePNGCompressSettings
* settings
)
2066 ucvector_init_buffer(&v
, *out
, *outsize
);
2067 error
= lodepng_deflatev(&v
, in
, insize
, settings
);
2073 static unsigned deflate(unsigned char** out
, size_t* outsize
,
2074 const unsigned char* in
, size_t insize
,
2075 const LodePNGCompressSettings
* settings
)
2077 if(settings
->custom_deflate
)
2079 return settings
->custom_deflate(out
, outsize
, in
, insize
, settings
);
2083 return lodepng_deflate(out
, outsize
, in
, insize
, settings
);
2087 #endif /*LODEPNG_COMPILE_DECODER*/
2089 /* ////////////////////////////////////////////////////////////////////////// */
2091 /* ////////////////////////////////////////////////////////////////////////// */
2093 static unsigned update_adler32(unsigned adler
, const unsigned char* data
, unsigned len
)
2095 unsigned s1
= adler
& 0xffff;
2096 unsigned s2
= (adler
>> 16) & 0xffff;
2100 /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2101 unsigned amount
= len
> 5550 ? 5550 : len
;
2113 return (s2
<< 16) | s1
;
2116 /*Return the adler32 of the bytes data[0..len-1]*/
2117 static unsigned adler32(const unsigned char* data
, unsigned len
)
2119 return update_adler32(1L, data
, len
);
2122 /* ////////////////////////////////////////////////////////////////////////// */
2124 /* ////////////////////////////////////////////////////////////////////////// */
2126 #ifdef LODEPNG_COMPILE_DECODER
2128 unsigned lodepng_zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2129 size_t insize
, const LodePNGDecompressSettings
* settings
)
2132 unsigned CM
, CINFO
, FDICT
;
2134 if(insize
< 2) return 53; /*error, size of zlib data too small*/
2135 /*read information from zlib header*/
2136 if((in
[0] * 256 + in
[1]) % 31 != 0)
2138 /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2143 CINFO
= (in
[0] >> 4) & 15;
2144 /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2145 FDICT
= (in
[1] >> 5) & 1;
2146 /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2148 if(CM
!= 8 || CINFO
> 7)
2150 /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2155 /*error: the specification of PNG says about the zlib stream:
2156 "The additional flags shall not specify a preset dictionary."*/
2160 error
= inflate(out
, outsize
, in
+ 2, insize
- 2, settings
);
2161 if(error
) return error
;
2163 if(!settings
->ignore_adler32
)
2165 unsigned ADLER32
= lodepng_read32bitInt(&in
[insize
- 4]);
2166 unsigned checksum
= adler32(*out
, (unsigned)(*outsize
));
2167 if(checksum
!= ADLER32
) return 58; /*error, adler checksum not correct, data must be corrupted*/
2170 return 0; /*no error*/
2173 static unsigned zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2174 size_t insize
, const LodePNGDecompressSettings
* settings
)
2176 if(settings
->custom_zlib
)
2177 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2179 return lodepng_zlib_decompress(out
, outsize
, in
, insize
, settings
);
2182 #endif /*LODEPNG_COMPILE_DECODER*/
2184 #ifdef LODEPNG_COMPILE_ENCODER
2186 unsigned lodepng_zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2187 size_t insize
, const LodePNGCompressSettings
* settings
)
2189 /*initially, *out must be NULL and outsize 0, if you just give some random *out
2190 that's pointing to a non allocated buffer, this'll crash*/
2194 unsigned char* deflatedata
= 0;
2195 size_t deflatesize
= 0;
2198 /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2199 unsigned CMF
= 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2200 unsigned FLEVEL
= 0;
2202 unsigned CMFFLG
= 256 * CMF
+ FDICT
* 32 + FLEVEL
* 64;
2203 unsigned FCHECK
= 31 - CMFFLG
% 31;
2206 /*ucvector-controlled version of the output buffer, for dynamic array*/
2207 ucvector_init_buffer(&outv
, *out
, *outsize
);
2209 ucvector_push_back(&outv
, (unsigned char)(CMFFLG
/ 256));
2210 ucvector_push_back(&outv
, (unsigned char)(CMFFLG
% 256));
2212 error
= deflate(&deflatedata
, &deflatesize
, in
, insize
, settings
);
2216 ADLER32
= adler32(in
, (unsigned)insize
);
2217 for(i
= 0; i
< deflatesize
; i
++) ucvector_push_back(&outv
, deflatedata
[i
]);
2218 myfree(deflatedata
);
2219 lodepng_add32bitInt(&outv
, ADLER32
);
2223 *outsize
= outv
.size
;
2228 /* compress using the default or custom zlib function */
2229 static unsigned zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2230 size_t insize
, const LodePNGCompressSettings
* settings
)
2232 if(settings
->custom_zlib
)
2234 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2238 return lodepng_zlib_compress(out
, outsize
, in
, insize
, settings
);
2242 #endif /*LODEPNG_COMPILE_ENCODER*/
2244 #else /*no LODEPNG_COMPILE_ZLIB*/
2246 #ifdef LODEPNG_COMPILE_DECODER
2247 static unsigned zlib_decompress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2248 size_t insize
, const LodePNGDecompressSettings
* settings
)
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_DECODER*/
2254 #ifdef LODEPNG_COMPILE_ENCODER
2255 static unsigned zlib_compress(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
2256 size_t insize
, const LodePNGCompressSettings
* settings
)
2258 if (!settings
->custom_zlib
) return 87; /*no custom zlib function provided */
2259 return settings
->custom_zlib(out
, outsize
, in
, insize
, settings
);
2261 #endif /*LODEPNG_COMPILE_ENCODER*/
2263 #endif /*LODEPNG_COMPILE_ZLIB*/
2265 /* ////////////////////////////////////////////////////////////////////////// */
2267 #ifdef LODEPNG_COMPILE_ENCODER
2269 /*this is a good tradeoff between speed and compression ratio*/
2270 #define DEFAULT_WINDOWSIZE 2048
2272 void lodepng_compress_settings_init(LodePNGCompressSettings
* settings
)
2274 /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2275 settings
->btype
= 2;
2276 settings
->use_lz77
= 1;
2277 settings
->windowsize
= DEFAULT_WINDOWSIZE
;
2278 settings
->minmatch
= 3;
2279 settings
->nicematch
= 128;
2280 settings
->lazymatching
= 1;
2282 settings
->custom_zlib
= 0;
2283 settings
->custom_deflate
= 0;
2284 settings
->custom_context
= 0;
2287 const LodePNGCompressSettings lodepng_default_compress_settings
= {2, 1, DEFAULT_WINDOWSIZE
, 3, 128, 1, 0, 0, 0};
2290 #endif /*LODEPNG_COMPILE_ENCODER*/
2292 #ifdef LODEPNG_COMPILE_DECODER
2294 void lodepng_decompress_settings_init(LodePNGDecompressSettings
* settings
)
2296 settings
->ignore_adler32
= 0;
2298 settings
->custom_zlib
= 0;
2299 settings
->custom_inflate
= 0;
2300 settings
->custom_context
= 0;
2303 const LodePNGDecompressSettings lodepng_default_decompress_settings
= {0, 0, 0, 0};
2305 #endif /*LODEPNG_COMPILE_DECODER*/
2307 /* ////////////////////////////////////////////////////////////////////////// */
2308 /* ////////////////////////////////////////////////////////////////////////// */
2309 /* // End of Zlib related code. Begin of PNG related code. // */
2310 /* ////////////////////////////////////////////////////////////////////////// */
2311 /* ////////////////////////////////////////////////////////////////////////// */
2313 #ifdef LODEPNG_COMPILE_PNG
2315 /* ////////////////////////////////////////////////////////////////////////// */
2317 /* ////////////////////////////////////////////////////////////////////////// */
2319 static unsigned Crc32_crc_table_computed
= 0;
2320 static unsigned Crc32_crc_table
[256];
2322 /*Make the table for a fast CRC.*/
2323 static void Crc32_make_crc_table(void)
2326 for(n
= 0; n
< 256; n
++)
2329 for(k
= 0; k
< 8; k
++)
2331 if(c
& 1) c
= 0xedb88320L
^ (c
>> 1);
2334 Crc32_crc_table
[n
] = c
;
2336 Crc32_crc_table_computed
= 1;
2339 /*Update a running CRC with the bytes buf[0..len-1]--the CRC should be
2340 initialized to all 1's, and the transmitted value is the 1's complement of the
2341 final running CRC (see the crc() routine below).*/
2342 static unsigned Crc32_update_crc(const unsigned char* buf
, unsigned crc
, size_t len
)
2347 if(!Crc32_crc_table_computed
) Crc32_make_crc_table();
2348 for(n
= 0; n
< len
; n
++)
2350 c
= Crc32_crc_table
[(c
^ buf
[n
]) & 0xff] ^ (c
>> 8);
2355 /*Return the CRC of the bytes buf[0..len-1].*/
2356 unsigned lodepng_crc32(const unsigned char* buf
, size_t len
)
2358 return Crc32_update_crc(buf
, 0xffffffffL
, len
) ^ 0xffffffffL
;
2361 /* ////////////////////////////////////////////////////////////////////////// */
2362 /* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2363 /* ////////////////////////////////////////////////////////////////////////// */
2365 static unsigned char readBitFromReversedStream(size_t* bitpointer
, const unsigned char* bitstream
)
2367 unsigned char result
= (unsigned char)((bitstream
[(*bitpointer
) >> 3] >> (7 - ((*bitpointer
) & 0x7))) & 1);
2372 static unsigned readBitsFromReversedStream(size_t* bitpointer
, const unsigned char* bitstream
, size_t nbits
)
2374 unsigned result
= 0;
2376 for(i
= nbits
- 1; i
< nbits
; i
--)
2378 result
+= (unsigned)readBitFromReversedStream(bitpointer
, bitstream
) << i
;
2383 #ifdef LODEPNG_COMPILE_DECODER
2384 static void setBitOfReversedStream0(size_t* bitpointer
, unsigned char* bitstream
, unsigned char bit
)
2386 /*the current bit in bitstream must be 0 for this to work*/
2389 /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2390 bitstream
[(*bitpointer
) >> 3] |= (bit
<< (7 - ((*bitpointer
) & 0x7)));
2394 #endif /*LODEPNG_COMPILE_DECODER*/
2396 static void setBitOfReversedStream(size_t* bitpointer
, unsigned char* bitstream
, unsigned char bit
)
2398 /*the current bit in bitstream may be 0 or 1 for this to work*/
2399 if(bit
== 0) bitstream
[(*bitpointer
) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer
) & 0x7))));
2400 else bitstream
[(*bitpointer
) >> 3] |= (1 << (7 - ((*bitpointer
) & 0x7)));
2404 /* ////////////////////////////////////////////////////////////////////////// */
2405 /* / PNG chunks / */
2406 /* ////////////////////////////////////////////////////////////////////////// */
2408 unsigned lodepng_chunk_length(const unsigned char* chunk
)
2410 return lodepng_read32bitInt(&chunk
[0]);
2413 void lodepng_chunk_type(char type
[5], const unsigned char* chunk
)
2416 for(i
= 0; i
< 4; i
++) type
[i
] = chunk
[4 + i
];
2417 type
[4] = 0; /*null termination char*/
2420 unsigned char lodepng_chunk_type_equals(const unsigned char* chunk
, const char* type
)
2422 if(MyStrlen(type
) != 4) return 0;
2423 return (chunk
[4] == type
[0] && chunk
[5] == type
[1] && chunk
[6] == type
[2] && chunk
[7] == type
[3]);
2426 unsigned char lodepng_chunk_ancillary(const unsigned char* chunk
)
2428 return((chunk
[4] & 32) != 0);
2431 unsigned char lodepng_chunk_private(const unsigned char* chunk
)
2433 return((chunk
[6] & 32) != 0);
2436 unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk
)
2438 return((chunk
[7] & 32) != 0);
2441 unsigned char* lodepng_chunk_data(unsigned char* chunk
)
2446 const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk
)
2451 unsigned lodepng_chunk_check_crc(const unsigned char* chunk
)
2453 unsigned length
= lodepng_chunk_length(chunk
);
2454 unsigned CRC
= lodepng_read32bitInt(&chunk
[length
+ 8]);
2455 /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2456 unsigned checksum
= lodepng_crc32(&chunk
[4], length
+ 4);
2457 if(CRC
!= checksum
) return 1;
2461 void lodepng_chunk_generate_crc(unsigned char* chunk
)
2463 unsigned length
= lodepng_chunk_length(chunk
);
2464 unsigned CRC
= lodepng_crc32(&chunk
[4], length
+ 4);
2465 lodepng_set32bitInt(chunk
+ 8 + length
, CRC
);
2468 unsigned char* lodepng_chunk_next(unsigned char* chunk
)
2470 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2471 return &chunk
[total_chunk_length
];
2474 const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk
)
2476 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2477 return &chunk
[total_chunk_length
];
2480 unsigned lodepng_chunk_append(unsigned char** out
, size_t* outlength
, const unsigned char* chunk
)
2483 unsigned total_chunk_length
= lodepng_chunk_length(chunk
) + 12;
2484 unsigned char *chunk_start
, *new_buffer
;
2485 size_t new_length
= (*outlength
) + total_chunk_length
;
2486 if(new_length
< total_chunk_length
|| new_length
< (*outlength
)) return 77; /*integer overflow happened*/
2488 new_buffer
= (unsigned char*)myrealloc(*out
, new_length
);
2489 if(!new_buffer
) return 83; /*alloc fail*/
2490 (*out
) = new_buffer
;
2491 (*outlength
) = new_length
;
2492 chunk_start
= &(*out
)[new_length
- total_chunk_length
];
2494 for(i
= 0; i
< total_chunk_length
; i
++) chunk_start
[i
] = chunk
[i
];
2499 unsigned lodepng_chunk_create(unsigned char** out
, size_t* outlength
, unsigned length
,
2500 const char* type
, const unsigned char* data
)
2503 unsigned char *chunk
, *new_buffer
;
2504 size_t new_length
= (*outlength
) + length
+ 12;
2505 if(new_length
< length
+ 12 || new_length
< (*outlength
)) return 77; /*integer overflow happened*/
2506 new_buffer
= (unsigned char*)myrealloc(*out
, new_length
);
2507 if(!new_buffer
) return 83; /*alloc fail*/
2508 (*out
) = new_buffer
;
2509 (*outlength
) = new_length
;
2510 chunk
= &(*out
)[(*outlength
) - length
- 12];
2513 lodepng_set32bitInt(chunk
, (unsigned)length
);
2515 /*2: chunk name (4 letters)*/
2522 for(i
= 0; i
< length
; i
++) chunk
[8 + i
] = data
[i
];
2524 /*4: CRC (of the chunkname characters and the data)*/
2525 lodepng_chunk_generate_crc(chunk
);
2530 /* ////////////////////////////////////////////////////////////////////////// */
2531 /* / Color types and such / */
2532 /* ////////////////////////////////////////////////////////////////////////// */
2534 /*return type is a LodePNG error code*/
2535 static unsigned checkColorValidity(LodePNGColorType colortype
, unsigned bd
) /*bd = bitdepth*/
2539 case 0: if(!(bd
== 1 || bd
== 2 || bd
== 4 || bd
== 8 || bd
== 16)) return 37; break; /*grey*/
2540 case 2: if(!( bd
== 8 || bd
== 16)) return 37; break; /*RGB*/
2541 case 3: if(!(bd
== 1 || bd
== 2 || bd
== 4 || bd
== 8 )) return 37; break; /*palette*/
2542 case 4: if(!( bd
== 8 || bd
== 16)) return 37; break; /*grey + alpha*/
2543 case 6: if(!( bd
== 8 || bd
== 16)) return 37; break; /*RGBA*/
2546 return 0; /*allowed color type / bits combination*/
2549 static unsigned getNumColorChannels(LodePNGColorType colortype
)
2553 case 0: return 1; /*grey*/
2554 case 2: return 3; /*RGB*/
2555 case 3: return 1; /*palette*/
2556 case 4: return 2; /*grey + alpha*/
2557 case 6: return 4; /*RGBA*/
2559 return 0; /*unexisting color type*/
2562 static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype
, unsigned bitdepth
)
2564 /*bits per pixel is amount of channels * bits per channel*/
2565 return getNumColorChannels(colortype
) * bitdepth
;
2568 /* ////////////////////////////////////////////////////////////////////////// */
2570 void lodepng_color_mode_init(LodePNGColorMode
* info
)
2572 info
->key_defined
= 0;
2573 info
->key_r
= info
->key_g
= info
->key_b
= 0;
2574 info
->colortype
= LCT_RGBA
;
2577 info
->palettesize
= 0;
2580 void lodepng_color_mode_cleanup(LodePNGColorMode
* info
)
2582 lodepng_palette_clear(info
);
2585 unsigned lodepng_color_mode_copy(LodePNGColorMode
* dest
, const LodePNGColorMode
* source
)
2588 lodepng_color_mode_cleanup(dest
);
2592 dest
->palette
= (unsigned char*)mymalloc(source
->palettesize
* 4);
2593 if(!dest
->palette
&& source
->palettesize
) return 83; /*alloc fail*/
2594 for(i
= 0; i
< source
->palettesize
* 4; i
++) dest
->palette
[i
] = source
->palette
[i
];
2599 static int lodepng_color_mode_equal(const LodePNGColorMode
* a
, const LodePNGColorMode
* b
)
2602 if(a
->colortype
!= b
->colortype
) return 0;
2603 if(a
->bitdepth
!= b
->bitdepth
) return 0;
2604 if(a
->key_defined
!= b
->key_defined
) return 0;
2607 if(a
->key_r
!= b
->key_r
) return 0;
2608 if(a
->key_g
!= b
->key_g
) return 0;
2609 if(a
->key_b
!= b
->key_b
) return 0;
2611 if(a
->palettesize
!= b
->palettesize
) return 0;
2612 for(i
= 0; i
< a
->palettesize
* 4; i
++)
2614 if(a
->palette
[i
] != b
->palette
[i
]) return 0;
2619 void lodepng_palette_clear(LodePNGColorMode
* info
)
2621 if(info
->palette
) myfree(info
->palette
);
2622 info
->palettesize
= 0;
2625 unsigned lodepng_palette_add(LodePNGColorMode
* info
,
2626 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
2628 unsigned char* data
;
2629 /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2630 the max of 256 colors, it'll have the exact alloc size*/
2631 if(!(info
->palettesize
& (info
->palettesize
- 1))) /*if palettesize is 0 or a power of two*/
2633 /*allocated data must be at least 4* palettesize (for 4 color bytes)*/
2634 size_t alloc_size
= info
->palettesize
== 0 ? 4 : info
->palettesize
* 4 * 2;
2635 data
= (unsigned char*)myrealloc(info
->palette
, alloc_size
);
2636 if(!data
) return 83; /*alloc fail*/
2637 else info
->palette
= data
;
2639 info
->palette
[4 * info
->palettesize
+ 0] = r
;
2640 info
->palette
[4 * info
->palettesize
+ 1] = g
;
2641 info
->palette
[4 * info
->palettesize
+ 2] = b
;
2642 info
->palette
[4 * info
->palettesize
+ 3] = a
;
2643 info
->palettesize
++;
2647 unsigned lodepng_get_bpp(const LodePNGColorMode
* info
)
2649 /*calculate bits per pixel out of colortype and bitdepth*/
2650 return lodepng_get_bpp_lct(info
->colortype
, info
->bitdepth
);
2653 unsigned lodepng_get_channels(const LodePNGColorMode
* info
)
2655 return getNumColorChannels(info
->colortype
);
2658 unsigned lodepng_is_greyscale_type(const LodePNGColorMode
* info
)
2660 return info
->colortype
== LCT_GREY
|| info
->colortype
== LCT_GREY_ALPHA
;
2663 unsigned lodepng_is_alpha_type(const LodePNGColorMode
* info
)
2665 return (info
->colortype
& 4) != 0; /*4 or 6*/
2668 unsigned lodepng_is_palette_type(const LodePNGColorMode
* info
)
2670 return info
->colortype
== LCT_PALETTE
;
2673 unsigned lodepng_has_palette_alpha(const LodePNGColorMode
* info
)
2676 for(i
= 0; i
< info
->palettesize
; i
++)
2678 if(info
->palette
[i
* 4 + 3] < 255) return 1;
2683 unsigned lodepng_can_have_alpha(const LodePNGColorMode
* info
)
2685 return info
->key_defined
2686 || lodepng_is_alpha_type(info
)
2687 || lodepng_has_palette_alpha(info
);
2690 size_t lodepng_get_raw_size(unsigned w
, unsigned h
, const LodePNGColorMode
* color
)
2692 return (w
* h
* lodepng_get_bpp(color
) + 7) / 8;
2695 size_t lodepng_get_raw_size_lct(unsigned w
, unsigned h
, LodePNGColorType colortype
, unsigned bitdepth
)
2697 return (w
* h
* lodepng_get_bpp_lct(colortype
, bitdepth
) + 7) / 8;
2700 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2702 static void LodePNGUnknownChunks_init(LodePNGInfo
* info
)
2705 for(i
= 0; i
< 3; i
++) info
->unknown_chunks_data
[i
] = 0;
2706 for(i
= 0; i
< 3; i
++) info
->unknown_chunks_size
[i
] = 0;
2709 static void LodePNGUnknownChunks_cleanup(LodePNGInfo
* info
)
2712 for(i
= 0; i
< 3; i
++) myfree(info
->unknown_chunks_data
[i
]);
2715 static unsigned LodePNGUnknownChunks_copy(LodePNGInfo
* dest
, const LodePNGInfo
* src
)
2719 LodePNGUnknownChunks_cleanup(dest
);
2721 for(i
= 0; i
< 3; i
++)
2724 dest
->unknown_chunks_size
[i
] = src
->unknown_chunks_size
[i
];
2725 dest
->unknown_chunks_data
[i
] = (unsigned char*)mymalloc(src
->unknown_chunks_size
[i
]);
2726 if(!dest
->unknown_chunks_data
[i
] && dest
->unknown_chunks_size
[i
]) return 83; /*alloc fail*/
2727 for(j
= 0; j
< src
->unknown_chunks_size
[i
]; j
++)
2729 dest
->unknown_chunks_data
[i
][j
] = src
->unknown_chunks_data
[i
][j
];
2736 /******************************************************************************/
2738 static void LodePNGText_init(LodePNGInfo
* info
)
2741 info
->text_keys
= NULL
;
2742 info
->text_strings
= NULL
;
2745 static void LodePNGText_cleanup(LodePNGInfo
* info
)
2748 for(i
= 0; i
< info
->text_num
; i
++)
2750 string_cleanup(&info
->text_keys
[i
]);
2751 string_cleanup(&info
->text_strings
[i
]);
2753 myfree(info
->text_keys
);
2754 myfree(info
->text_strings
);
2757 static unsigned LodePNGText_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2760 dest
->text_keys
= 0;
2761 dest
->text_strings
= 0;
2763 for(i
= 0; i
< source
->text_num
; i
++)
2765 CERROR_TRY_RETURN(lodepng_add_text(dest
, source
->text_keys
[i
], source
->text_strings
[i
]));
2770 void lodepng_clear_text(LodePNGInfo
* info
)
2772 LodePNGText_cleanup(info
);
2775 unsigned lodepng_add_text(LodePNGInfo
* info
, const char* key
, const char* str
)
2777 char** new_keys
= (char**)(myrealloc(info
->text_keys
, sizeof(char*) * (info
->text_num
+ 1)));
2778 char** new_strings
= (char**)(myrealloc(info
->text_strings
, sizeof(char*) * (info
->text_num
+ 1)));
2779 if(!new_keys
|| !new_strings
)
2782 myfree(new_strings
);
2783 return 83; /*alloc fail*/
2787 info
->text_keys
= new_keys
;
2788 info
->text_strings
= new_strings
;
2790 string_init(&info
->text_keys
[info
->text_num
- 1]);
2791 string_set(&info
->text_keys
[info
->text_num
- 1], key
);
2793 string_init(&info
->text_strings
[info
->text_num
- 1]);
2794 string_set(&info
->text_strings
[info
->text_num
- 1], str
);
2799 /******************************************************************************/
2801 static void LodePNGIText_init(LodePNGInfo
* info
)
2803 info
->itext_num
= 0;
2804 info
->itext_keys
= NULL
;
2805 info
->itext_langtags
= NULL
;
2806 info
->itext_transkeys
= NULL
;
2807 info
->itext_strings
= NULL
;
2810 static void LodePNGIText_cleanup(LodePNGInfo
* info
)
2813 for(i
= 0; i
< info
->itext_num
; i
++)
2815 string_cleanup(&info
->itext_keys
[i
]);
2816 string_cleanup(&info
->itext_langtags
[i
]);
2817 string_cleanup(&info
->itext_transkeys
[i
]);
2818 string_cleanup(&info
->itext_strings
[i
]);
2820 myfree(info
->itext_keys
);
2821 myfree(info
->itext_langtags
);
2822 myfree(info
->itext_transkeys
);
2823 myfree(info
->itext_strings
);
2826 static unsigned LodePNGIText_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2829 dest
->itext_keys
= 0;
2830 dest
->itext_langtags
= 0;
2831 dest
->itext_transkeys
= 0;
2832 dest
->itext_strings
= 0;
2833 dest
->itext_num
= 0;
2834 for(i
= 0; i
< source
->itext_num
; i
++)
2836 CERROR_TRY_RETURN(lodepng_add_itext(dest
, source
->itext_keys
[i
], source
->itext_langtags
[i
],
2837 source
->itext_transkeys
[i
], source
->itext_strings
[i
]));
2842 void lodepng_clear_itext(LodePNGInfo
* info
)
2844 LodePNGIText_cleanup(info
);
2847 unsigned lodepng_add_itext(LodePNGInfo
* info
, const char* key
, const char* langtag
,
2848 const char* transkey
, const char* str
)
2850 char** new_keys
= (char**)(myrealloc(info
->itext_keys
, sizeof(char*) * (info
->itext_num
+ 1)));
2851 char** new_langtags
= (char**)(myrealloc(info
->itext_langtags
, sizeof(char*) * (info
->itext_num
+ 1)));
2852 char** new_transkeys
= (char**)(myrealloc(info
->itext_transkeys
, sizeof(char*) * (info
->itext_num
+ 1)));
2853 char** new_strings
= (char**)(myrealloc(info
->itext_strings
, sizeof(char*) * (info
->itext_num
+ 1)));
2854 if(!new_keys
|| !new_langtags
|| !new_transkeys
|| !new_strings
)
2857 myfree(new_langtags
);
2858 myfree(new_transkeys
);
2859 myfree(new_strings
);
2860 return 83; /*alloc fail*/
2864 info
->itext_keys
= new_keys
;
2865 info
->itext_langtags
= new_langtags
;
2866 info
->itext_transkeys
= new_transkeys
;
2867 info
->itext_strings
= new_strings
;
2869 string_init(&info
->itext_keys
[info
->itext_num
- 1]);
2870 string_set(&info
->itext_keys
[info
->itext_num
- 1], key
);
2872 string_init(&info
->itext_langtags
[info
->itext_num
- 1]);
2873 string_set(&info
->itext_langtags
[info
->itext_num
- 1], langtag
);
2875 string_init(&info
->itext_transkeys
[info
->itext_num
- 1]);
2876 string_set(&info
->itext_transkeys
[info
->itext_num
- 1], transkey
);
2878 string_init(&info
->itext_strings
[info
->itext_num
- 1]);
2879 string_set(&info
->itext_strings
[info
->itext_num
- 1], str
);
2883 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2885 void lodepng_info_init(LodePNGInfo
* info
)
2887 lodepng_color_mode_init(&info
->color
);
2888 info
->interlace_method
= 0;
2889 info
->compression_method
= 0;
2890 info
->filter_method
= 0;
2891 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2892 info
->background_defined
= 0;
2893 info
->background_r
= info
->background_g
= info
->background_b
= 0;
2895 LodePNGText_init(info
);
2896 LodePNGIText_init(info
);
2898 info
->time_defined
= 0;
2899 info
->phys_defined
= 0;
2901 LodePNGUnknownChunks_init(info
);
2902 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2905 void lodepng_info_cleanup(LodePNGInfo
* info
)
2907 lodepng_color_mode_cleanup(&info
->color
);
2908 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2909 LodePNGText_cleanup(info
);
2910 LodePNGIText_cleanup(info
);
2912 LodePNGUnknownChunks_cleanup(info
);
2913 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2916 unsigned lodepng_info_copy(LodePNGInfo
* dest
, const LodePNGInfo
* source
)
2918 lodepng_info_cleanup(dest
);
2920 lodepng_color_mode_init(&dest
->color
);
2921 CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest
->color
, &source
->color
));
2923 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2924 CERROR_TRY_RETURN(LodePNGText_copy(dest
, source
));
2925 CERROR_TRY_RETURN(LodePNGIText_copy(dest
, source
));
2927 LodePNGUnknownChunks_init(dest
);
2928 CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest
, source
));
2929 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
2933 void lodepng_info_swap(LodePNGInfo
* a
, LodePNGInfo
* b
)
2935 LodePNGInfo temp
= *a
;
2940 /* ////////////////////////////////////////////////////////////////////////// */
2942 /*index: bitgroup index, bits: bitgroup size(1, 2 or 4, in: bitgroup value, out: octet array to add bits to*/
2943 static void addColorBits(unsigned char* out
, size_t index
, unsigned bits
, unsigned in
)
2945 /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
2946 unsigned p
= index
% (8 / bits
);
2947 in
&= (1 << bits
) - 1; /*filter out any other bits of the input value*/
2948 in
= in
<< (bits
* (8 / bits
- p
- 1));
2949 if(p
== 0) out
[index
* bits
/ 8] = in
;
2950 else out
[index
* bits
/ 8] |= in
;
2954 typedef struct ColorTree ColorTree
;
2957 One node of a color tree
2958 This is the data structure used to count the number of unique colors and to get a palette
2959 index for a color. It's like an octree, but because the alpha channel is used too, each
2960 node has 16 instead of 8 children.
2964 ColorTree
* children
[16]; /*up to 16 pointers to ColorTree of next level*/
2965 int index
; /*the payload. Only has a meaningful value if this is in the last level*/
2968 static void color_tree_init(ColorTree
* tree
)
2971 for(i
= 0; i
< 16; i
++) tree
->children
[i
] = 0;
2975 static void color_tree_cleanup(ColorTree
* tree
)
2978 for(i
= 0; i
< 16; i
++)
2980 if(tree
->children
[i
])
2982 color_tree_cleanup(tree
->children
[i
]);
2983 myfree(tree
->children
[i
]);
2988 /*returns -1 if color not present, its index otherwise*/
2989 static int color_tree_get(ColorTree
* tree
, unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
2992 for(bit
= 0; bit
< 8; bit
++)
2994 int i
= 8 * ((r
>> bit
) & 1) + 4 * ((g
>> bit
) & 1) + 2 * ((b
>> bit
) & 1) + 1 * ((a
>> bit
) & 1);
2995 if(!tree
->children
[i
]) return -1;
2996 else tree
= tree
->children
[i
];
2998 return tree
? tree
->index
: -1;
3001 #ifdef LODEPNG_COMPILE_ENCODER
3002 static int color_tree_has(ColorTree
* tree
, unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
3004 return color_tree_get(tree
, r
, g
, b
, a
) >= 0;
3006 #endif /*LODEPNG_COMPILE_ENCODER*/
3008 /*color is not allowed to already exist.
3009 Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
3010 static void color_tree_add(ColorTree
* tree
,
3011 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
, int index
)
3014 for(bit
= 0; bit
< 8; bit
++)
3016 int i
= 8 * ((r
>> bit
) & 1) + 4 * ((g
>> bit
) & 1) + 2 * ((b
>> bit
) & 1) + 1 * ((a
>> bit
) & 1);
3017 if(!tree
->children
[i
])
3019 tree
->children
[i
] = (ColorTree
*)mymalloc(sizeof(ColorTree
));
3020 color_tree_init(tree
->children
[i
]);
3022 tree
= tree
->children
[i
];
3024 tree
->index
= index
;
3027 /*put a pixel, given its RGBA color, into image of any color type*/
3028 static unsigned rgba8ToPixel(unsigned char* out
, size_t i
,
3029 const LodePNGColorMode
* mode
, ColorTree
* tree
/*for palette*/,
3030 unsigned char r
, unsigned char g
, unsigned char b
, unsigned char a
)
3032 if(mode
->colortype
== LCT_GREY
)
3034 unsigned char grey
= r
; /*((UINT16)r + g + b) / 3*/;
3035 if(mode
->bitdepth
== 8) out
[i
] = grey
;
3036 else if(mode
->bitdepth
== 16) out
[i
* 2 + 0] = out
[i
* 2 + 1] = grey
;
3039 /*take the most significant bits of grey*/
3040 grey
= (grey
>> (8 - mode
->bitdepth
)) & ((1 << mode
->bitdepth
) - 1);
3041 addColorBits(out
, i
, mode
->bitdepth
, grey
);
3044 else if(mode
->colortype
== LCT_RGB
)
3046 if(mode
->bitdepth
== 8)
3054 out
[i
* 6 + 0] = out
[i
* 6 + 1] = r
;
3055 out
[i
* 6 + 2] = out
[i
* 6 + 3] = g
;
3056 out
[i
* 6 + 4] = out
[i
* 6 + 5] = b
;
3059 else if(mode
->colortype
== LCT_PALETTE
)
3061 int index
= color_tree_get(tree
, r
, g
, b
, a
);
3062 if(index
< 0) return 82; /*color not in palette*/
3063 if(mode
->bitdepth
== 8) out
[i
] = index
;
3064 else addColorBits(out
, i
, mode
->bitdepth
, index
);
3066 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3068 unsigned char grey
= r
; /*((UINT16)r + g + b) / 3*/;
3069 if(mode
->bitdepth
== 8)
3071 out
[i
* 2 + 0] = grey
;
3074 else if(mode
->bitdepth
== 16)
3076 out
[i
* 4 + 0] = out
[i
* 4 + 1] = grey
;
3077 out
[i
* 4 + 2] = out
[i
* 4 + 3] = a
;
3080 else if(mode
->colortype
== LCT_RGBA
)
3082 if(mode
->bitdepth
== 8)
3091 out
[i
* 8 + 0] = out
[i
* 8 + 1] = r
;
3092 out
[i
* 8 + 2] = out
[i
* 8 + 3] = g
;
3093 out
[i
* 8 + 4] = out
[i
* 8 + 5] = b
;
3094 out
[i
* 8 + 6] = out
[i
* 8 + 7] = a
;
3098 return 0; /*no error*/
3101 /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3102 static unsigned rgba16ToPixel(unsigned char* out
, size_t i
,
3103 const LodePNGColorMode
* mode
,
3104 UINT16 r
, UINT16 g
, UINT16 b
, UINT16 a
)
3106 if(mode
->bitdepth
!= 16) return 85; /*must be 16 for this function*/
3107 if(mode
->colortype
== LCT_GREY
)
3109 UINT16 grey
= r
; /*((unsigned)r + g + b) / 3*/;
3110 out
[i
* 2 + 0] = (grey
>> 8) & 255;
3111 out
[i
* 2 + 1] = grey
& 255;
3113 else if(mode
->colortype
== LCT_RGB
)
3115 out
[i
* 6 + 0] = (r
>> 8) & 255;
3116 out
[i
* 6 + 1] = r
& 255;
3117 out
[i
* 6 + 2] = (g
>> 8) & 255;
3118 out
[i
* 6 + 3] = g
& 255;
3119 out
[i
* 6 + 4] = (b
>> 8) & 255;
3120 out
[i
* 6 + 5] = b
& 255;
3122 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3124 UINT16 grey
= r
; /*((unsigned)r + g + b) / 3*/;
3125 out
[i
* 4 + 0] = (grey
>> 8) & 255;
3126 out
[i
* 4 + 1] = grey
& 255;
3127 out
[i
* 4 + 2] = (a
>> 8) & 255;
3128 out
[i
* 4 + 3] = a
& 255;
3130 else if(mode
->colortype
== LCT_RGBA
)
3132 out
[i
* 8 + 0] = (r
>> 8) & 255;
3133 out
[i
* 8 + 1] = r
& 255;
3134 out
[i
* 8 + 2] = (g
>> 8) & 255;
3135 out
[i
* 8 + 3] = g
& 255;
3136 out
[i
* 8 + 4] = (b
>> 8) & 255;
3137 out
[i
* 8 + 5] = b
& 255;
3138 out
[i
* 8 + 6] = (a
>> 8) & 255;
3139 out
[i
* 8 + 7] = a
& 255;
3142 return 0; /*no error*/
3145 /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3146 static unsigned getPixelColorRGBA8(unsigned char* r
, unsigned char* g
,
3147 unsigned char* b
, unsigned char* a
,
3148 const unsigned char* in
, size_t i
,
3149 const LodePNGColorMode
* mode
)
3151 if(mode
->colortype
== LCT_GREY
)
3153 if(mode
->bitdepth
== 8)
3155 *r
= *g
= *b
= in
[i
];
3156 if(mode
->key_defined
&& *r
== mode
->key_r
) *a
= 0;
3159 else if(mode
->bitdepth
== 16)
3161 *r
= *g
= *b
= in
[i
* 2 + 0];
3162 if(mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
) *a
= 0;
3167 unsigned highest
= ((1U << mode
->bitdepth
) - 1U); /*highest possible value for this bit depth*/
3168 size_t j
= i
* mode
->bitdepth
;
3169 unsigned value
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3170 *r
= *g
= *b
= (value
* 255) / highest
;
3171 if(mode
->key_defined
&& value
== mode
->key_r
) *a
= 0;
3175 else if(mode
->colortype
== LCT_RGB
)
3177 if(mode
->bitdepth
== 8)
3179 *r
= in
[i
* 3 + 0]; *g
= in
[i
* 3 + 1]; *b
= in
[i
* 3 + 2];
3180 if(mode
->key_defined
&& *r
== mode
->key_r
&& *g
== mode
->key_g
&& *b
== mode
->key_b
) *a
= 0;
3188 if(mode
->key_defined
&& 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3189 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3190 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
) *a
= 0;
3194 else if(mode
->colortype
== LCT_PALETTE
)
3197 if(mode
->bitdepth
== 8) index
= in
[i
];
3200 size_t j
= i
* mode
->bitdepth
;
3201 index
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3203 if(index
>= mode
->palettesize
) return 47; /*index out of palette*/
3204 *r
= mode
->palette
[index
* 4 + 0];
3205 *g
= mode
->palette
[index
* 4 + 1];
3206 *b
= mode
->palette
[index
* 4 + 2];
3207 *a
= mode
->palette
[index
* 4 + 3];
3209 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3211 if(mode
->bitdepth
== 8)
3213 *r
= *g
= *b
= in
[i
* 2 + 0];
3218 *r
= *g
= *b
= in
[i
* 4 + 0];
3222 else if(mode
->colortype
== LCT_RGBA
)
3224 if(mode
->bitdepth
== 8)
3240 return 0; /*no error*/
3243 /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3244 mode test cases, optimized to convert the colors much faster, when converting
3245 to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
3246 enough memory, if has_alpha is true the output is RGBA. mode has the color mode
3247 of the input buffer.*/
3248 static unsigned getPixelColorsRGBA8(unsigned char* buffer
, size_t numpixels
,
3249 unsigned has_alpha
, const unsigned char* in
,
3250 const LodePNGColorMode
* mode
)
3252 unsigned num_channels
= has_alpha
? 4 : 3;
3254 if(mode
->colortype
== LCT_GREY
)
3256 if(mode
->bitdepth
== 8)
3258 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3260 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
];
3261 if(has_alpha
) buffer
[3] = mode
->key_defined
&& in
[i
] == mode
->key_r
? 0 : 255;
3264 else if(mode
->bitdepth
== 16)
3266 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3268 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 2];
3269 if(has_alpha
) buffer
[3] = mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
? 0 : 255;
3274 unsigned highest
= ((1U << mode
->bitdepth
) - 1U); /*highest possible value for this bit depth*/
3276 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3278 unsigned value
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3279 buffer
[0] = buffer
[1] = buffer
[2] = (value
* 255) / highest
;
3280 if(has_alpha
) buffer
[3] = mode
->key_defined
&& value
== mode
->key_r
? 0 : 255;
3284 else if(mode
->colortype
== LCT_RGB
)
3286 if(mode
->bitdepth
== 8)
3288 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3290 buffer
[0] = in
[i
* 3 + 0];
3291 buffer
[1] = in
[i
* 3 + 1];
3292 buffer
[2] = in
[i
* 3 + 2];
3293 if(has_alpha
) buffer
[3] = mode
->key_defined
&& buffer
[0] == mode
->key_r
3294 && buffer
[1]== mode
->key_g
&& buffer
[2] == mode
->key_b
? 0 : 255;
3299 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3301 buffer
[0] = in
[i
* 6 + 0];
3302 buffer
[1] = in
[i
* 6 + 2];
3303 buffer
[2] = in
[i
* 6 + 4];
3304 if(has_alpha
) buffer
[3] = mode
->key_defined
3305 && 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3306 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3307 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
? 0 : 255;
3311 else if(mode
->colortype
== LCT_PALETTE
)
3315 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3317 if(mode
->bitdepth
== 8) index
= in
[i
];
3318 else index
= readBitsFromReversedStream(&j
, in
, mode
->bitdepth
);
3319 if(index
>= mode
->palettesize
) return 47; /*index out of palette*/
3320 buffer
[0] = mode
->palette
[index
* 4 + 0];
3321 buffer
[1] = mode
->palette
[index
* 4 + 1];
3322 buffer
[2] = mode
->palette
[index
* 4 + 2];
3323 if(has_alpha
) buffer
[3] = mode
->palette
[index
* 4 + 3];
3326 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3328 if(mode
->bitdepth
== 8)
3330 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3332 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 2 + 0];
3333 if(has_alpha
) buffer
[3] = in
[i
* 2 + 1];
3338 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3340 buffer
[0] = buffer
[1] = buffer
[2] = in
[i
* 4 + 0];
3341 if(has_alpha
) buffer
[3] = in
[i
* 4 + 2];
3345 else if(mode
->colortype
== LCT_RGBA
)
3347 if(mode
->bitdepth
== 8)
3349 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3351 buffer
[0] = in
[i
* 4 + 0];
3352 buffer
[1] = in
[i
* 4 + 1];
3353 buffer
[2] = in
[i
* 4 + 2];
3354 if(has_alpha
) buffer
[3] = in
[i
* 4 + 3];
3359 for(i
= 0; i
< numpixels
; i
++, buffer
+= num_channels
)
3361 buffer
[0] = in
[i
* 8 + 0];
3362 buffer
[1] = in
[i
* 8 + 2];
3363 buffer
[2] = in
[i
* 8 + 4];
3364 if(has_alpha
) buffer
[3] = in
[i
* 8 + 6];
3369 return 0; /*no error*/
3372 /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3373 given color type, but the given color type must be 16-bit itself.*/
3374 static unsigned getPixelColorRGBA16(UINT16
* r
, UINT16
* g
, UINT16
* b
, UINT16
* a
,
3375 const unsigned char* in
, size_t i
, const LodePNGColorMode
* mode
)
3377 if(mode
->bitdepth
!= 16) return 85; /*error: this function only supports 16-bit input*/
3379 if(mode
->colortype
== LCT_GREY
)
3381 *r
= *g
= *b
= 256 * in
[i
* 2 + 0] + in
[i
* 2 + 1];
3382 if(mode
->key_defined
&& 256U * in
[i
* 2 + 0] + in
[i
* 2 + 1] == mode
->key_r
) *a
= 0;
3385 else if(mode
->colortype
== LCT_RGB
)
3387 *r
= 256 * in
[i
* 6 + 0] + in
[i
* 6 + 1];
3388 *g
= 256 * in
[i
* 6 + 2] + in
[i
* 6 + 3];
3389 *b
= 256 * in
[i
* 6 + 4] + in
[i
* 6 + 5];
3390 if(mode
->key_defined
&& 256U * in
[i
* 6 + 0] + in
[i
* 6 + 1] == mode
->key_r
3391 && 256U * in
[i
* 6 + 2] + in
[i
* 6 + 3] == mode
->key_g
3392 && 256U * in
[i
* 6 + 4] + in
[i
* 6 + 5] == mode
->key_b
) *a
= 0;
3395 else if(mode
->colortype
== LCT_GREY_ALPHA
)
3397 *r
= *g
= *b
= 256 * in
[i
* 4 + 0] + in
[i
* 4 + 1];
3398 *a
= 256 * in
[i
* 4 + 2] + in
[i
* 4 + 3];
3400 else if(mode
->colortype
== LCT_RGBA
)
3402 *r
= 256 * in
[i
* 8 + 0] + in
[i
* 8 + 1];
3403 *g
= 256 * in
[i
* 8 + 2] + in
[i
* 8 + 3];
3404 *b
= 256 * in
[i
* 8 + 4] + in
[i
* 8 + 5];
3405 *a
= 256 * in
[i
* 8 + 6] + in
[i
* 8 + 7];
3407 else return 85; /*error: this function only supports 16-bit input, not palettes*/
3409 return 0; /*no error*/
3413 converts from any color type to 24-bit or 32-bit (later maybe more supported). return value = LodePNG error code
3414 the out buffer must have (w * h * bpp + 7) / 8 bytes, where bpp is the bits per pixel of the output color type
3415 (lodepng_get_bpp) for < 8 bpp images, there may _not_ be padding bits at the end of scanlines.
3417 unsigned lodepng_convert(unsigned char* out
, const unsigned char* in
,
3418 LodePNGColorMode
* mode_out
, LodePNGColorMode
* mode_in
,
3419 unsigned w
, unsigned h
)
3424 size_t numpixels
= w
* h
;
3426 if(lodepng_color_mode_equal(mode_out
, mode_in
))
3428 size_t numbytes
= lodepng_get_raw_size(w
, h
, mode_in
);
3429 for(i
= 0; i
< numbytes
; i
++) out
[i
] = in
[i
];
3433 if(mode_out
->colortype
== LCT_PALETTE
)
3435 size_t palsize
= 1 << mode_out
->bitdepth
;
3436 if(mode_out
->palettesize
< palsize
) palsize
= mode_out
->palettesize
;
3437 color_tree_init(&tree
);
3438 for(i
= 0; i
< palsize
; i
++)
3440 unsigned char* p
= &mode_out
->palette
[i
* 4];
3441 color_tree_add(&tree
, p
[0], p
[1], p
[2], p
[3], i
);
3445 if(mode_in
->bitdepth
== 16 && mode_out
->bitdepth
== 16)
3447 for(i
= 0; i
< numpixels
; i
++)
3449 UINT16 r
= 0, g
= 0, b
= 0, a
= 0;
3450 error
= getPixelColorRGBA16(&r
, &g
, &b
, &a
, in
, i
, mode_in
);
3452 error
= rgba16ToPixel(out
, i
, mode_out
, r
, g
, b
, a
);
3456 else if(mode_out
->bitdepth
== 8 && mode_out
->colortype
== LCT_RGBA
)
3458 error
= getPixelColorsRGBA8(out
, numpixels
, 1, in
, mode_in
);
3460 else if(mode_out
->bitdepth
== 8 && mode_out
->colortype
== LCT_RGB
)
3462 error
= getPixelColorsRGBA8(out
, numpixels
, 0, in
, mode_in
);
3466 unsigned char r
= 0, g
= 0, b
= 0, a
= 0;
3467 for(i
= 0; i
< numpixels
; i
++)
3469 error
= getPixelColorRGBA8(&r
, &g
, &b
, &a
, in
, i
, mode_in
);
3471 error
= rgba8ToPixel(out
, i
, mode_out
, &tree
, r
, g
, b
, a
);
3476 if(mode_out
->colortype
== LCT_PALETTE
)
3478 color_tree_cleanup(&tree
);
3484 #ifdef LODEPNG_COMPILE_ENCODER
3487 typedef struct ColorProfile
3489 unsigned char sixteenbit
; /*needs more than 8 bits per channel*/
3490 unsigned char sixteenbit_done
;
3493 unsigned char colored
; /*not greyscale*/
3494 unsigned char colored_done
;
3496 unsigned char key
; /*a color key is required, or more*/
3497 UINT16 key_r
; /*these values are always in 16-bit bitdepth in the profile*/
3500 unsigned char alpha
; /*alpha channel, or alpha palette, required*/
3501 unsigned char alpha_done
;
3504 ColorTree tree
; /*for listing the counted colors, up to 256*/
3505 unsigned char* palette
; /*size 1024. Remember up to the first 256 RGBA colors*/
3506 unsigned maxnumcolors
; /*if more than that amount counted*/
3507 unsigned char numcolors_done
;
3509 unsigned greybits
; /*amount of bits required for greyscale (1, 2, 4, 8). Does not take 16 bit into account.*/
3510 unsigned char greybits_done
;
3514 static void color_profile_init(ColorProfile
* profile
, LodePNGColorMode
* mode
)
3516 profile
->sixteenbit
= 0;
3517 profile
->sixteenbit_done
= mode
->bitdepth
== 16 ? 0 : 1;
3519 profile
->colored
= 0;
3520 profile
->colored_done
= lodepng_is_greyscale_type(mode
) ? 1 : 0;
3524 profile
->alpha_done
= lodepng_can_have_alpha(mode
) ? 0 : 1;
3526 profile
->numcolors
= 0;
3527 color_tree_init(&profile
->tree
);
3528 profile
->palette
= (unsigned char*)mymalloc(1024);
3529 profile
->maxnumcolors
= 257;
3530 if(lodepng_get_bpp(mode
) <= 8)
3532 int bpp
= lodepng_get_bpp(mode
);
3533 profile
->maxnumcolors
= bpp
== 1 ? 2 : (bpp
== 2 ? 4 : (bpp
== 4 ? 16 : 256));
3535 profile
->numcolors_done
= 0;
3537 profile
->greybits
= 1;
3538 profile
->greybits_done
= lodepng_get_bpp(mode
) == 1 ? 1 : 0;
3541 static void color_profile_cleanup(ColorProfile
* profile
)
3543 color_tree_cleanup(&profile
->tree
);
3544 myfree(profile
->palette
);
3547 /*function used for debug purposes with C++*/
3548 /*void printColorProfile(ColorProfile* p)
3550 std::cout << "sixteenbit: " << (int)p->sixteenbit << std::endl;
3551 std::cout << "sixteenbit_done: " << (int)p->sixteenbit_done << std::endl;
3552 std::cout << "colored: " << (int)p->colored << std::endl;
3553 std::cout << "colored_done: " << (int)p->colored_done << std::endl;
3554 std::cout << "key: " << (int)p->key << std::endl;
3555 std::cout << "key_r: " << (int)p->key_r << std::endl;
3556 std::cout << "key_g: " << (int)p->key_g << std::endl;
3557 std::cout << "key_b: " << (int)p->key_b << std::endl;
3558 std::cout << "alpha: " << (int)p->alpha << std::endl;
3559 std::cout << "alpha_done: " << (int)p->alpha_done << std::endl;
3560 std::cout << "numcolors: " << (int)p->numcolors << std::endl;
3561 std::cout << "maxnumcolors: " << (int)p->maxnumcolors << std::endl;
3562 std::cout << "numcolors_done: " << (int)p->numcolors_done << std::endl;
3563 std::cout << "greybits: " << (int)p->greybits << std::endl;
3564 std::cout << "greybits_done: " << (int)p->greybits_done << std::endl;
3567 /*Returns how many bits needed to represent given value (max 8 bit)*/
3568 unsigned getValueRequiredBits(UINT16 value
)
3570 if(value
== 0 || value
== 255) return 1;
3571 /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3572 if(value
% 17 == 0) return value
% 85 == 0 ? 2 : 4;
3576 /*profile must already have been inited with mode.
3577 It's ok to set some parameters of profile to done already.*/
3578 static unsigned get_color_profile(ColorProfile
* profile
,
3579 const unsigned char* in
, size_t numpixels
,
3580 LodePNGColorMode
* mode
)
3585 if(mode
->bitdepth
== 16)
3587 for(i
= 0; i
< numpixels
; i
++)
3590 error
= getPixelColorRGBA16(&r
, &g
, &b
, &a
, in
, i
, mode
);
3593 /*a color is considered good for 8-bit if the first byte and the second byte are equal,
3594 (so if it's divisible through 257), NOT necessarily if the second byte is 0*/
3595 if(!profile
->sixteenbit_done
3596 && (((r
& 255) != ((r
>> 8) & 255))
3597 || ((g
& 255) != ((g
>> 8) & 255))
3598 || ((b
& 255) != ((b
>> 8) & 255))))
3600 profile
->sixteenbit
= 1;
3601 profile
->sixteenbit_done
= 1;
3602 profile
->greybits_done
= 1; /*greybits is not applicable anymore at 16-bit*/
3603 profile
->numcolors_done
= 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3606 if(!profile
->colored_done
&& (r
!= g
|| r
!= b
))
3608 profile
->colored
= 1;
3609 profile
->colored_done
= 1;
3610 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3613 if(!profile
->alpha_done
&& a
!= 255)
3615 if(a
== 0 && !(profile
->key
&& (r
!= profile
->key_r
|| g
!= profile
->key_g
|| b
!= profile
->key_b
)))
3628 profile
->alpha_done
= 1;
3629 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3633 if(!profile
->greybits_done
)
3635 /*assuming 8-bit r, this test does not care about 16-bit*/
3636 unsigned bits
= getValueRequiredBits(r
);
3637 if(bits
> profile
->greybits
) profile
->greybits
= bits
;
3638 if(profile
->greybits
>= 8) profile
->greybits_done
= 1;
3641 if(!profile
->numcolors_done
)
3643 /*assuming 8-bit rgba, this test does not care about 16-bit*/
3644 if(!color_tree_has(&profile
->tree
, (unsigned char)r
, (unsigned char)g
, (unsigned char)b
, (unsigned char)a
))
3646 color_tree_add(&profile
->tree
, (unsigned char)r
, (unsigned char)g
, (unsigned char)b
, (unsigned char)a
,
3647 profile
->numcolors
);
3648 if(profile
->numcolors
< 256)
3650 unsigned char* p
= profile
->palette
;
3651 unsigned i
= profile
->numcolors
;
3652 p
[i
* 4 + 0] = (unsigned char)r
;
3653 p
[i
* 4 + 1] = (unsigned char)g
;
3654 p
[i
* 4 + 2] = (unsigned char)b
;
3655 p
[i
* 4 + 3] = (unsigned char)a
;
3657 profile
->numcolors
++;
3658 if(profile
->numcolors
>= profile
->maxnumcolors
) profile
->numcolors_done
= 1;
3662 if(profile
->alpha_done
&& profile
->numcolors_done
3663 && profile
->colored_done
&& profile
->sixteenbit_done
&& profile
->greybits_done
)
3671 for(i
= 0; i
< numpixels
; i
++)
3673 unsigned char r
= 0, g
= 0, b
= 0, a
= 0;
3674 error
= getPixelColorRGBA8(&r
, &g
, &b
, &a
, in
, i
, mode
);
3677 if(!profile
->colored_done
&& (r
!= g
|| r
!= b
))
3679 profile
->colored
= 1;
3680 profile
->colored_done
= 1;
3681 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3684 if(!profile
->alpha_done
&& a
!= 255)
3686 if(a
== 0 && !(profile
->key
&& (r
!= profile
->key_r
|| g
!= profile
->key_g
|| b
!= profile
->key_b
)))
3699 profile
->alpha_done
= 1;
3700 profile
->greybits_done
= 1; /*greybits is not applicable anymore*/
3704 if(!profile
->greybits_done
)
3706 unsigned bits
= getValueRequiredBits(r
);
3707 if(bits
> profile
->greybits
) profile
->greybits
= bits
;
3708 if(profile
->greybits
>= 8) profile
->greybits_done
= 1;
3711 if(!profile
->numcolors_done
)
3713 if(!color_tree_has(&profile
->tree
, r
, g
, b
, a
))
3716 color_tree_add(&profile
->tree
, r
, g
, b
, a
, profile
->numcolors
);
3717 if(profile
->numcolors
< 256)
3719 unsigned char* p
= profile
->palette
;
3720 unsigned i
= profile
->numcolors
;
3726 profile
->numcolors
++;
3727 if(profile
->numcolors
>= profile
->maxnumcolors
) profile
->numcolors_done
= 1;
3731 if(profile
->alpha_done
&& profile
->numcolors_done
&& profile
->colored_done
&& profile
->greybits_done
)
3738 /*make the profile's key always 16-bit for consistency*/
3739 if(mode
->bitdepth
< 16)
3741 /*repeat each byte twice*/
3742 profile
->key_r
*= 257;
3743 profile
->key_g
*= 257;
3744 profile
->key_b
*= 257;
3750 /*updates values of mode with a potentially smaller color model. mode_out should
3751 contain the user chosen color model, but will be overwritten with the new chosen one.*/
3752 static unsigned doAutoChooseColor(LodePNGColorMode
* mode_out
,
3753 const unsigned char* image
, unsigned w
, unsigned h
, LodePNGColorMode
* mode_in
,
3754 LodePNGAutoConvert auto_convert
)
3756 ColorProfile profile
;
3758 int no_nibbles
= auto_convert
== LAC_AUTO_NO_NIBBLES
|| auto_convert
== LAC_AUTO_NO_NIBBLES_NO_PALETTE
;
3759 int no_palette
= auto_convert
== LAC_AUTO_NO_PALETTE
|| auto_convert
== LAC_AUTO_NO_NIBBLES_NO_PALETTE
;
3761 if(auto_convert
== LAC_ALPHA
)
3763 if(mode_out
->colortype
!= LCT_RGBA
&& mode_out
->colortype
!= LCT_GREY_ALPHA
) return 0;
3766 color_profile_init(&profile
, mode_in
);
3767 if(auto_convert
== LAC_ALPHA
)
3769 profile
.colored_done
= 1;
3770 profile
.greybits_done
= 1;
3771 profile
.numcolors_done
= 1;
3772 profile
.sixteenbit_done
= 1;
3774 error
= get_color_profile(&profile
, image
, w
* h
, mode_in
);
3776 if(!error
&& auto_convert
== LAC_ALPHA
)
3780 mode_out
->colortype
= (mode_out
->colortype
== LCT_RGBA
? LCT_RGB
: LCT_GREY
);
3783 else if(!error
&& auto_convert
!= LAC_ALPHA
)
3785 mode_out
->key_defined
= 0;
3787 if(profile
.sixteenbit
)
3789 mode_out
->bitdepth
= 16;
3792 mode_out
->colortype
= profile
.colored
? LCT_RGBA
: LCT_GREY_ALPHA
;
3796 mode_out
->colortype
= profile
.colored
? LCT_RGB
: LCT_GREY
;
3799 mode_out
->key_defined
= 1;
3800 mode_out
->key_r
= profile
.key_r
;
3801 mode_out
->key_g
= profile
.key_g
;
3802 mode_out
->key_b
= profile
.key_b
;
3806 else /*less than 16 bits per channel*/
3808 /*don't add palette overhead if image hasn't got a lot of pixels*/
3809 unsigned n
= profile
.numcolors
;
3810 int palette_ok
= !no_palette
&& n
<= 256 && (n
* 2 < w
* h
);
3811 unsigned palettebits
= n
<= 2 ? 1 : (n
<= 4 ? 2 : (n
<= 16 ? 4 : 8));
3812 int grey_ok
= !profile
.colored
&& !profile
.alpha
; /*grey without alpha, with potentially low bits*/
3813 if(palette_ok
|| grey_ok
)
3815 if(!palette_ok
|| (grey_ok
&& profile
.greybits
<= palettebits
))
3817 mode_out
->colortype
= LCT_GREY
;
3818 mode_out
->bitdepth
= profile
.greybits
;
3821 unsigned keyval
= profile
.key_r
;
3822 keyval
&= (profile
.greybits
- 1); /*same subgroup of bits repeated, so taking right bits is fine*/
3823 mode_out
->key_defined
= 1;
3824 mode_out
->key_r
= keyval
;
3825 mode_out
->key_g
= keyval
;
3826 mode_out
->key_b
= keyval
;
3831 /*fill in the palette*/
3833 unsigned char* p
= profile
.palette
;
3834 for(i
= 0; i
< profile
.numcolors
; i
++)
3836 error
= lodepng_palette_add(mode_out
, p
[i
* 4 + 0], p
[i
* 4 + 1], p
[i
* 4 + 2], p
[i
* 4 + 3]);
3840 mode_out
->colortype
= LCT_PALETTE
;
3841 mode_out
->bitdepth
= palettebits
;
3844 else /*8-bit per channel*/
3846 mode_out
->bitdepth
= 8;
3849 mode_out
->colortype
= profile
.colored
? LCT_RGBA
: LCT_GREY_ALPHA
;
3853 mode_out
->colortype
= profile
.colored
? LCT_RGB
: LCT_GREY
/*LCT_GREY normally won't occur, already done earlier*/;
3856 mode_out
->key_defined
= 1;
3857 mode_out
->key_r
= profile
.key_r
% 256;
3858 mode_out
->key_g
= profile
.key_g
% 256;
3859 mode_out
->key_b
= profile
.key_b
% 256;
3866 color_profile_cleanup(&profile
);
3868 if(mode_out
->colortype
== LCT_PALETTE
&& mode_in
->palettesize
== mode_out
->palettesize
)
3870 /*In this case keep the palette order of the input, so that the user can choose an optimal one*/
3872 for(i
= 0; i
< mode_in
->palettesize
* 4; i
++)
3874 mode_out
->palette
[i
] = mode_in
->palette
[i
];
3878 if(no_nibbles
&& mode_out
->bitdepth
< 8)
3880 /*palette can keep its small amount of colors, as long as no indices use it*/
3881 mode_out
->bitdepth
= 8;
3887 #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3889 // My own absolute value implementation, since it doesn't seem to be part of
3890 // either GNU-EFI or TianoCore EDK2, but the compiler complains if I use the
3891 // function name "abs()"....
3892 short myabs(short orig
) {
3900 Paeth predicter, used by PNG filter type 4
3901 The parameters are of type short, but should come from unsigned chars, the shorts
3902 are only needed to make the paeth calculation correct.
3904 static unsigned char paethPredictor(short a
, short b
, short c
)
3906 short pa
= myabs(b
- c
);
3907 short pb
= myabs(a
- c
);
3908 short pc
= myabs(a
+ b
- c
- c
);
3910 if(pc
< pa
&& pc
< pb
) return (unsigned char)c
;
3911 else if(pb
< pa
) return (unsigned char)b
;
3912 else return (unsigned char)a
;
3915 /*shared values used by multiple Adam7 related functions*/
3917 static const unsigned ADAM7_IX
[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3918 static const unsigned ADAM7_IY
[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3919 static const unsigned ADAM7_DX
[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3920 static const unsigned ADAM7_DY
[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3923 Outputs various dimensions and positions in the image related to the Adam7 reduced images.
3924 passw: output containing the width of the 7 passes
3925 passh: output containing the height of the 7 passes
3926 filter_passstart: output containing the index of the start and end of each
3927 reduced image with filter bytes
3928 padded_passstart output containing the index of the start and end of each
3929 reduced image when without filter bytes but with padded scanlines
3930 passstart: output containing the index of the start and end of each reduced
3931 image without padding between scanlines, but still padding between the images
3932 w, h: width and height of non-interlaced image
3934 "padded" is only relevant if bpp is less than 8 and a scanline or image does not
3937 static void Adam7_getpassvalues(unsigned passw
[7], unsigned passh
[7], size_t filter_passstart
[8],
3938 size_t padded_passstart
[8], size_t passstart
[8], unsigned w
, unsigned h
, unsigned bpp
)
3940 /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3943 /*calculate width and height in pixels of each pass*/
3944 for(i
= 0; i
< 7; i
++)
3946 passw
[i
] = (w
+ ADAM7_DX
[i
] - ADAM7_IX
[i
] - 1) / ADAM7_DX
[i
];
3947 passh
[i
] = (h
+ ADAM7_DY
[i
] - ADAM7_IY
[i
] - 1) / ADAM7_DY
[i
];
3948 if(passw
[i
] == 0) passh
[i
] = 0;
3949 if(passh
[i
] == 0) passw
[i
] = 0;
3952 filter_passstart
[0] = padded_passstart
[0] = passstart
[0] = 0;
3953 for(i
= 0; i
< 7; i
++)
3955 /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
3956 filter_passstart
[i
+ 1] = filter_passstart
[i
]
3957 + ((passw
[i
] && passh
[i
]) ? passh
[i
] * (1 + (passw
[i
] * bpp
+ 7) / 8) : 0);
3958 /*bits padded if needed to fill full byte at end of each scanline*/
3959 padded_passstart
[i
+ 1] = padded_passstart
[i
] + passh
[i
] * ((passw
[i
] * bpp
+ 7) / 8);
3960 /*only padded at end of reduced image*/
3961 passstart
[i
+ 1] = passstart
[i
] + (passh
[i
] * passw
[i
] * bpp
+ 7) / 8;
3965 #ifdef LODEPNG_COMPILE_DECODER
3967 /* ////////////////////////////////////////////////////////////////////////// */
3968 /* / PNG Decoder / */
3969 /* ////////////////////////////////////////////////////////////////////////// */
3971 /*read the information from the header and store it in the LodePNGInfo. return value is error*/
3972 unsigned lodepng_inspect(unsigned* w
, unsigned* h
, LodePNGState
* state
,
3973 const unsigned char* in
, size_t insize
)
3975 LodePNGInfo
* info
= &state
->info_png
;
3976 if(insize
== 0 || in
== 0)
3978 CERROR_RETURN_ERROR(state
->error
, 48); /*error: the given data is empty*/
3982 CERROR_RETURN_ERROR(state
->error
, 27); /*error: the data length is smaller than the length of a PNG header*/
3985 /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
3986 lodepng_info_cleanup(info
);
3987 lodepng_info_init(info
);
3989 if(in
[0] != 137 || in
[1] != 80 || in
[2] != 78 || in
[3] != 71
3990 || in
[4] != 13 || in
[5] != 10 || in
[6] != 26 || in
[7] != 10)
3992 CERROR_RETURN_ERROR(state
->error
, 28); /*error: the first 8 bytes are not the correct PNG signature*/
3994 if(in
[12] != 'I' || in
[13] != 'H' || in
[14] != 'D' || in
[15] != 'R')
3996 CERROR_RETURN_ERROR(state
->error
, 29); /*error: it doesn't start with a IHDR chunk!*/
3999 /*read the values given in the header*/
4000 *w
= lodepng_read32bitInt(&in
[16]);
4001 *h
= lodepng_read32bitInt(&in
[20]);
4002 info
->color
.bitdepth
= in
[24];
4003 info
->color
.colortype
= (LodePNGColorType
)in
[25];
4004 info
->compression_method
= in
[26];
4005 info
->filter_method
= in
[27];
4006 info
->interlace_method
= in
[28];
4008 if(!state
->decoder
.ignore_crc
)
4010 unsigned CRC
= lodepng_read32bitInt(&in
[29]);
4011 unsigned checksum
= lodepng_crc32(&in
[12], 17);
4014 CERROR_RETURN_ERROR(state
->error
, 57); /*invalid CRC*/
4018 /*error: only compression method 0 is allowed in the specification*/
4019 if(info
->compression_method
!= 0) CERROR_RETURN_ERROR(state
->error
, 32);
4020 /*error: only filter method 0 is allowed in the specification*/
4021 if(info
->filter_method
!= 0) CERROR_RETURN_ERROR(state
->error
, 33);
4022 /*error: only interlace methods 0 and 1 exist in the specification*/
4023 if(info
->interlace_method
> 1) CERROR_RETURN_ERROR(state
->error
, 34);
4025 state
->error
= checkColorValidity(info
->color
.colortype
, info
->color
.bitdepth
);
4026 return state
->error
;
4029 static unsigned unfilterScanline(unsigned char* recon
, const unsigned char* scanline
, const unsigned char* precon
,
4030 size_t bytewidth
, unsigned char filterType
, size_t length
)
4033 For PNG filter method 0
4034 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
4035 the filter works byte per byte (bytewidth = 1)
4036 precon is the previous unfiltered scanline, recon the result, scanline the current one
4037 the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
4038 recon and scanline MAY be the same memory address! precon must be disjoint.
4045 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
];
4048 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
];
4049 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + recon
[i
- bytewidth
];
4054 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
] + precon
[i
];
4058 for(i
= 0; i
< length
; i
++) recon
[i
] = scanline
[i
];
4064 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
] + precon
[i
] / 2;
4065 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + ((recon
[i
- bytewidth
] + precon
[i
]) / 2);
4069 for(i
= 0; i
< bytewidth
; i
++) recon
[i
] = scanline
[i
];
4070 for(i
= bytewidth
; i
< length
; i
++) recon
[i
] = scanline
[i
] + recon
[i
- bytewidth
] / 2;
4076 for(i
= 0; i
< bytewidth
; i
++)
4078 recon
[i
] = (scanline
[i
] + precon
[i
]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
4080 for(i
= bytewidth
; i
< length
; i
++)
4082 recon
[i
] = (scanline
[i
] + paethPredictor(recon
[i
- bytewidth
], precon
[i
], precon
[i
- bytewidth
]));
4087 for(i
= 0; i
< bytewidth
; i
++)
4089 recon
[i
] = scanline
[i
];
4091 for(i
= bytewidth
; i
< length
; i
++)
4093 /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
4094 recon
[i
] = (scanline
[i
] + recon
[i
- bytewidth
]);
4098 default: return 36; /*error: unexisting filter type given*/
4103 static unsigned unfilter(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
4106 For PNG filter method 0
4107 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
4108 out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
4109 w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
4110 in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
4114 unsigned char* prevline
= 0;
4116 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
4117 size_t bytewidth
= (bpp
+ 7) / 8;
4118 size_t linebytes
= (w
* bpp
+ 7) / 8;
4120 for(y
= 0; y
< h
; y
++)
4122 size_t outindex
= linebytes
* y
;
4123 size_t inindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
4124 unsigned char filterType
= in
[inindex
];
4126 CERROR_TRY_RETURN(unfilterScanline(&out
[outindex
], &in
[inindex
+ 1], prevline
, bytewidth
, filterType
, linebytes
));
4128 prevline
= &out
[outindex
];
4135 in: Adam7 interlaced image, with no padding bits between scanlines, but between
4136 reduced images so that each reduced image starts at a byte.
4137 out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4139 out has the following size in bits: w * h * bpp.
4140 in is possibly bigger due to padding bits between reduced images.
4141 out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4142 (because that's likely a little bit faster)
4143 NOTE: comments about padding bits are only relevant if bpp < 8
4145 static void Adam7_deinterlace(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
4147 unsigned passw
[7], passh
[7];
4148 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
4151 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
4155 for(i
= 0; i
< 7; i
++)
4158 size_t bytewidth
= bpp
/ 8;
4159 for(y
= 0; y
< passh
[i
]; y
++)
4160 for(x
= 0; x
< passw
[i
]; x
++)
4162 size_t pixelinstart
= passstart
[i
] + (y
* passw
[i
] + x
) * bytewidth
;
4163 size_t pixeloutstart
= ((ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * w
+ ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bytewidth
;
4164 for(b
= 0; b
< bytewidth
; b
++)
4166 out
[pixeloutstart
+ b
] = in
[pixelinstart
+ b
];
4171 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4173 for(i
= 0; i
< 7; i
++)
4176 unsigned ilinebits
= bpp
* passw
[i
];
4177 unsigned olinebits
= bpp
* w
;
4178 size_t obp
, ibp
; /*bit pointers (for out and in buffer)*/
4179 for(y
= 0; y
< passh
[i
]; y
++)
4180 for(x
= 0; x
< passw
[i
]; x
++)
4182 ibp
= (8 * passstart
[i
]) + (y
* ilinebits
+ x
* bpp
);
4183 obp
= (ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * olinebits
+ (ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bpp
;
4184 for(b
= 0; b
< bpp
; b
++)
4186 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
4187 /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4188 setBitOfReversedStream0(&obp
, out
, bit
);
4195 static void removePaddingBits(unsigned char* out
, const unsigned char* in
,
4196 size_t olinebits
, size_t ilinebits
, unsigned h
)
4199 After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4200 to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4201 for the Adam7 code, the color convert code and the output to the user.
4202 in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4203 have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4204 also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4205 only useful if (ilinebits - olinebits) is a value in the range 1..7
4208 size_t diff
= ilinebits
- olinebits
;
4209 size_t ibp
= 0, obp
= 0; /*input and output bit pointers*/
4210 for(y
= 0; y
< h
; y
++)
4213 for(x
= 0; x
< olinebits
; x
++)
4215 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
4216 setBitOfReversedStream(&obp
, out
, bit
);
4222 /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4223 the IDAT chunks (with filter index bytes and possible padding bits)
4224 return value is error*/
4225 static unsigned postProcessScanlines(unsigned char* out
, unsigned char* in
,
4226 unsigned w
, unsigned h
, const LodePNGInfo
* info_png
)
4229 This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4231 *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4232 *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4233 NOTE: the in buffer will be overwritten with intermediate data!
4235 unsigned bpp
= lodepng_get_bpp(&info_png
->color
);
4236 if(bpp
== 0) return 31; /*error: invalid colortype*/
4238 if(info_png
->interlace_method
== 0)
4240 if(bpp
< 8 && w
* bpp
!= ((w
* bpp
+ 7) / 8) * 8)
4242 CERROR_TRY_RETURN(unfilter(in
, in
, w
, h
, bpp
));
4243 removePaddingBits(out
, in
, w
* bpp
, ((w
* bpp
+ 7) / 8) * 8, h
);
4245 /*we can immediatly filter into the out buffer, no other steps needed*/
4246 else CERROR_TRY_RETURN(unfilter(out
, in
, w
, h
, bpp
));
4248 else /*interlace_method is 1 (Adam7)*/
4250 unsigned passw
[7], passh
[7]; size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
4253 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
4255 for(i
= 0; i
< 7; i
++)
4257 CERROR_TRY_RETURN(unfilter(&in
[padded_passstart
[i
]], &in
[filter_passstart
[i
]], passw
[i
], passh
[i
], bpp
));
4258 /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4259 move bytes instead of bits or move not at all*/
4262 /*remove padding bits in scanlines; after this there still may be padding
4263 bits between the different reduced images: each reduced image still starts nicely at a byte*/
4264 removePaddingBits(&in
[passstart
[i
]], &in
[padded_passstart
[i
]], passw
[i
] * bpp
,
4265 ((passw
[i
] * bpp
+ 7) / 8) * 8, passh
[i
]);
4269 Adam7_deinterlace(out
, in
, w
, h
, bpp
);
4275 static unsigned readChunk_PLTE(LodePNGColorMode
* color
, const unsigned char* data
, size_t chunkLength
)
4277 unsigned pos
= 0, i
;
4278 if(color
->palette
) myfree(color
->palette
);
4279 color
->palettesize
= chunkLength
/ 3;
4280 color
->palette
= (unsigned char*)mymalloc(4 * color
->palettesize
);
4281 if(!color
->palette
&& color
->palettesize
)
4283 color
->palettesize
= 0;
4284 return 83; /*alloc fail*/
4286 if(color
->palettesize
> 256) return 38; /*error: palette too big*/
4288 for(i
= 0; i
< color
->palettesize
; i
++)
4290 color
->palette
[4 * i
+ 0] = data
[pos
++]; /*R*/
4291 color
->palette
[4 * i
+ 1] = data
[pos
++]; /*G*/
4292 color
->palette
[4 * i
+ 2] = data
[pos
++]; /*B*/
4293 color
->palette
[4 * i
+ 3] = 255; /*alpha*/
4299 static unsigned readChunk_tRNS(LodePNGColorMode
* color
, const unsigned char* data
, size_t chunkLength
)
4302 if(color
->colortype
== LCT_PALETTE
)
4304 /*error: more alpha values given than there are palette entries*/
4305 if(chunkLength
> color
->palettesize
) return 38;
4307 for(i
= 0; i
< chunkLength
; i
++) color
->palette
[4 * i
+ 3] = data
[i
];
4309 else if(color
->colortype
== LCT_GREY
)
4311 /*error: this chunk must be 2 bytes for greyscale image*/
4312 if(chunkLength
!= 2) return 30;
4314 color
->key_defined
= 1;
4315 color
->key_r
= color
->key_g
= color
->key_b
= 256 * data
[0] + data
[1];
4317 else if(color
->colortype
== LCT_RGB
)
4319 /*error: this chunk must be 6 bytes for RGB image*/
4320 if(chunkLength
!= 6) return 41;
4322 color
->key_defined
= 1;
4323 color
->key_r
= 256 * data
[0] + data
[1];
4324 color
->key_g
= 256 * data
[2] + data
[3];
4325 color
->key_b
= 256 * data
[4] + data
[5];
4327 else return 42; /*error: tRNS chunk not allowed for other color models*/
4333 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4334 /*background color chunk (bKGD)*/
4335 static unsigned readChunk_bKGD(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4337 if(info
->color
.colortype
== LCT_PALETTE
)
4339 /*error: this chunk must be 1 byte for indexed color image*/
4340 if(chunkLength
!= 1) return 43;
4342 info
->background_defined
= 1;
4343 info
->background_r
= info
->background_g
= info
->background_b
= data
[0];
4345 else if(info
->color
.colortype
== LCT_GREY
|| info
->color
.colortype
== LCT_GREY_ALPHA
)
4347 /*error: this chunk must be 2 bytes for greyscale image*/
4348 if(chunkLength
!= 2) return 44;
4350 info
->background_defined
= 1;
4351 info
->background_r
= info
->background_g
= info
->background_b
4352 = 256 * data
[0] + data
[1];
4354 else if(info
->color
.colortype
== LCT_RGB
|| info
->color
.colortype
== LCT_RGBA
)
4356 /*error: this chunk must be 6 bytes for greyscale image*/
4357 if(chunkLength
!= 6) return 45;
4359 info
->background_defined
= 1;
4360 info
->background_r
= 256 * data
[0] + data
[1];
4361 info
->background_g
= 256 * data
[2] + data
[3];
4362 info
->background_b
= 256 * data
[4] + data
[5];
4368 /*text chunk (tEXt)*/
4369 static unsigned readChunk_tEXt(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4372 char *key
= 0, *str
= 0;
4375 while(!error
) /*not really a while loop, only used to break on error*/
4377 unsigned length
, string2_begin
;
4380 while(length
< chunkLength
&& data
[length
] != 0) length
++;
4381 /*even though it's not allowed by the standard, no error is thrown if
4382 there's no null termination char, if the text is empty*/
4383 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4385 key
= (char*)mymalloc(length
+ 1);
4386 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4389 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4391 string2_begin
= length
+ 1; /*skip keyword null terminator*/
4393 length
= chunkLength
< string2_begin
? 0 : chunkLength
- string2_begin
;
4394 str
= (char*)mymalloc(length
+ 1);
4395 if(!str
) CERROR_BREAK(error
, 83); /*alloc fail*/
4398 for(i
= 0; i
< length
; i
++) str
[i
] = data
[string2_begin
+ i
];
4400 error
= lodepng_add_text(info
, key
, str
);
4411 /*compressed text chunk (zTXt)*/
4412 static unsigned readChunk_zTXt(LodePNGInfo
* info
, const LodePNGDecompressSettings
* zlibsettings
,
4413 const unsigned char* data
, size_t chunkLength
)
4418 unsigned length
, string2_begin
;
4422 ucvector_init(&decoded
);
4424 while(!error
) /*not really a while loop, only used to break on error*/
4426 for(length
= 0; length
< chunkLength
&& data
[length
] != 0; length
++) ;
4427 if(length
+ 2 >= chunkLength
) CERROR_BREAK(error
, 75); /*no null termination, corrupt?*/
4428 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4430 key
= (char*)mymalloc(length
+ 1);
4431 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4434 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4436 if(data
[length
+ 1] != 0) CERROR_BREAK(error
, 72); /*the 0 byte indicating compression must be 0*/
4438 string2_begin
= length
+ 2;
4439 if(string2_begin
> chunkLength
) CERROR_BREAK(error
, 75); /*no null termination, corrupt?*/
4441 length
= chunkLength
- string2_begin
;
4442 /*will fail if zlib error, e.g. if length is too small*/
4443 error
= zlib_decompress(&decoded
.data
, &decoded
.size
,
4444 (unsigned char*)(&data
[string2_begin
]),
4445 length
, zlibsettings
);
4447 ucvector_push_back(&decoded
, 0);
4449 error
= lodepng_add_text(info
, key
, (char*)decoded
.data
);
4455 ucvector_cleanup(&decoded
);
4460 /*international text chunk (iTXt)*/
4461 static unsigned readChunk_iTXt(LodePNGInfo
* info
, const LodePNGDecompressSettings
* zlibsettings
,
4462 const unsigned char* data
, size_t chunkLength
)
4467 unsigned length
, begin
, compressed
;
4468 char *key
= 0, *langtag
= 0, *transkey
= 0;
4470 ucvector_init(&decoded
);
4472 while(!error
) /*not really a while loop, only used to break on error*/
4474 /*Quick check if the chunk length isn't too small. Even without check
4475 it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4476 if(chunkLength
< 5) CERROR_BREAK(error
, 30); /*iTXt chunk too short*/
4479 for(length
= 0; length
< chunkLength
&& data
[length
] != 0; length
++) ;
4480 if(length
+ 3 >= chunkLength
) CERROR_BREAK(error
, 75); /*no null termination char, corrupt?*/
4481 if(length
< 1 || length
> 79) CERROR_BREAK(error
, 89); /*keyword too short or long*/
4483 key
= (char*)mymalloc(length
+ 1);
4484 if(!key
) CERROR_BREAK(error
, 83); /*alloc fail*/
4487 for(i
= 0; i
< length
; i
++) key
[i
] = data
[i
];
4489 /*read the compression method*/
4490 compressed
= data
[length
+ 1];
4491 if(data
[length
+ 2] != 0) CERROR_BREAK(error
, 72); /*the 0 byte indicating compression must be 0*/
4493 /*even though it's not allowed by the standard, no error is thrown if
4494 there's no null termination char, if the text is empty for the next 3 texts*/
4496 /*read the langtag*/
4499 for(i
= begin
; i
< chunkLength
&& data
[i
] != 0; i
++) length
++;
4501 langtag
= (char*)mymalloc(length
+ 1);
4502 if(!langtag
) CERROR_BREAK(error
, 83); /*alloc fail*/
4504 langtag
[length
] = 0;
4505 for(i
= 0; i
< length
; i
++) langtag
[i
] = data
[begin
+ i
];
4507 /*read the transkey*/
4508 begin
+= length
+ 1;
4510 for(i
= begin
; i
< chunkLength
&& data
[i
] != 0; i
++) length
++;
4512 transkey
= (char*)mymalloc(length
+ 1);
4513 if(!transkey
) CERROR_BREAK(error
, 83); /*alloc fail*/
4515 transkey
[length
] = 0;
4516 for(i
= 0; i
< length
; i
++) transkey
[i
] = data
[begin
+ i
];
4518 /*read the actual text*/
4519 begin
+= length
+ 1;
4521 length
= chunkLength
< begin
? 0 : chunkLength
- begin
;
4525 /*will fail if zlib error, e.g. if length is too small*/
4526 error
= zlib_decompress(&decoded
.data
, &decoded
.size
,
4527 (unsigned char*)(&data
[begin
]),
4528 length
, zlibsettings
);
4530 if(decoded
.allocsize
< decoded
.size
) decoded
.allocsize
= decoded
.size
;
4531 ucvector_push_back(&decoded
, 0);
4535 if(!ucvector_resize(&decoded
, length
+ 1)) CERROR_BREAK(error
, 83 /*alloc fail*/);
4537 decoded
.data
[length
] = 0;
4538 for(i
= 0; i
< length
; i
++) decoded
.data
[i
] = data
[begin
+ i
];
4541 error
= lodepng_add_itext(info
, key
, langtag
, transkey
, (char*)decoded
.data
);
4549 ucvector_cleanup(&decoded
);
4554 static unsigned readChunk_tIME(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4556 if(chunkLength
!= 7) return 73; /*invalid tIME chunk size*/
4558 info
->time_defined
= 1;
4559 info
->time
.year
= 256 * data
[0] + data
[+ 1];
4560 info
->time
.month
= data
[2];
4561 info
->time
.day
= data
[3];
4562 info
->time
.hour
= data
[4];
4563 info
->time
.minute
= data
[5];
4564 info
->time
.second
= data
[6];
4569 static unsigned readChunk_pHYs(LodePNGInfo
* info
, const unsigned char* data
, size_t chunkLength
)
4571 if(chunkLength
!= 9) return 74; /*invalid pHYs chunk size*/
4573 info
->phys_defined
= 1;
4574 info
->phys_x
= 16777216 * data
[0] + 65536 * data
[1] + 256 * data
[2] + data
[3];
4575 info
->phys_y
= 16777216 * data
[4] + 65536 * data
[5] + 256 * data
[6] + data
[7];
4576 info
->phys_unit
= data
[8];
4580 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4582 /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4583 static void decodeGeneric(unsigned char** out
, unsigned* w
, unsigned* h
,
4584 LodePNGState
* state
,
4585 const unsigned char* in
, size_t insize
)
4587 unsigned char IEND
= 0;
4588 const unsigned char* chunk
;
4590 ucvector idat
; /*the data from idat chunks*/
4592 /*for unknown chunk order*/
4593 unsigned unknown
= 0;
4594 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4595 unsigned critical_pos
= 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4596 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4598 /*provide some proper output values if error will happen*/
4601 state
->error
= lodepng_inspect(w
, h
, state
, in
, insize
); /*reads header and resets other parameters in state->info_png*/
4602 if(state
->error
) return;
4604 ucvector_init(&idat
);
4605 chunk
= &in
[33]; /*first byte of the first chunk after the header*/
4607 /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4608 IDAT data is put at the start of the in buffer*/
4609 while(!IEND
&& !state
->error
)
4611 unsigned chunkLength
;
4612 const unsigned char* data
; /*the data in the chunk*/
4614 /*error: size of the in buffer too small to contain next chunk*/
4615 if((size_t)((chunk
- in
) + 12) > insize
|| chunk
< in
) CERROR_BREAK(state
->error
, 30);
4617 /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4618 chunkLength
= lodepng_chunk_length(chunk
);
4619 /*error: chunk length larger than the max PNG chunk size*/
4620 if(chunkLength
> 2147483647) CERROR_BREAK(state
->error
, 63);
4622 if((size_t)((chunk
- in
) + chunkLength
+ 12) > insize
|| (chunk
+ chunkLength
+ 12) < in
)
4624 CERROR_BREAK(state
->error
, 64); /*error: size of the in buffer too small to contain next chunk*/
4627 data
= lodepng_chunk_data_const(chunk
);
4629 /*IDAT chunk, containing compressed image data*/
4630 if(lodepng_chunk_type_equals(chunk
, "IDAT"))
4632 size_t oldsize
= idat
.size
;
4633 if(!ucvector_resize(&idat
, oldsize
+ chunkLength
)) CERROR_BREAK(state
->error
, 83 /*alloc fail*/);
4634 for(i
= 0; i
< chunkLength
; i
++) idat
.data
[oldsize
+ i
] = data
[i
];
4635 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4637 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4640 else if(lodepng_chunk_type_equals(chunk
, "IEND"))
4644 /*palette chunk (PLTE)*/
4645 else if(lodepng_chunk_type_equals(chunk
, "PLTE"))
4647 state
->error
= readChunk_PLTE(&state
->info_png
.color
, data
, chunkLength
);
4648 if(state
->error
) break;
4649 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4651 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4653 /*palette transparency chunk (tRNS)*/
4654 else if(lodepng_chunk_type_equals(chunk
, "tRNS"))
4656 state
->error
= readChunk_tRNS(&state
->info_png
.color
, data
, chunkLength
);
4657 if(state
->error
) break;
4659 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4660 /*background color chunk (bKGD)*/
4661 else if(lodepng_chunk_type_equals(chunk
, "bKGD"))
4663 state
->error
= readChunk_bKGD(&state
->info_png
, data
, chunkLength
);
4664 if(state
->error
) break;
4666 /*text chunk (tEXt)*/
4667 else if(lodepng_chunk_type_equals(chunk
, "tEXt"))
4669 if(state
->decoder
.read_text_chunks
)
4671 state
->error
= readChunk_tEXt(&state
->info_png
, data
, chunkLength
);
4672 if(state
->error
) break;
4675 /*compressed text chunk (zTXt)*/
4676 else if(lodepng_chunk_type_equals(chunk
, "zTXt"))
4678 if(state
->decoder
.read_text_chunks
)
4680 state
->error
= readChunk_zTXt(&state
->info_png
, &state
->decoder
.zlibsettings
, data
, chunkLength
);
4681 if(state
->error
) break;
4684 /*international text chunk (iTXt)*/
4685 else if(lodepng_chunk_type_equals(chunk
, "iTXt"))
4687 if(state
->decoder
.read_text_chunks
)
4689 state
->error
= readChunk_iTXt(&state
->info_png
, &state
->decoder
.zlibsettings
, data
, chunkLength
);
4690 if(state
->error
) break;
4693 else if(lodepng_chunk_type_equals(chunk
, "tIME"))
4695 state
->error
= readChunk_tIME(&state
->info_png
, data
, chunkLength
);
4696 if(state
->error
) break;
4698 else if(lodepng_chunk_type_equals(chunk
, "pHYs"))
4700 state
->error
= readChunk_pHYs(&state
->info_png
, data
, chunkLength
);
4701 if(state
->error
) break;
4703 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4704 else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4706 /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4707 if(!lodepng_chunk_ancillary(chunk
)) CERROR_BREAK(state
->error
, 69);
4710 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4711 if(state
->decoder
.remember_unknown_chunks
)
4713 state
->error
= lodepng_chunk_append(&state
->info_png
.unknown_chunks_data
[critical_pos
- 1],
4714 &state
->info_png
.unknown_chunks_size
[critical_pos
- 1], chunk
);
4715 if(state
->error
) break;
4717 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4720 if(!state
->decoder
.ignore_crc
&& !unknown
) /*check CRC if wanted, only on known chunk types*/
4722 if(lodepng_chunk_check_crc(chunk
)) CERROR_BREAK(state
->error
, 57); /*invalid CRC*/
4725 if(!IEND
) chunk
= lodepng_chunk_next_const(chunk
);
4731 ucvector_init(&scanlines
);
4733 /*maximum final image length is already reserved in the vector's length - this is not really necessary*/
4734 if(!ucvector_resize(&scanlines
, lodepng_get_raw_size(*w
, *h
, &state
->info_png
.color
) + *h
))
4736 state
->error
= 83; /*alloc fail*/
4740 /*decompress with the Zlib decompressor*/
4741 state
->error
= zlib_decompress(&scanlines
.data
, &scanlines
.size
, idat
.data
,
4742 idat
.size
, &state
->decoder
.zlibsettings
);
4748 ucvector_init(&outv
);
4749 if(!ucvector_resizev(&outv
,
4750 lodepng_get_raw_size(*w
, *h
, &state
->info_png
.color
), 0)) state
->error
= 83; /*alloc fail*/
4751 if(!state
->error
) state
->error
= postProcessScanlines(outv
.data
, scanlines
.data
, *w
, *h
, &state
->info_png
);
4754 ucvector_cleanup(&scanlines
);
4757 ucvector_cleanup(&idat
);
4760 unsigned lodepng_decode(unsigned char** out
, unsigned* w
, unsigned* h
,
4761 LodePNGState
* state
,
4762 const unsigned char* in
, size_t insize
)
4765 decodeGeneric(out
, w
, h
, state
, in
, insize
);
4766 if(state
->error
) return state
->error
;
4767 if(!state
->decoder
.color_convert
|| lodepng_color_mode_equal(&state
->info_raw
, &state
->info_png
.color
))
4769 /*same color type, no copying or converting of data needed*/
4770 /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4771 the raw image has to the end user*/
4772 if(!state
->decoder
.color_convert
)
4774 state
->error
= lodepng_color_mode_copy(&state
->info_raw
, &state
->info_png
.color
);
4775 if(state
->error
) return state
->error
;
4780 /*color conversion needed; sort of copy of the data*/
4781 unsigned char* data
= *out
;
4784 /*TODO: check if this works according to the statement in the documentation: "The converter can convert
4785 from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
4786 if(!(state
->info_raw
.colortype
== LCT_RGB
|| state
->info_raw
.colortype
== LCT_RGBA
)
4787 && !(state
->info_raw
.bitdepth
== 8))
4789 return 56; /*unsupported color mode conversion*/
4792 outsize
= lodepng_get_raw_size(*w
, *h
, &state
->info_raw
);
4793 *out
= (unsigned char*)mymalloc(outsize
);
4796 state
->error
= 83; /*alloc fail*/
4798 else state
->error
= lodepng_convert(*out
, data
, &state
->info_raw
, &state
->info_png
.color
, *w
, *h
);
4801 return state
->error
;
4804 unsigned lodepng_decode_memory(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
,
4805 size_t insize
, LodePNGColorType colortype
, unsigned bitdepth
)
4809 lodepng_state_init(&state
);
4810 state
.info_raw
.colortype
= colortype
;
4811 state
.info_raw
.bitdepth
= bitdepth
;
4812 error
= lodepng_decode(out
, w
, h
, &state
, in
, insize
);
4813 lodepng_state_cleanup(&state
);
4817 unsigned lodepng_decode32(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
, size_t insize
)
4819 return lodepng_decode_memory(out
, w
, h
, in
, insize
, LCT_RGBA
, 8);
4822 unsigned lodepng_decode24(unsigned char** out
, unsigned* w
, unsigned* h
, const unsigned char* in
, size_t insize
)
4824 return lodepng_decode_memory(out
, w
, h
, in
, insize
, LCT_RGB
, 8);
4827 #ifdef LODEPNG_COMPILE_DISK
4828 unsigned lodepng_decode_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
,
4829 LodePNGColorType colortype
, unsigned bitdepth
)
4831 unsigned char* buffer
;
4834 error
= lodepng_load_file(&buffer
, &buffersize
, filename
);
4835 if(!error
) error
= lodepng_decode_memory(out
, w
, h
, buffer
, buffersize
, colortype
, bitdepth
);
4840 unsigned lodepng_decode32_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
)
4842 return lodepng_decode_file(out
, w
, h
, filename
, LCT_RGBA
, 8);
4845 unsigned lodepng_decode24_file(unsigned char** out
, unsigned* w
, unsigned* h
, const char* filename
)
4847 return lodepng_decode_file(out
, w
, h
, filename
, LCT_RGB
, 8);
4849 #endif /*LODEPNG_COMPILE_DISK*/
4851 void lodepng_decoder_settings_init(LodePNGDecoderSettings
* settings
)
4853 settings
->color_convert
= 1;
4854 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4855 settings
->read_text_chunks
= 1;
4856 settings
->remember_unknown_chunks
= 0;
4857 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4858 settings
->ignore_crc
= 0;
4859 lodepng_decompress_settings_init(&settings
->zlibsettings
);
4862 #endif /*LODEPNG_COMPILE_DECODER*/
4864 #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4866 void lodepng_state_init(LodePNGState
* state
)
4868 #ifdef LODEPNG_COMPILE_DECODER
4869 lodepng_decoder_settings_init(&state
->decoder
);
4870 #endif /*LODEPNG_COMPILE_DECODER*/
4871 #ifdef LODEPNG_COMPILE_ENCODER
4872 lodepng_encoder_settings_init(&state
->encoder
);
4873 #endif /*LODEPNG_COMPILE_ENCODER*/
4874 lodepng_color_mode_init(&state
->info_raw
);
4875 lodepng_info_init(&state
->info_png
);
4879 void lodepng_state_cleanup(LodePNGState
* state
)
4881 lodepng_color_mode_cleanup(&state
->info_raw
);
4882 lodepng_info_cleanup(&state
->info_png
);
4885 void lodepng_state_copy(LodePNGState
* dest
, const LodePNGState
* source
)
4887 lodepng_state_cleanup(dest
);
4889 lodepng_color_mode_init(&dest
->info_raw
);
4890 lodepng_info_init(&dest
->info_png
);
4891 dest
->error
= lodepng_color_mode_copy(&dest
->info_raw
, &source
->info_raw
); if(dest
->error
) return;
4892 dest
->error
= lodepng_info_copy(&dest
->info_png
, &source
->info_png
); if(dest
->error
) return;
4895 #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4897 #ifdef LODEPNG_COMPILE_ENCODER
4899 /* ////////////////////////////////////////////////////////////////////////// */
4900 /* / PNG Encoder / */
4901 /* ////////////////////////////////////////////////////////////////////////// */
4903 /*chunkName must be string of 4 characters*/
4904 static unsigned addChunk(ucvector
* out
, const char* chunkName
, const unsigned char* data
, size_t length
)
4906 CERROR_TRY_RETURN(lodepng_chunk_create(&out
->data
, &out
->size
, (unsigned)length
, chunkName
, data
));
4907 out
->allocsize
= out
->size
; /*fix the allocsize again*/
4911 static void writeSignature(ucvector
* out
)
4913 /*8 bytes PNG signature, aka the magic bytes*/
4914 ucvector_push_back(out
, 137);
4915 ucvector_push_back(out
, 80);
4916 ucvector_push_back(out
, 78);
4917 ucvector_push_back(out
, 71);
4918 ucvector_push_back(out
, 13);
4919 ucvector_push_back(out
, 10);
4920 ucvector_push_back(out
, 26);
4921 ucvector_push_back(out
, 10);
4924 static unsigned addChunk_IHDR(ucvector
* out
, unsigned w
, unsigned h
,
4925 LodePNGColorType colortype
, unsigned bitdepth
, unsigned interlace_method
)
4929 ucvector_init(&header
);
4931 lodepng_add32bitInt(&header
, w
); /*width*/
4932 lodepng_add32bitInt(&header
, h
); /*height*/
4933 ucvector_push_back(&header
, (unsigned char)bitdepth
); /*bit depth*/
4934 ucvector_push_back(&header
, (unsigned char)colortype
); /*color type*/
4935 ucvector_push_back(&header
, 0); /*compression method*/
4936 ucvector_push_back(&header
, 0); /*filter method*/
4937 ucvector_push_back(&header
, interlace_method
); /*interlace method*/
4939 error
= addChunk(out
, "IHDR", header
.data
, header
.size
);
4940 ucvector_cleanup(&header
);
4945 static unsigned addChunk_PLTE(ucvector
* out
, const LodePNGColorMode
* info
)
4950 ucvector_init(&PLTE
);
4951 for(i
= 0; i
< info
->palettesize
* 4; i
++)
4953 /*add all channels except alpha channel*/
4954 if(i
% 4 != 3) ucvector_push_back(&PLTE
, info
->palette
[i
]);
4956 error
= addChunk(out
, "PLTE", PLTE
.data
, PLTE
.size
);
4957 ucvector_cleanup(&PLTE
);
4962 static unsigned addChunk_tRNS(ucvector
* out
, const LodePNGColorMode
* info
)
4967 ucvector_init(&tRNS
);
4968 if(info
->colortype
== LCT_PALETTE
)
4970 size_t amount
= info
->palettesize
;
4971 /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
4972 for(i
= info
->palettesize
; i
> 0; i
--)
4974 if(info
->palette
[4 * (i
- 1) + 3] == 255) amount
--;
4977 /*add only alpha channel*/
4978 for(i
= 0; i
< amount
; i
++) ucvector_push_back(&tRNS
, info
->palette
[4 * i
+ 3]);
4980 else if(info
->colortype
== LCT_GREY
)
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));
4988 else if(info
->colortype
== LCT_RGB
)
4990 if(info
->key_defined
)
4992 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
/ 256));
4993 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_r
% 256));
4994 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_g
/ 256));
4995 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_g
% 256));
4996 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_b
/ 256));
4997 ucvector_push_back(&tRNS
, (unsigned char)(info
->key_b
% 256));
5001 error
= addChunk(out
, "tRNS", tRNS
.data
, tRNS
.size
);
5002 ucvector_cleanup(&tRNS
);
5007 static unsigned addChunk_IDAT(ucvector
* out
, const unsigned char* data
, size_t datasize
,
5008 LodePNGCompressSettings
* zlibsettings
)
5013 /*compress with the Zlib compressor*/
5014 ucvector_init(&zlibdata
);
5015 error
= zlib_compress(&zlibdata
.data
, &zlibdata
.size
, data
, datasize
, zlibsettings
);
5016 if(!error
) error
= addChunk(out
, "IDAT", zlibdata
.data
, zlibdata
.size
);
5017 ucvector_cleanup(&zlibdata
);
5022 static unsigned addChunk_IEND(ucvector
* out
)
5025 error
= addChunk(out
, "IEND", 0, 0);
5029 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5031 static unsigned addChunk_tEXt(ucvector
* out
, const char* keyword
, const char* textstring
)
5036 ucvector_init(&text
);
5037 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&text
, (unsigned char)keyword
[i
]);
5038 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5039 ucvector_push_back(&text
, 0); /*0 termination char*/
5040 for(i
= 0; textstring
[i
] != 0; i
++) ucvector_push_back(&text
, (unsigned char)textstring
[i
]);
5041 error
= addChunk(out
, "tEXt", text
.data
, text
.size
);
5042 ucvector_cleanup(&text
);
5047 static unsigned addChunk_zTXt(ucvector
* out
, const char* keyword
, const char* textstring
,
5048 LodePNGCompressSettings
* zlibsettings
)
5051 ucvector data
, compressed
;
5052 size_t i
, textsize
= MyStrlen(textstring
);
5054 ucvector_init(&data
);
5055 ucvector_init(&compressed
);
5056 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)keyword
[i
]);
5057 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5058 ucvector_push_back(&data
, 0); /*0 termination char*/
5059 ucvector_push_back(&data
, 0); /*compression method: 0*/
5061 error
= zlib_compress(&compressed
.data
, &compressed
.size
,
5062 (unsigned char*)textstring
, textsize
, zlibsettings
);
5065 for(i
= 0; i
< compressed
.size
; i
++) ucvector_push_back(&data
, compressed
.data
[i
]);
5066 error
= addChunk(out
, "zTXt", data
.data
, data
.size
);
5069 ucvector_cleanup(&compressed
);
5070 ucvector_cleanup(&data
);
5074 static unsigned addChunk_iTXt(ucvector
* out
, unsigned compressed
, const char* keyword
, const char* langtag
,
5075 const char* transkey
, const char* textstring
, LodePNGCompressSettings
* zlibsettings
)
5079 size_t i
, textsize
= MyStrlen(textstring
);
5081 ucvector_init(&data
);
5083 for(i
= 0; keyword
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)keyword
[i
]);
5084 if(i
< 1 || i
> 79) return 89; /*error: invalid keyword size*/
5085 ucvector_push_back(&data
, 0); /*null termination char*/
5086 ucvector_push_back(&data
, compressed
? 1 : 0); /*compression flag*/
5087 ucvector_push_back(&data
, 0); /*compression method*/
5088 for(i
= 0; langtag
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)langtag
[i
]);
5089 ucvector_push_back(&data
, 0); /*null termination char*/
5090 for(i
= 0; transkey
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)transkey
[i
]);
5091 ucvector_push_back(&data
, 0); /*null termination char*/
5095 ucvector compressed_data
;
5096 ucvector_init(&compressed_data
);
5097 error
= zlib_compress(&compressed_data
.data
, &compressed_data
.size
,
5098 (unsigned char*)textstring
, textsize
, zlibsettings
);
5101 for(i
= 0; i
< compressed_data
.size
; i
++) ucvector_push_back(&data
, compressed_data
.data
[i
]);
5103 ucvector_cleanup(&compressed_data
);
5105 else /*not compressed*/
5107 for(i
= 0; textstring
[i
] != 0; i
++) ucvector_push_back(&data
, (unsigned char)textstring
[i
]);
5110 if(!error
) error
= addChunk(out
, "iTXt", data
.data
, data
.size
);
5111 ucvector_cleanup(&data
);
5115 static unsigned addChunk_bKGD(ucvector
* out
, const LodePNGInfo
* info
)
5119 ucvector_init(&bKGD
);
5120 if(info
->color
.colortype
== LCT_GREY
|| info
->color
.colortype
== LCT_GREY_ALPHA
)
5122 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
/ 256));
5123 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256));
5125 else if(info
->color
.colortype
== LCT_RGB
|| info
->color
.colortype
== LCT_RGBA
)
5127 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
/ 256));
5128 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256));
5129 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_g
/ 256));
5130 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_g
% 256));
5131 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_b
/ 256));
5132 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_b
% 256));
5134 else if(info
->color
.colortype
== LCT_PALETTE
)
5136 ucvector_push_back(&bKGD
, (unsigned char)(info
->background_r
% 256)); /*palette index*/
5139 error
= addChunk(out
, "bKGD", bKGD
.data
, bKGD
.size
);
5140 ucvector_cleanup(&bKGD
);
5145 static unsigned addChunk_tIME(ucvector
* out
, const LodePNGTime
* time
)
5148 unsigned char* data
= (unsigned char*)mymalloc(7);
5149 if(!data
) return 83; /*alloc fail*/
5150 data
[0] = (unsigned char)(time
->year
/ 256);
5151 data
[1] = (unsigned char)(time
->year
% 256);
5152 data
[2] = time
->month
;
5153 data
[3] = time
->day
;
5154 data
[4] = time
->hour
;
5155 data
[5] = time
->minute
;
5156 data
[6] = time
->second
;
5157 error
= addChunk(out
, "tIME", data
, 7);
5162 static unsigned addChunk_pHYs(ucvector
* out
, const LodePNGInfo
* info
)
5166 ucvector_init(&data
);
5168 lodepng_add32bitInt(&data
, info
->phys_x
);
5169 lodepng_add32bitInt(&data
, info
->phys_y
);
5170 ucvector_push_back(&data
, info
->phys_unit
);
5172 error
= addChunk(out
, "pHYs", data
.data
, data
.size
);
5173 ucvector_cleanup(&data
);
5178 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5180 static void filterScanline(unsigned char* out
, const unsigned char* scanline
, const unsigned char* prevline
,
5181 size_t length
, size_t bytewidth
, unsigned char filterType
)
5187 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
];
5192 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5193 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
];
5197 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5198 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
];
5204 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
] - prevline
[i
];
5208 for(i
= 0; i
< length
; i
++) out
[i
] = scanline
[i
];
5214 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
] - prevline
[i
] / 2;
5215 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - ((scanline
[i
- bytewidth
] + prevline
[i
]) / 2);
5219 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5220 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = scanline
[i
] - scanline
[i
- bytewidth
] / 2;
5226 /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
5227 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = (scanline
[i
] - prevline
[i
]);
5228 for(i
= bytewidth
; i
< length
; i
++)
5230 out
[i
] = (scanline
[i
] - paethPredictor(scanline
[i
- bytewidth
], prevline
[i
], prevline
[i
- bytewidth
]));
5235 for(i
= 0; i
< bytewidth
; i
++) out
[i
] = scanline
[i
];
5236 /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
5237 for(i
= bytewidth
; i
< length
; i
++) out
[i
] = (scanline
[i
] - scanline
[i
- bytewidth
]);
5240 default: return; /*unexisting filter type given*/
5244 /* log2 approximation. A slight bit faster than std::log. */
5245 static float flog2(float f
)
5248 while(f
> 32) { result
+= 4; f
/= 16; }
5249 while(f
> 2) { result
++; f
/= 2; }
5250 return result
+ 1.442695f
* (f
* f
* f
/ 3 - 3 * f
* f
/ 2 + 3 * f
- 1.83333f
);
5253 static unsigned filter(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
,
5254 const LodePNGColorMode
* info
, const LodePNGEncoderSettings
* settings
)
5257 For PNG filter method 0
5258 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
5259 the scanlines with 1 extra byte per scanline
5262 unsigned bpp
= lodepng_get_bpp(info
);
5263 /*the width of a scanline in bytes, not including the filter type*/
5264 size_t linebytes
= (w
* bpp
+ 7) / 8;
5265 /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
5266 size_t bytewidth
= (bpp
+ 7) / 8;
5267 const unsigned char* prevline
= 0;
5270 LodePNGFilterStrategy strategy
= settings
->filter_strategy
;
5273 There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
5274 * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
5275 use fixed filtering, with the filter None).
5276 * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
5277 not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
5278 all five filters and select the filter that produces the smallest sum of absolute values per row.
5279 This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
5281 If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
5282 but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
5285 if(settings
->filter_palette_zero
&&
5286 (info
->colortype
== LCT_PALETTE
|| info
->bitdepth
< 8)) strategy
= LFS_ZERO
;
5288 if(bpp
== 0) return 31; /*error: invalid color type*/
5290 if(strategy
== LFS_ZERO
)
5292 for(y
= 0; y
< h
; y
++)
5294 size_t outindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
5295 size_t inindex
= linebytes
* y
;
5296 out
[outindex
] = 0; /*filter type byte*/
5297 filterScanline(&out
[outindex
+ 1], &in
[inindex
], prevline
, linebytes
, bytewidth
, 0);
5298 prevline
= &in
[inindex
];
5301 else if(strategy
== LFS_MINSUM
)
5303 /*adaptive filtering*/
5305 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5306 size_t smallest
= 0;
5307 unsigned type
, bestType
= 0;
5309 for(type
= 0; type
< 5; type
++)
5311 ucvector_init(&attempt
[type
]);
5312 if(!ucvector_resize(&attempt
[type
], linebytes
)) return 83; /*alloc fail*/
5317 for(y
= 0; y
< h
; y
++)
5319 /*try the 5 filter types*/
5320 for(type
= 0; type
< 5; type
++)
5322 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5324 /*calculate the sum of the result*/
5328 for(x
= 0; x
< linebytes
; x
++) sum
[type
] += (unsigned char)(attempt
[type
].data
[x
]);
5332 for(x
= 0; x
< linebytes
; x
++)
5334 /*For differences, each byte should be treated as signed, values above 127 are negative
5335 (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
5336 This means filtertype 0 is almost never chosen, but that is justified.*/
5337 signed char s
= (signed char)(attempt
[type
].data
[x
]);
5338 sum
[type
] += s
< 0 ? -s
: s
;
5342 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5343 if(type
== 0 || sum
[type
] < smallest
)
5346 smallest
= sum
[type
];
5350 prevline
= &in
[y
* linebytes
];
5352 /*now fill the out values*/
5353 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5354 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5358 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5360 else if(strategy
== LFS_ENTROPY
)
5363 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5365 unsigned type
, bestType
= 0;
5366 unsigned count
[256];
5368 for(type
= 0; type
< 5; type
++)
5370 ucvector_init(&attempt
[type
]);
5371 if(!ucvector_resize(&attempt
[type
], linebytes
)) return 83; /*alloc fail*/
5374 for(y
= 0; y
< h
; y
++)
5376 /*try the 5 filter types*/
5377 for(type
= 0; type
< 5; type
++)
5379 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5380 for(x
= 0; x
< 256; x
++) count
[x
] = 0;
5381 for(x
= 0; x
< linebytes
; x
++) count
[attempt
[type
].data
[x
]]++;
5382 count
[type
]++; /*the filter type itself is part of the scanline*/
5384 for(x
= 0; x
< 256; x
++)
5386 float p
= count
[x
] / (float)(linebytes
+ 1);
5387 sum
[type
] += count
[x
] == 0 ? 0 : flog2(1 / p
) * p
;
5389 /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
5390 if(type
== 0 || sum
[type
] < smallest
)
5393 smallest
= sum
[type
];
5397 prevline
= &in
[y
* linebytes
];
5399 /*now fill the out values*/
5400 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5401 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5404 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5406 else if(strategy
== LFS_PREDEFINED
)
5408 for(y
= 0; y
< h
; y
++)
5410 size_t outindex
= (1 + linebytes
) * y
; /*the extra filterbyte added to each row*/
5411 size_t inindex
= linebytes
* y
;
5412 unsigned type
= settings
->predefined_filters
[y
];
5413 out
[outindex
] = type
; /*filter type byte*/
5414 filterScanline(&out
[outindex
+ 1], &in
[inindex
], prevline
, linebytes
, bytewidth
, type
);
5415 prevline
= &in
[inindex
];
5418 else if(strategy
== LFS_BRUTE_FORCE
)
5420 /*brute force filter chooser.
5421 deflate the scanline after every filter attempt to see which one deflates best.
5422 This is very slow and gives only slightly smaller, sometimes even larger, result*/
5424 ucvector attempt
[5]; /*five filtering attempts, one for each filter type*/
5425 size_t smallest
= 0;
5426 unsigned type
= 0, bestType
= 0;
5427 unsigned char* dummy
;
5428 LodePNGCompressSettings zlibsettings
= settings
->zlibsettings
;
5429 /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
5430 to simulate the true case where the tree is the same for the whole image. Sometimes it gives
5431 better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
5432 cases better compression. It does make this a bit less slow, so it's worth doing this.*/
5433 zlibsettings
.btype
= 1;
5434 /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
5435 images only, so disable it*/
5436 zlibsettings
.custom_zlib
= 0;
5437 zlibsettings
.custom_deflate
= 0;
5438 for(type
= 0; type
< 5; type
++)
5440 ucvector_init(&attempt
[type
]);
5441 ucvector_resize(&attempt
[type
], linebytes
); /*todo: give error if resize failed*/
5443 for(y
= 0; y
< h
; y
++) /*try the 5 filter types*/
5445 for(type
= 0; type
< 5; type
++)
5447 unsigned testsize
= attempt
[type
].size
;
5448 /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
5450 filterScanline(attempt
[type
].data
, &in
[y
* linebytes
], prevline
, linebytes
, bytewidth
, type
);
5453 zlib_compress(&dummy
, &size
[type
], attempt
[type
].data
, testsize
, &zlibsettings
);
5455 /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
5456 if(type
== 0 || size
[type
] < smallest
)
5459 smallest
= size
[type
];
5462 prevline
= &in
[y
* linebytes
];
5463 out
[y
* (linebytes
+ 1)] = bestType
; /*the first byte of a scanline will be the filter type*/
5464 for(x
= 0; x
< linebytes
; x
++) out
[y
* (linebytes
+ 1) + 1 + x
] = attempt
[bestType
].data
[x
];
5466 for(type
= 0; type
< 5; type
++) ucvector_cleanup(&attempt
[type
]);
5468 else return 88; /* unknown filter strategy */
5473 static void addPaddingBits(unsigned char* out
, const unsigned char* in
,
5474 size_t olinebits
, size_t ilinebits
, unsigned h
)
5476 /*The opposite of the removePaddingBits function
5477 olinebits must be >= ilinebits*/
5479 size_t diff
= olinebits
- ilinebits
;
5480 size_t obp
= 0, ibp
= 0; /*bit pointers*/
5481 for(y
= 0; y
< h
; y
++)
5484 for(x
= 0; x
< ilinebits
; x
++)
5486 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
5487 setBitOfReversedStream(&obp
, out
, bit
);
5489 /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
5490 "Use of uninitialised value of size ###" warning from valgrind*/
5491 for(x
= 0; x
< diff
; x
++) setBitOfReversedStream(&obp
, out
, 0);
5496 in: non-interlaced image with size w*h
5497 out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
5498 no padding bits between scanlines, but between reduced images so that each
5499 reduced image starts at a byte.
5501 there are no padding bits, not between scanlines, not between reduced images
5502 in has the following size in bits: w * h * bpp.
5503 out is possibly bigger due to padding bits between reduced images
5504 NOTE: comments about padding bits are only relevant if bpp < 8
5506 static void Adam7_interlace(unsigned char* out
, const unsigned char* in
, unsigned w
, unsigned h
, unsigned bpp
)
5508 unsigned passw
[7], passh
[7];
5509 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
5512 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
5516 for(i
= 0; i
< 7; i
++)
5519 size_t bytewidth
= bpp
/ 8;
5520 for(y
= 0; y
< passh
[i
]; y
++)
5521 for(x
= 0; x
< passw
[i
]; x
++)
5523 size_t pixelinstart
= ((ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * w
+ ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bytewidth
;
5524 size_t pixeloutstart
= passstart
[i
] + (y
* passw
[i
] + x
) * bytewidth
;
5525 for(b
= 0; b
< bytewidth
; b
++)
5527 out
[pixeloutstart
+ b
] = in
[pixelinstart
+ b
];
5532 else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
5534 for(i
= 0; i
< 7; i
++)
5537 unsigned ilinebits
= bpp
* passw
[i
];
5538 unsigned olinebits
= bpp
* w
;
5539 size_t obp
, ibp
; /*bit pointers (for out and in buffer)*/
5540 for(y
= 0; y
< passh
[i
]; y
++)
5541 for(x
= 0; x
< passw
[i
]; x
++)
5543 ibp
= (ADAM7_IY
[i
] + y
* ADAM7_DY
[i
]) * olinebits
+ (ADAM7_IX
[i
] + x
* ADAM7_DX
[i
]) * bpp
;
5544 obp
= (8 * passstart
[i
]) + (y
* ilinebits
+ x
* bpp
);
5545 for(b
= 0; b
< bpp
; b
++)
5547 unsigned char bit
= readBitFromReversedStream(&ibp
, in
);
5548 setBitOfReversedStream(&obp
, out
, bit
);
5555 /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
5556 return value is error**/
5557 static unsigned preProcessScanlines(unsigned char** out
, size_t* outsize
, const unsigned char* in
,
5558 unsigned w
, unsigned h
,
5559 const LodePNGInfo
* info_png
, const LodePNGEncoderSettings
* settings
)
5562 This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
5563 *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
5564 *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
5566 unsigned bpp
= lodepng_get_bpp(&info_png
->color
);
5569 if(info_png
->interlace_method
== 0)
5571 *outsize
= h
+ (h
* ((w
* bpp
+ 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
5572 *out
= (unsigned char*)mymalloc(*outsize
);
5573 if(!(*out
) && (*outsize
)) error
= 83; /*alloc fail*/
5577 /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
5578 if(bpp
< 8 && w
* bpp
!= ((w
* bpp
+ 7) / 8) * 8)
5580 unsigned char* padded
= (unsigned char*)mymalloc(h
* ((w
* bpp
+ 7) / 8));
5581 if(!padded
) error
= 83; /*alloc fail*/
5584 addPaddingBits(padded
, in
, ((w
* bpp
+ 7) / 8) * 8, w
* bpp
, h
);
5585 error
= filter(*out
, padded
, w
, h
, &info_png
->color
, settings
);
5591 /*we can immediatly filter into the out buffer, no other steps needed*/
5592 error
= filter(*out
, in
, w
, h
, &info_png
->color
, settings
);
5596 else /*interlace_method is 1 (Adam7)*/
5598 unsigned passw
[7], passh
[7];
5599 size_t filter_passstart
[8], padded_passstart
[8], passstart
[8];
5600 unsigned char* adam7
;
5602 Adam7_getpassvalues(passw
, passh
, filter_passstart
, padded_passstart
, passstart
, w
, h
, bpp
);
5604 *outsize
= filter_passstart
[7]; /*image size plus an extra byte per scanline + possible padding bits*/
5605 *out
= (unsigned char*)mymalloc(*outsize
);
5606 if(!(*out
)) error
= 83; /*alloc fail*/
5608 adam7
= (unsigned char*)mymalloc(passstart
[7]);
5609 if(!adam7
&& passstart
[7]) error
= 83; /*alloc fail*/
5615 Adam7_interlace(adam7
, in
, w
, h
, bpp
);
5616 for(i
= 0; i
< 7; i
++)
5620 unsigned char* padded
= (unsigned char*)mymalloc(padded_passstart
[i
+ 1] - padded_passstart
[i
]);
5621 if(!padded
) ERROR_BREAK(83); /*alloc fail*/
5622 addPaddingBits(padded
, &adam7
[passstart
[i
]],
5623 ((passw
[i
] * bpp
+ 7) / 8) * 8, passw
[i
] * bpp
, passh
[i
]);
5624 error
= filter(&(*out
)[filter_passstart
[i
]], padded
,
5625 passw
[i
], passh
[i
], &info_png
->color
, settings
);
5630 error
= filter(&(*out
)[filter_passstart
[i
]], &adam7
[padded_passstart
[i
]],
5631 passw
[i
], passh
[i
], &info_png
->color
, settings
);
5645 palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
5646 returns 0 if the palette is opaque,
5647 returns 1 if the palette has a single color with alpha 0 ==> color key
5648 returns 2 if the palette is semi-translucent.
5650 static unsigned getPaletteTranslucency(const unsigned char* palette
, size_t palettesize
)
5653 unsigned r
= 0, g
= 0, b
= 0; /*the value of the color with alpha 0, so long as color keying is possible*/
5654 for(i
= 0; i
< palettesize
; i
++)
5656 if(!key
&& palette
[4 * i
+ 3] == 0)
5658 r
= palette
[4 * i
+ 0]; g
= palette
[4 * i
+ 1]; b
= palette
[4 * i
+ 2];
5660 i
= (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
5662 else if(palette
[4 * i
+ 3] != 255) return 2;
5663 /*when key, no opaque RGB may have key's RGB*/
5664 else if(key
&& r
== palette
[i
* 4 + 0] && g
== palette
[i
* 4 + 1] && b
== palette
[i
* 4 + 2]) return 2;
5669 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5670 static unsigned addUnknownChunks(ucvector
* out
, unsigned char* data
, size_t datasize
)
5672 unsigned char* inchunk
= data
;
5673 while((size_t)(inchunk
- data
) < datasize
)
5675 CERROR_TRY_RETURN(lodepng_chunk_append(&out
->data
, &out
->size
, inchunk
));
5676 out
->allocsize
= out
->size
; /*fix the allocsize again*/
5677 inchunk
= lodepng_chunk_next(inchunk
);
5681 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5683 unsigned lodepng_encode(unsigned char** out
, size_t* outsize
,
5684 const unsigned char* image
, unsigned w
, unsigned h
,
5685 LodePNGState
* state
)
5689 unsigned char* data
= 0; /*uncompressed version of the IDAT chunk data*/
5690 size_t datasize
= 0;
5692 /*provide some proper output values if error will happen*/
5697 lodepng_info_init(&info
);
5698 lodepng_info_copy(&info
, &state
->info_png
);
5700 if((info
.color
.colortype
== LCT_PALETTE
|| state
->encoder
.force_palette
)
5701 && (info
.color
.palettesize
== 0 || info
.color
.palettesize
> 256))
5703 state
->error
= 68; /*invalid palette size, it is only allowed to be 1-256*/
5704 return state
->error
;
5707 if(state
->encoder
.auto_convert
!= LAC_NO
)
5709 state
->error
= doAutoChooseColor(&info
.color
, image
, w
, h
, &state
->info_raw
,
5710 state
->encoder
.auto_convert
);
5712 if(state
->error
) return state
->error
;
5714 if(state
->encoder
.zlibsettings
.windowsize
> 32768)
5716 CERROR_RETURN_ERROR(state
->error
, 60); /*error: windowsize larger than allowed*/
5718 if(state
->encoder
.zlibsettings
.btype
> 2)
5720 CERROR_RETURN_ERROR(state
->error
, 61); /*error: unexisting btype*/
5722 if(state
->info_png
.interlace_method
> 1)
5724 CERROR_RETURN_ERROR(state
->error
, 71); /*error: unexisting interlace mode*/
5727 state
->error
= checkColorValidity(info
.color
.colortype
, info
.color
.bitdepth
);
5728 if(state
->error
) return state
->error
; /*error: unexisting color type given*/
5729 state
->error
= checkColorValidity(state
->info_raw
.colortype
, state
->info_raw
.bitdepth
);
5730 if(state
->error
) return state
->error
; /*error: unexisting color type given*/
5732 if(!lodepng_color_mode_equal(&state
->info_raw
, &info
.color
))
5734 unsigned char* converted
;
5735 size_t size
= (w
* h
* lodepng_get_bpp(&info
.color
) + 7) / 8;
5737 converted
= (unsigned char*)mymalloc(size
);
5738 if(!converted
&& size
) state
->error
= 83; /*alloc fail*/
5741 state
->error
= lodepng_convert(converted
, image
, &info
.color
, &state
->info_raw
, w
, h
);
5743 if(!state
->error
) preProcessScanlines(&data
, &datasize
, converted
, w
, h
, &info
, &state
->encoder
);
5746 else preProcessScanlines(&data
, &datasize
, image
, w
, h
, &info
, &state
->encoder
);
5748 ucvector_init(&outv
);
5749 while(!state
->error
) /*while only executed once, to break on error*/
5751 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5753 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5754 /*write signature and chunks*/
5755 writeSignature(&outv
);
5757 addChunk_IHDR(&outv
, w
, h
, info
.color
.colortype
, info
.color
.bitdepth
, info
.interlace_method
);
5758 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5759 /*unknown chunks between IHDR and PLTE*/
5760 if(info
.unknown_chunks_data
[0])
5762 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[0], info
.unknown_chunks_size
[0]);
5763 if(state
->error
) break;
5765 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5767 if(info
.color
.colortype
== LCT_PALETTE
)
5769 addChunk_PLTE(&outv
, &info
.color
);
5771 if(state
->encoder
.force_palette
&& (info
.color
.colortype
== LCT_RGB
|| info
.color
.colortype
== LCT_RGBA
))
5773 addChunk_PLTE(&outv
, &info
.color
);
5776 if(info
.color
.colortype
== LCT_PALETTE
&& getPaletteTranslucency(info
.color
.palette
, info
.color
.palettesize
) != 0)
5778 addChunk_tRNS(&outv
, &info
.color
);
5780 if((info
.color
.colortype
== LCT_GREY
|| info
.color
.colortype
== LCT_RGB
) && info
.color
.key_defined
)
5782 addChunk_tRNS(&outv
, &info
.color
);
5784 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5785 /*bKGD (must come between PLTE and the IDAt chunks*/
5786 if(info
.background_defined
) addChunk_bKGD(&outv
, &info
);
5787 /*pHYs (must come before the IDAT chunks)*/
5788 if(info
.phys_defined
) addChunk_pHYs(&outv
, &info
);
5790 /*unknown chunks between PLTE and IDAT*/
5791 if(info
.unknown_chunks_data
[1])
5793 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[1], info
.unknown_chunks_size
[1]);
5794 if(state
->error
) break;
5796 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5797 /*IDAT (multiple IDAT chunks must be consecutive)*/
5798 state
->error
= addChunk_IDAT(&outv
, data
, datasize
, &state
->encoder
.zlibsettings
);
5799 if(state
->error
) break;
5800 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5802 if(info
.time_defined
) addChunk_tIME(&outv
, &info
.time
);
5803 /*tEXt and/or zTXt*/
5804 for(i
= 0; i
< info
.text_num
; i
++)
5806 if(MyStrlen(info
.text_keys
[i
]) > 79)
5808 state
->error
= 66; /*text chunk too large*/
5811 if(MyStrlen(info
.text_keys
[i
]) < 1)
5813 state
->error
= 67; /*text chunk too small*/
5816 if(state
->encoder
.text_compression
)
5817 addChunk_zTXt(&outv
, info
.text_keys
[i
], info
.text_strings
[i
], &state
->encoder
.zlibsettings
);
5819 addChunk_tEXt(&outv
, info
.text_keys
[i
], info
.text_strings
[i
]);
5821 /*LodePNG version id in text chunk*/
5822 if(state
->encoder
.add_id
)
5824 unsigned alread_added_id_text
= 0;
5825 for(i
= 0; i
< info
.text_num
; i
++)
5827 if(!strcmp(info
.text_keys
[i
], "LodePNG"))
5829 alread_added_id_text
= 1;
5833 if(alread_added_id_text
== 0)
5834 addChunk_tEXt(&outv
, "LodePNG", VERSION_STRING
); /*it's shorter as tEXt than as zTXt chunk*/
5837 for(i
= 0; i
< info
.itext_num
; i
++)
5839 if(MyStrlen(info
.itext_keys
[i
]) > 79)
5841 state
->error
= 66; /*text chunk too large*/
5844 if(MyStrlen(info
.itext_keys
[i
]) < 1)
5846 state
->error
= 67; /*text chunk too small*/
5849 addChunk_iTXt(&outv
, state
->encoder
.text_compression
,
5850 info
.itext_keys
[i
], info
.itext_langtags
[i
], info
.itext_transkeys
[i
], info
.itext_strings
[i
],
5851 &state
->encoder
.zlibsettings
);
5854 /*unknown chunks between IDAT and IEND*/
5855 if(info
.unknown_chunks_data
[2])
5857 state
->error
= addUnknownChunks(&outv
, info
.unknown_chunks_data
[2], info
.unknown_chunks_size
[2]);
5858 if(state
->error
) break;
5860 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5862 addChunk_IEND(&outv
);
5864 break; /*this isn't really a while loop; no error happened so break out now!*/
5867 lodepng_info_cleanup(&info
);
5869 /*instead of cleaning the vector up, give it to the output*/
5871 *outsize
= outv
.size
;
5873 return state
->error
;
5876 unsigned lodepng_encode_memory(unsigned char** out
, size_t* outsize
, const unsigned char* image
,
5877 unsigned w
, unsigned h
, LodePNGColorType colortype
, unsigned bitdepth
)
5881 lodepng_state_init(&state
);
5882 state
.info_raw
.colortype
= colortype
;
5883 state
.info_raw
.bitdepth
= bitdepth
;
5884 state
.info_png
.color
.colortype
= colortype
;
5885 state
.info_png
.color
.bitdepth
= bitdepth
;
5886 lodepng_encode(out
, outsize
, image
, w
, h
, &state
);
5887 error
= state
.error
;
5888 lodepng_state_cleanup(&state
);
5892 unsigned lodepng_encode32(unsigned char** out
, size_t* outsize
, const unsigned char* image
, unsigned w
, unsigned h
)
5894 return lodepng_encode_memory(out
, outsize
, image
, w
, h
, LCT_RGBA
, 8);
5897 unsigned lodepng_encode24(unsigned char** out
, size_t* outsize
, const unsigned char* image
, unsigned w
, unsigned h
)
5899 return lodepng_encode_memory(out
, outsize
, image
, w
, h
, LCT_RGB
, 8);
5902 #ifdef LODEPNG_COMPILE_DISK
5903 unsigned lodepng_encode_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
,
5904 LodePNGColorType colortype
, unsigned bitdepth
)
5906 unsigned char* buffer
;
5908 unsigned error
= lodepng_encode_memory(&buffer
, &buffersize
, image
, w
, h
, colortype
, bitdepth
);
5909 if(!error
) error
= lodepng_save_file(buffer
, buffersize
, filename
);
5914 unsigned lodepng_encode32_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
)
5916 return lodepng_encode_file(filename
, image
, w
, h
, LCT_RGBA
, 8);
5919 unsigned lodepng_encode24_file(const char* filename
, const unsigned char* image
, unsigned w
, unsigned h
)
5921 return lodepng_encode_file(filename
, image
, w
, h
, LCT_RGB
, 8);
5923 #endif /*LODEPNG_COMPILE_DISK*/
5925 void lodepng_encoder_settings_init(LodePNGEncoderSettings
* settings
)
5927 lodepng_compress_settings_init(&settings
->zlibsettings
);
5928 settings
->filter_palette_zero
= 1;
5929 settings
->filter_strategy
= LFS_MINSUM
;
5930 settings
->auto_convert
= LAC_AUTO
;
5931 settings
->force_palette
= 0;
5932 settings
->predefined_filters
= 0;
5933 #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5934 settings
->add_id
= 0;
5935 settings
->text_compression
= 1;
5936 #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5939 #endif /*LODEPNG_COMPILE_ENCODER*/
5940 #endif /*LODEPNG_COMPILE_PNG*/
5942 #ifdef LODEPNG_COMPILE_ERROR_TEXT
5944 This returns the description of a numerical error code in English. This is also
5945 the documentation of all the error codes.
5947 const CHAR16
* lodepng_error_text(unsigned code
)
5951 case 0: return L
"no error, everything went ok";
5952 case 1: return L
"nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
5953 case 10: return L
"end of input memory reached without huffman end code"; /*while huffman decoding*/
5954 case 11: return L
"error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
5955 case 13: return L
"problem while processing dynamic deflate block";
5956 case 14: return L
"problem while processing dynamic deflate block";
5957 case 15: return L
"problem while processing dynamic deflate block";
5958 case 16: return L
"unexisting code while processing dynamic deflate block";
5959 case 17: return L
"end of out buffer memory reached while inflating";
5960 case 18: return L
"invalid distance code while inflating";
5961 case 19: return L
"end of out buffer memory reached while inflating";
5962 case 20: return L
"invalid deflate block BTYPE encountered while decoding";
5963 case 21: return L
"NLEN is not ones complement of LEN in a deflate block";
5964 /*end of out buffer memory reached while inflating:
5965 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
5966 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
5967 happen in a normal, well encoded, PNG image.*/
5968 case 22: return L
"end of out buffer memory reached while inflating";
5969 case 23: return L
"end of in buffer memory reached while inflating";
5970 case 24: return L
"invalid FCHECK in zlib header";
5971 case 25: return L
"invalid compression method in zlib header";
5972 case 26: return L
"FDICT encountered in zlib header while it's not used for PNG";
5973 case 27: return L
"PNG file is smaller than a PNG header";
5974 /*Checks the magic file header, the first 8 bytes of the PNG file*/
5975 case 28: return L
"incorrect PNG signature, it's no PNG or corrupted";
5976 case 29: return L
"first chunk is not the header chunk";
5977 case 30: return L
"chunk length too large, chunk broken off at end of file";
5978 case 31: return L
"illegal PNG color type or bpp";
5979 case 32: return L
"illegal PNG compression method";
5980 case 33: return L
"illegal PNG filter method";
5981 case 34: return L
"illegal PNG interlace method";
5982 case 35: return L
"chunk length of a chunk is too large or the chunk too small";
5983 case 36: return L
"illegal PNG filter type encountered";
5984 case 37: return L
"illegal bit depth for this color type given";
5985 case 38: return L
"the palette is too big"; /*more than 256 colors*/
5986 case 39: return L
"more palette alpha values given in tRNS chunk than there are colors in the palette";
5987 case 40: return L
"tRNS chunk has wrong size for greyscale image";
5988 case 41: return L
"tRNS chunk has wrong size for RGB image";
5989 case 42: return L
"tRNS chunk appeared while it was not allowed for this color type";
5990 case 43: return L
"bKGD chunk has wrong size for palette image";
5991 case 44: return L
"bKGD chunk has wrong size for greyscale image";
5992 case 45: return L
"bKGD chunk has wrong size for RGB image";
5993 /*Is the palette too small?*/
5994 case 46: return L
"a value in indexed image is larger than the palette size (bitdepth = 8)";
5995 /*Is the palette too small?*/
5996 case 47: return L
"a value in indexed image is larger than the palette size (bitdepth < 8)";
5997 /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/
5998 case 48: return L
"empty input or file doesn't exist";
5999 case 49: return L
"jumped past memory while generating dynamic huffman tree";
6000 case 50: return L
"jumped past memory while generating dynamic huffman tree";
6001 case 51: return L
"jumped past memory while inflating huffman block";
6002 case 52: return L
"jumped past memory while inflating";
6003 case 53: return L
"size of zlib data too small";
6004 case 54: return L
"repeat symbol in tree while there was no value symbol yet";
6005 /*jumped past tree while generating huffman tree, this could be when the
6006 tree will have more leaves than symbols after generating it out of the
6007 given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
6008 case 55: return L
"jumped past tree while generating huffman tree";
6009 case 56: return L
"given output image colortype or bitdepth not supported for color conversion";
6010 case 57: return L
"invalid CRC encountered (checking CRC can be disabled)";
6011 case 58: return L
"invalid ADLER32 encountered (checking ADLER32 can be disabled)";
6012 case 59: return L
"requested color conversion not supported";
6013 case 60: return L
"invalid window size given in the settings of the encoder (must be 0-32768)";
6014 case 61: return L
"invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
6015 /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
6016 case 62: return L
"conversion from color to greyscale not supported";
6017 case 63: return L
"length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
6018 /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
6019 case 64: return L
"the length of the END symbol 256 in the Huffman tree is 0";
6020 case 66: return L
"the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
6021 case 67: return L
"the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
6022 case 68: return L
"tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
6023 case 69: return L
"unknown chunk type with 'critical' flag encountered by the decoder";
6024 case 71: return L
"unexisting interlace mode given to encoder (must be 0 or 1)";
6025 case 72: return L
"while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
6026 case 73: return L
"invalid tIME chunk size";
6027 case 74: return L
"invalid pHYs chunk size";
6028 /*length could be wrong, or data chopped off*/
6029 case 75: return L
"no null termination char found while decoding text chunk";
6030 case 76: return L
"iTXt chunk too short to contain required bytes";
6031 case 77: return L
"integer overflow in buffer size";
6032 case 78: return L
"failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
6033 case 79: return L
"failed to open file for writing";
6034 case 80: return L
"tried creating a tree of 0 symbols";
6035 case 81: return L
"lazy matching at pos 0 is impossible";
6036 case 82: return L
"color conversion to palette requested while a color isn't in palette";
6037 case 83: return L
"memory allocation failed";
6038 case 84: return L
"given image too small to contain all pixels to be encoded";
6039 case 85: return L
"internal color conversion bug";
6040 case 86: return L
"impossible offset in lz77 encoding (internal bug)";
6041 case 87: return L
"must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
6042 case 88: return L
"invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
6043 case 89: return L
"text chunk keyword too short or long: must have size 1-79";
6045 return L
"unknown error code";
6047 #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
6049 /* ////////////////////////////////////////////////////////////////////////// */
6050 /* ////////////////////////////////////////////////////////////////////////// */
6051 /* // C++ Wrapper // */
6052 /* ////////////////////////////////////////////////////////////////////////// */
6053 /* ////////////////////////////////////////////////////////////////////////// */
6056 #ifdef LODEPNG_COMPILE_CPP
6060 #ifdef LODEPNG_COMPILE_DISK
6061 void load_file(std::vector
<unsigned char>& buffer
, const std::string
& filename
)
6063 std::ifstream
file(filename
.c_str(), std::ios::in
|std::ios::binary
|std::ios::ate
);
6066 std::streamsize size
= 0;
6067 if(file
.seekg(0, std::ios::end
).good()) size
= file
.tellg();
6068 if(file
.seekg(0, std::ios::beg
).good()) size
-= file
.tellg();
6070 /*read contents of the file into the vector*/
6071 buffer
.resize(size_t(size
));
6072 if(size
> 0) file
.read((char*)(&buffer
[0]), size
);
6075 /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
6076 void save_file(const std::vector
<unsigned char>& buffer
, const std::string
& filename
)
6078 std::ofstream
file(filename
.c_str(), std::ios::out
|std::ios::binary
);
6079 file
.write(buffer
.empty() ? 0 : (char*)&buffer
[0], std::streamsize(buffer
.size()));
6081 #endif //LODEPNG_COMPILE_DISK
6083 #ifdef LODEPNG_COMPILE_ZLIB
6084 #ifdef LODEPNG_COMPILE_DECODER
6085 unsigned decompress(std::vector
<unsigned char>& out
, const unsigned char* in
, size_t insize
,
6086 const LodePNGDecompressSettings
& settings
)
6088 unsigned char* buffer
= 0;
6089 size_t buffersize
= 0;
6090 unsigned error
= zlib_decompress(&buffer
, &buffersize
, in
, insize
, &settings
);
6093 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6099 unsigned decompress(std::vector
<unsigned char>& out
, const std::vector
<unsigned char>& in
,
6100 const LodePNGDecompressSettings
& settings
)
6102 return decompress(out
, in
.empty() ? 0 : &in
[0], in
.size(), settings
);
6104 #endif //LODEPNG_COMPILE_DECODER
6106 #ifdef LODEPNG_COMPILE_ENCODER
6107 unsigned compress(std::vector
<unsigned char>& out
, const unsigned char* in
, size_t insize
,
6108 const LodePNGCompressSettings
& settings
)
6110 unsigned char* buffer
= 0;
6111 size_t buffersize
= 0;
6112 unsigned error
= zlib_compress(&buffer
, &buffersize
, in
, insize
, &settings
);
6115 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6121 unsigned compress(std::vector
<unsigned char>& out
, const std::vector
<unsigned char>& in
,
6122 const LodePNGCompressSettings
& settings
)
6124 return compress(out
, in
.empty() ? 0 : &in
[0], in
.size(), settings
);
6126 #endif //LODEPNG_COMPILE_ENCODER
6127 #endif //LODEPNG_COMPILE_ZLIB
6130 #ifdef LODEPNG_COMPILE_PNG
6134 lodepng_state_init(this);
6137 State::State(const State
& other
)
6139 lodepng_state_init(this);
6140 lodepng_state_copy(this, &other
);
6145 lodepng_state_cleanup(this);
6148 State
& State::operator=(const State
& other
)
6150 lodepng_state_copy(this, &other
);
6154 #ifdef LODEPNG_COMPILE_DECODER
6156 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
, const unsigned char* in
,
6157 size_t insize
, LodePNGColorType colortype
, unsigned bitdepth
)
6159 unsigned char* buffer
;
6160 unsigned error
= lodepng_decode_memory(&buffer
, &w
, &h
, in
, insize
, colortype
, bitdepth
);
6161 if(buffer
&& !error
)
6164 state
.info_raw
.colortype
= colortype
;
6165 state
.info_raw
.bitdepth
= bitdepth
;
6166 size_t buffersize
= lodepng_get_raw_size(w
, h
, &state
.info_raw
);
6167 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6173 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6174 const std::vector
<unsigned char>& in
, LodePNGColorType colortype
, unsigned bitdepth
)
6176 return decode(out
, w
, h
, in
.empty() ? 0 : &in
[0], (unsigned)in
.size(), colortype
, bitdepth
);
6179 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6181 const unsigned char* in
, size_t insize
)
6183 unsigned char* buffer
;
6184 unsigned error
= lodepng_decode(&buffer
, &w
, &h
, &state
, in
, insize
);
6185 if(buffer
&& !error
)
6187 size_t buffersize
= lodepng_get_raw_size(w
, h
, &state
.info_raw
);
6188 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6194 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
,
6196 const std::vector
<unsigned char>& in
)
6198 return decode(out
, w
, h
, state
, in
.empty() ? 0 : &in
[0], in
.size());
6201 #ifdef LODEPNG_COMPILE_DISK
6202 unsigned decode(std::vector
<unsigned char>& out
, unsigned& w
, unsigned& h
, const std::string
& filename
,
6203 LodePNGColorType colortype
, unsigned bitdepth
)
6205 std::vector
<unsigned char> buffer
;
6206 load_file(buffer
, filename
);
6207 return decode(out
, w
, h
, buffer
, colortype
, bitdepth
);
6209 #endif //LODEPNG_COMPILE_DECODER
6210 #endif //LODEPNG_COMPILE_DISK
6212 #ifdef LODEPNG_COMPILE_ENCODER
6213 unsigned encode(std::vector
<unsigned char>& out
, const unsigned char* in
, unsigned w
, unsigned h
,
6214 LodePNGColorType colortype
, unsigned bitdepth
)
6216 unsigned char* buffer
;
6218 unsigned error
= lodepng_encode_memory(&buffer
, &buffersize
, in
, w
, h
, colortype
, bitdepth
);
6221 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6227 unsigned encode(std::vector
<unsigned char>& out
,
6228 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6229 LodePNGColorType colortype
, unsigned bitdepth
)
6231 if(lodepng_get_raw_size_lct(w
, h
, colortype
, bitdepth
) > in
.size()) return 84;
6232 return encode(out
, in
.empty() ? 0 : &in
[0], w
, h
, colortype
, bitdepth
);
6235 unsigned encode(std::vector
<unsigned char>& out
,
6236 const unsigned char* in
, unsigned w
, unsigned h
,
6239 unsigned char* buffer
;
6241 unsigned error
= lodepng_encode(&buffer
, &buffersize
, in
, w
, h
, &state
);
6244 out
.insert(out
.end(), &buffer
[0], &buffer
[buffersize
]);
6250 unsigned encode(std::vector
<unsigned char>& out
,
6251 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6254 if(lodepng_get_raw_size(w
, h
, &state
.info_raw
) > in
.size()) return 84;
6255 return encode(out
, in
.empty() ? 0 : &in
[0], w
, h
, state
);
6258 #ifdef LODEPNG_COMPILE_DISK
6259 unsigned encode(const std::string
& filename
,
6260 const unsigned char* in
, unsigned w
, unsigned h
,
6261 LodePNGColorType colortype
, unsigned bitdepth
)
6263 std::vector
<unsigned char> buffer
;
6264 unsigned error
= encode(buffer
, in
, w
, h
, colortype
, bitdepth
);
6265 if(!error
) save_file(buffer
, filename
);
6269 unsigned encode(const std::string
& filename
,
6270 const std::vector
<unsigned char>& in
, unsigned w
, unsigned h
,
6271 LodePNGColorType colortype
, unsigned bitdepth
)
6273 if(lodepng_get_raw_size_lct(w
, h
, colortype
, bitdepth
) > in
.size()) return 84;
6274 return encode(filename
, in
.empty() ? 0 : &in
[0], w
, h
, colortype
, bitdepth
);
6276 #endif //LODEPNG_COMPILE_DISK
6277 #endif //LODEPNG_COMPILE_ENCODER
6278 #endif //LODEPNG_COMPILE_PNG
6279 } //namespace lodepng
6280 #endif /*LODEPNG_COMPILE_CPP*/
6283 typedef struct _lode_color
{
6290 EG_IMAGE
* egDecodePNG(IN UINT8
*FileData
, IN UINTN FileDataLength
, IN UINTN IconSize
, IN BOOLEAN WantAlpha
) {
6291 EG_IMAGE
*NewImage
= NULL
;
6292 unsigned Error
, Width
, Height
;
6293 EG_PIXEL
*PixelData
;
6294 lode_color
*LodeData
;
6297 Error
= lodepng_decode_memory((unsigned char **) &PixelData
, &Width
, &Height
, (unsigned char*) FileData
,
6298 (size_t) FileDataLength
, LCT_RGBA
, 8);
6304 // allocate image structure and buffer
6305 NewImage
= egCreateImage(Width
, Height
, WantAlpha
);
6306 if ((NewImage
== NULL
) || (NewImage
->Width
!= Width
) || (NewImage
->Height
!= Height
))
6309 LodeData
= (lode_color
*) PixelData
;
6310 for (i
= 0; i
< (NewImage
->Height
* NewImage
->Width
); i
++) {
6311 NewImage
->PixelData
[i
].r
= LodeData
[i
].red
;
6312 NewImage
->PixelData
[i
].g
= LodeData
[i
].green
;
6313 NewImage
->PixelData
[i
].b
= LodeData
[i
].blue
;
6315 NewImage
->PixelData
[i
].a
= LodeData
[i
].alpha
;
6320 } // EG_IMAGE * egDecodePNG()