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