Coverage Report

Created: 2026-01-09 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lodepng/lodepng.cpp
Line
Count
Source
1
/*
2
LodePNG version 20260102
3
4
Copyright (c) 2005-2026 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
#ifdef LODEPNG_COMPILE_DISK
34
#include <limits.h> /* LONG_MAX */
35
#include <stdio.h> /* file handling */
36
#endif /* LODEPNG_COMPILE_DISK */
37
38
#ifdef LODEPNG_COMPILE_ALLOCATORS
39
#include <stdlib.h> /* allocations */
40
#endif /* LODEPNG_COMPILE_ALLOCATORS */
41
42
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
43
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
44
#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
45
#endif /*_MSC_VER */
46
47
const char* LODEPNG_VERSION_STRING = "20260102";
48
49
/*
50
This source file is divided into the following large parts. The code sections
51
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
52
-Tools for C and common code for PNG and Zlib
53
-C Code for Zlib (huffman, deflate, ...)
54
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
55
-The C++ wrapper around all of the above
56
*/
57
58
/* ////////////////////////////////////////////////////////////////////////// */
59
/* ////////////////////////////////////////////////////////////////////////// */
60
/* // Tools for C, and common code for PNG and Zlib.                       // */
61
/* ////////////////////////////////////////////////////////////////////////// */
62
/* ////////////////////////////////////////////////////////////////////////// */
63
64
/*The malloc, realloc and free functions defined here with "lodepng_" in front
65
of the name, so that you can easily change them to others related to your
66
platform if needed. Everything else in the code calls these. Pass
67
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
68
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
69
define them in your own project's source files without needing to change
70
lodepng source code. Don't forget to remove "static" if you copypaste them
71
from here.*/
72
73
#ifdef LODEPNG_COMPILE_ALLOCATORS
74
1.53M
static void* lodepng_malloc(size_t size) {
75
1.53M
#ifdef LODEPNG_MAX_ALLOC
76
1.53M
  if(size > LODEPNG_MAX_ALLOC) return 0;
77
1.53M
#endif
78
1.53M
  return malloc(size);
79
1.53M
}
80
81
/* NOTE: when realloc returns NULL, it leaves the original memory untouched */
82
603k
static void* lodepng_realloc(void* ptr, size_t new_size) {
83
603k
#ifdef LODEPNG_MAX_ALLOC
84
603k
  if(new_size > LODEPNG_MAX_ALLOC) return 0;
85
602k
#endif
86
602k
  return realloc(ptr, new_size);
87
603k
}
88
89
1.71M
static void lodepng_free(void* ptr) {
90
1.71M
  free(ptr);
91
1.71M
}
92
#else /*LODEPNG_COMPILE_ALLOCATORS*/
93
/* TODO: support giving additional void* payload to the custom allocators */
94
void* lodepng_malloc(size_t size);
95
void* lodepng_realloc(void* ptr, size_t new_size);
96
void lodepng_free(void* ptr);
97
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
98
99
/* convince the compiler to inline a function, for use when this measurably improves performance */
100
/* inline is not available in C90, but use it when supported by the compiler */
101
#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
102
#define LODEPNG_INLINE inline
103
#else
104
#define LODEPNG_INLINE /* not available */
105
#endif
106
107
/* restrict is not available in C90, but use it when supported by the compiler */
108
#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\
109
    (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \
110
    (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus))
111
#define LODEPNG_RESTRICT __restrict
112
#else
113
#define LODEPNG_RESTRICT /* not available */
114
#endif
115
116
/* Replacements for C library functions such as memcpy and strlen, to support platforms
117
where a full C library is not available. The compiler can recognize them and compile
118
to something as fast. */
119
120
static void lodepng_memcpy(void* LODEPNG_RESTRICT dst,
121
19.2M
                           const void* LODEPNG_RESTRICT src, size_t size) {
122
19.2M
  size_t i;
123
566M
  for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i];
124
19.2M
}
125
126
static void lodepng_memset(void* LODEPNG_RESTRICT dst,
127
86.0k
                           int value, size_t num) {
128
86.0k
  size_t i;
129
258M
  for(i = 0; i < num; i++) ((char*)dst)[i] = (char)value;
130
86.0k
}
131
132
/* does not check memory out of bounds, do not use on untrusted data */
133
2.02M
static size_t lodepng_strlen(const char* a) {
134
2.02M
  const char* orig = a;
135
  /* avoid warning about unused function in case of disabled COMPILE... macros */
136
2.02M
  (void)(&lodepng_strlen);
137
14.6M
  while(*a) a++;
138
2.02M
  return (size_t)(a - orig);
139
2.02M
}
140
141
55.9k
#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
142
0
#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
143
144
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)
145
/* Safely check if adding two integers will overflow (no undefined
146
behavior, compiler removing the code, etc...) and output result. */
147
258k
static int lodepng_addofl(size_t a, size_t b, size_t* result) {
148
258k
  *result = a + b; /* Unsigned addition is well defined and safe in C90 */
149
258k
  return *result < a;
150
258k
}
151
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/
152
153
#ifdef LODEPNG_COMPILE_DECODER
154
/* Safely check if multiplying two integers will overflow (no undefined
155
behavior, compiler removing the code, etc...) and output result. */
156
40.8k
static int lodepng_mulofl(size_t a, size_t b, size_t* result) {
157
40.8k
  *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
158
40.8k
  return (a != 0 && *result / a != b);
159
40.8k
}
160
161
#ifdef LODEPNG_COMPILE_ZLIB
162
/* Safely check if a + b > c, even if overflow could happen. */
163
6.74k
static int lodepng_gtofl(size_t a, size_t b, size_t c) {
164
6.74k
  size_t d;
165
6.74k
  if(lodepng_addofl(a, b, &d)) return 1;
166
6.74k
  return d > c;
167
6.74k
}
168
#endif /*LODEPNG_COMPILE_ZLIB*/
169
#endif /*LODEPNG_COMPILE_DECODER*/
170
171
172
/*
173
Often in case of an error a value is assigned to a variable and then it breaks
174
out of a loop (to go to the cleanup phase of a function). This macro does that.
175
It makes the error handling code shorter and more readable.
176
177
Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83);
178
*/
179
0
#define CERROR_BREAK(errorvar, code){\
180
0
  errorvar = code;\
181
0
  break;\
182
908
}
183
184
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
185
591
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
186
187
/*Set error var to the error code, and return it.*/
188
232
#define CERROR_RETURN_ERROR(errorvar, code){\
189
232
  errorvar = code;\
190
232
  return code;\
191
232
}
192
193
/*Try the code, if it returns error, also return the error.*/
194
162k
#define CERROR_TRY_RETURN(call){\
195
162k
  unsigned error = call;\
196
162k
  if(error) return error;\
197
162k
}
198
199
/*Set error var to the error code, and return from the void function.*/
200
66
#define CERROR_RETURN(errorvar, code){\
201
66
  errorvar = code;\
202
66
  return;\
203
66
}
204
205
/*
206
About uivector, ucvector and string:
207
-All of them wrap dynamic arrays or text strings in a similar way.
208
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
209
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
210
-They're not used in the interface, only internally in this file as static functions.
211
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
212
*/
213
214
#ifdef LODEPNG_COMPILE_ZLIB
215
#ifdef LODEPNG_COMPILE_ENCODER
216
/*dynamic vector of unsigned ints*/
217
typedef struct uivector {
218
  unsigned* data;
219
  size_t size; /*size in number of unsigned longs*/
220
  size_t allocsize; /*allocated size in bytes*/
221
} uivector;
222
223
0
static void uivector_cleanup(void* p) {
224
0
  ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
225
0
  lodepng_free(((uivector*)p)->data);
226
0
  ((uivector*)p)->data = NULL;
227
0
}
228
229
/*returns 1 if success, 0 if failure ==> nothing done*/
230
0
static unsigned uivector_resize(uivector* p, size_t size) {
231
0
  size_t allocsize = size * sizeof(unsigned);
232
0
  if(allocsize > p->allocsize) {
233
0
    size_t newsize = allocsize + (p->allocsize >> 1u);
234
0
    void* data = lodepng_realloc(p->data, newsize);
235
0
    if(data) {
236
0
      p->allocsize = newsize;
237
0
      p->data = (unsigned*)data;
238
0
    }
239
0
    else return 0; /*error: not enough memory*/
240
0
  }
241
0
  p->size = size;
242
0
  return 1; /*success*/
243
0
}
244
245
0
static void uivector_init(uivector* p) {
246
0
  p->data = NULL;
247
0
  p->size = p->allocsize = 0;
248
0
}
249
250
/*returns 1 if success, 0 if failure ==> nothing done*/
251
0
static unsigned uivector_push_back(uivector* p, unsigned c) {
252
0
  if(!uivector_resize(p, p->size + 1)) return 0;
253
0
  p->data[p->size - 1] = c;
254
0
  return 1;
255
0
}
256
#endif /*LODEPNG_COMPILE_ENCODER*/
257
#endif /*LODEPNG_COMPILE_ZLIB*/
258
259
/* /////////////////////////////////////////////////////////////////////////// */
260
261
/*dynamic vector of unsigned chars*/
262
typedef struct ucvector {
263
  unsigned char* data;
264
  size_t size; /*used size*/
265
  size_t allocsize; /*allocated size*/
266
} ucvector;
267
268
/*returns 1 if success, 0 if failure ==> nothing done*/
269
53.8k
static unsigned ucvector_reserve(ucvector* p, size_t size) {
270
53.8k
  if(size > p->allocsize) {
271
30.5k
    size_t newsize = size + (p->allocsize >> 1u);
272
30.5k
    void* data = lodepng_realloc(p->data, newsize);
273
30.5k
    if(data) {
274
29.6k
      p->allocsize = newsize;
275
29.6k
      p->data = (unsigned char*)data;
276
29.6k
    }
277
950
    else return 0; /*error: not enough memory*/
278
30.5k
  }
279
52.9k
  return 1; /*success*/
280
53.8k
}
281
282
/*returns 1 if success, 0 if failure ==> nothing done*/
283
12.4k
static unsigned ucvector_resize(ucvector* p, size_t size) {
284
12.4k
  p->size = size;
285
12.4k
  return ucvector_reserve(p, size);
286
12.4k
}
287
288
9.55k
static ucvector ucvector_init(unsigned char* buffer, size_t size) {
289
9.55k
  ucvector v;
290
9.55k
  v.data = buffer;
291
9.55k
  v.allocsize = v.size = size;
292
9.55k
  return v;
293
9.55k
}
294
295
/* ////////////////////////////////////////////////////////////////////////// */
296
297
#ifdef LODEPNG_COMPILE_PNG
298
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
299
300
/*also appends null termination character*/
301
573k
static char* alloc_string_sized(const char* in, size_t insize) {
302
573k
  char* out = (char*)lodepng_malloc(insize + 1);
303
573k
  if(out) {
304
573k
    lodepng_memcpy(out, in, insize);
305
573k
    out[insize] = 0;
306
573k
  }
307
573k
  return out;
308
573k
}
309
310
/* dynamically allocates a new string with a copy of the null terminated input text */
311
381k
static char* alloc_string(const char* in) {
312
381k
  return alloc_string_sized(in, lodepng_strlen(in));
313
381k
}
314
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
315
#endif /*LODEPNG_COMPILE_PNG*/
316
317
/* ////////////////////////////////////////////////////////////////////////// */
318
319
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)
320
459k
static unsigned lodepng_read32bitInt(const unsigned char* buffer) {
321
459k
  return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) |
322
459k
         ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);
323
459k
}
324
#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/
325
326
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
327
/*buffer must have at least 4 allocated bytes available*/
328
0
static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {
329
0
  buffer[0] = (unsigned char)((value >> 24) & 0xff);
330
0
  buffer[1] = (unsigned char)((value >> 16) & 0xff);
331
0
  buffer[2] = (unsigned char)((value >>  8) & 0xff);
332
0
  buffer[3] = (unsigned char)((value      ) & 0xff);
333
0
}
334
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
335
336
/* ////////////////////////////////////////////////////////////////////////// */
337
/* / File IO                                                                / */
338
/* ////////////////////////////////////////////////////////////////////////// */
339
340
#ifdef LODEPNG_COMPILE_DISK
341
342
/* returns negative value on error. This should be pure C compatible, so no fstat. */
343
0
static long lodepng_filesize(FILE* file) {
344
0
  long size;
345
0
  if(fseek(file, 0, SEEK_END) != 0) return -1;
346
0
  size = ftell(file);
347
  /* It may give LONG_MAX as directory size, this is invalid for us. */
348
0
  if(size == LONG_MAX) return -1;
349
0
  if(fseek(file, 0, SEEK_SET) != 0) return -1;
350
0
  return size;
351
0
}
352
353
/* Allocates the output buffer to the file size and reads the file into it. Returns error code.*/
354
0
static unsigned lodepng_load_file_(unsigned char** out, size_t* outsize, FILE* file) {
355
0
  long size = lodepng_filesize(file);
356
0
  if(size < 0) return 78;
357
0
  *outsize = (size_t)size;
358
0
  *out = (unsigned char*)lodepng_malloc((size_t)size);
359
0
  if(!(*out) && size > 0) return 83; /*the above malloc failed*/
360
0
  if(fread(*out, 1, *outsize, file) != *outsize) return 78;
361
0
  return 0; /*ok*/
362
0
}
363
364
0
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {
365
0
  unsigned error;
366
0
  FILE* file = fopen(filename, "rb");
367
0
  if(!file) return 78;
368
0
  error = lodepng_load_file_(out, outsize, file);
369
0
  fclose(file);
370
0
  return error;
371
0
}
372
373
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
374
0
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {
375
0
  FILE* file = fopen(filename, "wb" );
376
0
  if(!file) return 79;
377
0
  fwrite(buffer, 1, buffersize, file);
378
0
  fclose(file);
379
0
  return 0;
380
0
}
381
382
#endif /*LODEPNG_COMPILE_DISK*/
383
384
/* ////////////////////////////////////////////////////////////////////////// */
385
/* ////////////////////////////////////////////////////////////////////////// */
386
/* // End of common code and tools. Begin of Zlib related code.            // */
387
/* ////////////////////////////////////////////////////////////////////////// */
388
/* ////////////////////////////////////////////////////////////////////////// */
389
390
#ifdef LODEPNG_COMPILE_ZLIB
391
#ifdef LODEPNG_COMPILE_ENCODER
392
393
typedef struct {
394
  ucvector* data;
395
  unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/
396
} LodePNGBitWriter;
397
398
0
static void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) {
399
0
  writer->data = data;
400
0
  writer->bp = 0;
401
0
}
402
403
/*TODO: this ignores potential out of memory errors*/
404
0
#define WRITEBIT(writer, bit){\
405
0
  /* append new byte */\
406
0
  if(((writer->bp) & 7u) == 0) {\
407
0
    if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\
408
0
    writer->data->data[writer->data->size - 1] = 0;\
409
0
  }\
410
0
  (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\
411
0
  ++writer->bp;\
412
0
}
413
414
/* LSB of value is written first, and LSB of bytes is used first */
415
0
static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
416
0
  if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */
417
0
    WRITEBIT(writer, value);
418
0
  } else {
419
    /* TODO: increase output size only once here rather than in each WRITEBIT */
420
0
    size_t i;
421
0
    for(i = 0; i != nbits; ++i) {
422
0
      WRITEBIT(writer, (unsigned char)((value >> i) & 1));
423
0
    }
424
0
  }
425
0
}
426
427
/* This one is to use for adding huffman symbol, the value bits are written MSB first */
428
0
static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
429
0
  size_t i;
430
0
  for(i = 0; i != nbits; ++i) {
431
    /* TODO: increase output size only once here rather than in each WRITEBIT */
432
0
    WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u));
433
0
  }
434
0
}
435
#endif /*LODEPNG_COMPILE_ENCODER*/
436
437
#ifdef LODEPNG_COMPILE_DECODER
438
439
typedef struct {
440
  const unsigned char* data;
441
  size_t size; /*size of data in bytes*/
442
  size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/
443
  size_t bp;
444
  unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/
445
} LodePNGBitReader;
446
447
/* data size argument is in bytes. Returns error if size too large causing overflow */
448
8.84k
static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) {
449
8.84k
  size_t temp;
450
8.84k
  reader->data = data;
451
8.84k
  reader->size = size;
452
  /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB)  */
453
8.84k
  if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;
454
  /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and
455
  trying to ensure 32 more bits*/
456
8.84k
  if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;
457
8.84k
  reader->bp = 0;
458
8.84k
  reader->buffer = 0;
459
8.84k
  return 0; /*ok*/
460
8.84k
}
461
462
/*
463
ensureBits functions:
464
Ensures the reader can at least read nbits bits in one or more readBits calls,
465
safely even if not enough bits are available.
466
The nbits parameter is unused but is given for documentation purposes, error
467
checking for amount of bits must be done beforehand.
468
*/
469
470
/*See ensureBits documentation above. This one ensures up to 9 bits */
471
136k
static LODEPNG_INLINE void ensureBits9(LodePNGBitReader* reader, size_t nbits) {
472
136k
  size_t start = reader->bp >> 3u;
473
136k
  size_t size = reader->size;
474
136k
  if(start + 1u < size) {
475
136k
    reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u);
476
136k
    reader->buffer >>= (reader->bp & 7u);
477
136k
  } else {
478
173
    reader->buffer = 0;
479
173
    if(start + 0u < size) reader->buffer = reader->data[start + 0];
480
173
    reader->buffer >>= (reader->bp & 7u);
481
173
  }
482
136k
  (void)nbits;
483
136k
}
484
485
/*See ensureBits documentation above. This one ensures up to 17 bits */
486
6.74k
static LODEPNG_INLINE void ensureBits17(LodePNGBitReader* reader, size_t nbits) {
487
6.74k
  size_t start = reader->bp >> 3u;
488
6.74k
  size_t size = reader->size;
489
6.74k
  if(start + 2u < size) {
490
6.72k
    reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
491
6.72k
                     ((unsigned)reader->data[start + 2] << 16u);
492
6.72k
    reader->buffer >>= (reader->bp & 7u);
493
6.72k
  } else {
494
23
    reader->buffer = 0;
495
23
    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
496
23
    if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
497
23
    reader->buffer >>= (reader->bp & 7u);
498
23
  }
499
6.74k
  (void)nbits;
500
6.74k
}
501
502
/*See ensureBits documentation above. This one ensures up to 25 bits */
503
2.56M
static LODEPNG_INLINE void ensureBits25(LodePNGBitReader* reader, size_t nbits) {
504
2.56M
  size_t start = reader->bp >> 3u;
505
2.56M
  size_t size = reader->size;
506
2.56M
  if(start + 3u < size) {
507
2.56M
    reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
508
2.56M
                     ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
509
2.56M
    reader->buffer >>= (reader->bp & 7u);
510
2.56M
  } else {
511
6.71k
    reader->buffer = 0;
512
6.71k
    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
513
6.71k
    if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
514
6.71k
    if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
515
6.71k
    reader->buffer >>= (reader->bp & 7u);
516
6.71k
  }
517
2.56M
  (void)nbits;
518
2.56M
}
519
520
/*See ensureBits documentation above. This one ensures up to 32 bits */
521
39.8M
static LODEPNG_INLINE void ensureBits32(LodePNGBitReader* reader, size_t nbits) {
522
39.8M
  size_t start = reader->bp >> 3u;
523
39.8M
  size_t size = reader->size;
524
39.8M
  if(start + 4u < size) {
525
39.7M
    reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
526
39.7M
                     ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
527
39.7M
    reader->buffer >>= (reader->bp & 7u);
528
39.7M
    reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u)));
529
39.7M
  } else {
530
32.1k
    reader->buffer = 0;
531
32.1k
    if(start + 0u < size) reader->buffer |= reader->data[start + 0];
532
32.1k
    if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
533
32.1k
    if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
534
32.1k
    if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u);
535
32.1k
    reader->buffer >>= (reader->bp & 7u);
536
32.1k
  }
537
39.8M
  (void)nbits;
538
39.8M
}
539
540
/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */
541
53.1M
static LODEPNG_INLINE unsigned peekBits(LodePNGBitReader* reader, size_t nbits) {
542
  /* The shift allows nbits to be only up to 31. */
543
53.1M
  return reader->buffer & ((1u << nbits) - 1u);
544
53.1M
}
545
546
/* Must have enough bits available with ensureBits */
547
53.1M
static LODEPNG_INLINE void advanceBits(LodePNGBitReader* reader, size_t nbits) {
548
53.1M
  reader->buffer >>= nbits;
549
53.1M
  reader->bp += nbits;
550
53.1M
}
551
552
/* Must have enough bits available with ensureBits */
553
7.00M
static LODEPNG_INLINE unsigned readBits(LodePNGBitReader* reader, size_t nbits) {
554
7.00M
  unsigned result = peekBits(reader, nbits);
555
7.00M
  advanceBits(reader, nbits);
556
7.00M
  return result;
557
7.00M
}
558
#endif /*LODEPNG_COMPILE_DECODER*/
559
560
6.40M
static unsigned reverseBits(unsigned bits, unsigned num) {
561
  /*TODO: implement faster lookup table based version when needed*/
562
6.40M
  unsigned i, result = 0;
563
56.8M
  for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;
564
6.40M
  return result;
565
6.40M
}
566
567
/* ////////////////////////////////////////////////////////////////////////// */
568
/* / Deflate - Huffman                                                      / */
569
/* ////////////////////////////////////////////////////////////////////////// */
570
571
72.5M
#define FIRST_LENGTH_CODE_INDEX 257
572
18.1M
#define LAST_LENGTH_CODE_INDEX 285
573
/*256 literals, the end code, some length codes, and 2 unused codes*/
574
57.2k
#define NUM_DEFLATE_CODE_SYMBOLS 288
575
/*the distance codes have their own symbols, 30 used, 2 unused*/
576
676k
#define NUM_DISTANCE_SYMBOLS 32
577
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
578
42.2k
#define NUM_CODE_LENGTH_CODES 19
579
580
/*the base lengths represented by codes 257-285*/
581
static const unsigned LENGTHBASE[29]
582
  = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
583
     67, 83, 99, 115, 131, 163, 195, 227, 258};
584
585
/*the extra bits used by codes 257-285 (added to base length)*/
586
static const unsigned LENGTHEXTRA[29]
587
  = {0, 0, 0, 0, 0, 0, 0,  0,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,
588
      4,  4,  4,   4,   5,   5,   5,   5,   0};
589
590
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
591
static const unsigned DISTANCEBASE[30]
592
  = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
593
     769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
594
595
/*the extra bits of backwards distances (added to base)*/
596
static const unsigned DISTANCEEXTRA[30]
597
  = {0, 0, 0, 0, 1, 1, 2,  2,  3,  3,  4,  4,  5,  5,   6,   6,   7,   7,   8,
598
       8,    9,    9,   10,   10,   11,   11,   12,    12,    13,    13};
599
600
/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman
601
tree of the dynamic huffman tree lengths is generated*/
602
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
603
  = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
604
605
/* ////////////////////////////////////////////////////////////////////////// */
606
607
/*
608
Huffman tree struct, containing multiple representations of the tree
609
*/
610
typedef struct HuffmanTree {
611
  unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/
612
  unsigned* lengths; /*the lengths of the huffman codes*/
613
  unsigned maxbitlen; /*maximum number of bits a single code can get*/
614
  unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
615
  /* for reading only */
616
  unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/
617
  unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/
618
} HuffmanTree;
619
620
57.8k
static void HuffmanTree_init(HuffmanTree* tree) {
621
57.8k
  tree->codes = 0;
622
57.8k
  tree->lengths = 0;
623
57.8k
  tree->table_len = 0;
624
57.8k
  tree->table_value = 0;
625
57.8k
}
626
627
57.8k
static void HuffmanTree_cleanup(HuffmanTree* tree) {
628
57.8k
  lodepng_free(tree->codes);
629
57.8k
  lodepng_free(tree->lengths);
630
57.8k
  lodepng_free(tree->table_len);
631
57.8k
  lodepng_free(tree->table_value);
632
57.8k
}
633
634
/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/
635
/* values 8u and 9u work the fastest */
636
172M
#define FIRSTBITS 9u
637
638
/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination,
639
which is possible in case of only 0 or 1 present symbols. */
640
990k
#define INVALIDSYMBOL 65535u
641
642
/* make table for huffman decoding */
643
57.1k
static unsigned HuffmanTree_makeTable(HuffmanTree* tree) {
644
57.1k
  static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/
645
57.1k
  static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;
646
57.1k
  size_t i, numpresent, pointer, size; /*total table size*/
647
57.1k
  unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned));
648
57.1k
  if(!maxlens) return 83; /*alloc fail*/
649
650
  /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/
651
57.1k
  lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens));
652
8.26M
  for(i = 0; i < tree->numcodes; i++) {
653
8.20M
    unsigned symbol = tree->codes[i];
654
8.20M
    unsigned l = tree->lengths[i];
655
8.20M
    unsigned index;
656
8.20M
    if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/
657
    /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/
658
47.9k
    index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);
659
47.9k
    maxlens[index] = LODEPNG_MAX(maxlens[index], l);
660
47.9k
  }
661
  /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */
662
57.1k
  size = headsize;
663
29.3M
  for(i = 0; i < headsize; ++i) {
664
29.2M
    unsigned l = maxlens[i];
665
29.2M
    if(l > FIRSTBITS) size += (((size_t)1) << (l - FIRSTBITS));
666
29.2M
  }
667
57.1k
  tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len));
668
57.1k
  tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value));
669
57.1k
  if(!tree->table_len || !tree->table_value) {
670
0
    lodepng_free(maxlens);
671
    /* freeing tree->table values is done at a higher scope */
672
0
    return 83; /*alloc fail*/
673
0
  }
674
  /*initialize with an invalid length to indicate unused entries*/
675
29.3M
  for(i = 0; i < size; ++i) tree->table_len[i] = 16;
676
677
  /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/
678
57.1k
  pointer = headsize;
679
29.3M
  for(i = 0; i < headsize; ++i) {
680
29.2M
    unsigned l = maxlens[i];
681
29.2M
    if(l <= FIRSTBITS) continue;
682
20.4k
    tree->table_len[i] = l;
683
20.4k
    tree->table_value[i] = (unsigned short)pointer;
684
20.4k
    pointer += (((size_t)1) << (l - FIRSTBITS));
685
20.4k
  }
686
57.1k
  lodepng_free(maxlens);
687
688
  /*fill in the first table for short symbols, or secondary table for long symbols*/
689
57.1k
  numpresent = 0;
690
8.26M
  for(i = 0; i < tree->numcodes; ++i) {
691
8.20M
    unsigned l = tree->lengths[i];
692
8.20M
    unsigned symbol, reverse;
693
8.20M
    if(l == 0) continue;
694
6.35M
    symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/
695
    /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/
696
6.35M
    reverse = reverseBits(symbol, l);
697
6.35M
    numpresent++;
698
699
6.35M
    if(l <= FIRSTBITS) {
700
      /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/
701
6.30M
      unsigned num = 1u << (FIRSTBITS - l);
702
6.30M
      unsigned j;
703
34.5M
      for(j = 0; j < num; ++j) {
704
        /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/
705
28.2M
        unsigned index = reverse | (j << l);
706
28.2M
        if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
707
28.2M
        tree->table_len[index] = l;
708
28.2M
        tree->table_value[index] = (unsigned short)i;
709
28.2M
      }
710
6.30M
    } else {
711
      /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/
712
      /*the FIRSTBITS MSBs of the symbol are the first table index*/
713
47.8k
      unsigned index = reverse & mask;
714
47.8k
      unsigned maxlen = tree->table_len[index];
715
      /*log2 of secondary table length, should be >= l - FIRSTBITS*/
716
47.8k
      unsigned tablelen = maxlen - FIRSTBITS;
717
47.8k
      unsigned start = tree->table_value[index]; /*starting index in secondary table*/
718
47.8k
      unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/
719
47.8k
      unsigned j;
720
47.8k
      if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
721
98.8k
      for(j = 0; j < num; ++j) {
722
50.9k
        unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */
723
50.9k
        unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));
724
50.9k
        tree->table_len[index2] = l;
725
50.9k
        tree->table_value[index2] = (unsigned short)i;
726
50.9k
      }
727
47.8k
    }
728
6.35M
  }
729
730
57.0k
  if(numpresent < 2) {
731
    /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits,
732
    but deflate uses 1 bit instead. In case of 0 symbols, no symbols can
733
    appear at all, but such huffman tree could still exist (e.g. if distance
734
    codes are never used). In both cases, not all symbols of the table will be
735
    filled in. Fill them in with an invalid symbol value so returning them from
736
    huffmanDecodeSymbol will cause error. */
737
1.14M
    for(i = 0; i < size; ++i) {
738
1.13M
      if(tree->table_len[i] == 16) {
739
        /* As length, use a value smaller than FIRSTBITS for the head table,
740
        and a value larger than FIRSTBITS for the secondary table, to ensure
741
        valid behavior for advanceBits when reading this symbol. */
742
990k
        tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1);
743
990k
        tree->table_value[i] = INVALIDSYMBOL;
744
990k
      }
745
1.13M
    }
746
54.8k
  } else {
747
    /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
748
    If that is not the case (due to too long length codes), the table will not
749
    have been fully used, and this is an error (not all bit combinations can be
750
    decoded): an oversubscribed huffman tree, indicated by error 55. */
751
28.1M
    for(i = 0; i < size; ++i) {
752
28.1M
      if(tree->table_len[i] == 16) return 55;
753
28.1M
    }
754
54.8k
  }
755
756
57.0k
  return 0;
757
57.0k
}
758
759
/*
760
Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
761
numcodes, lengths and maxbitlen must already be filled in correctly. return
762
value is error.
763
*/
764
57.1k
static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {
765
57.1k
  unsigned* blcount;
766
57.1k
  unsigned* nextcode;
767
57.1k
  unsigned error = 0;
768
57.1k
  unsigned bits, n;
769
770
57.1k
  tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
771
57.1k
  blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
772
57.1k
  nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
773
57.1k
  if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/
774
775
57.1k
  if(!error) {
776
917k
    for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;
777
    /*step 1: count number of instances of each code length*/
778
8.26M
    for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];
779
    /*step 2: generate the nextcode values*/
780
860k
    for(bits = 1; bits <= tree->maxbitlen; ++bits) {
781
803k
      nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u;
782
803k
    }
783
    /*step 3: generate all the codes*/
784
8.26M
    for(n = 0; n != tree->numcodes; ++n) {
785
8.20M
      if(tree->lengths[n] != 0) {
786
6.35M
        tree->codes[n] = nextcode[tree->lengths[n]]++;
787
        /*remove superfluous bits from the code*/
788
6.35M
        tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);
789
6.35M
      }
790
8.20M
    }
791
57.1k
  }
792
793
57.1k
  lodepng_free(blcount);
794
57.1k
  lodepng_free(nextcode);
795
796
57.1k
  if(!error) error = HuffmanTree_makeTable(tree);
797
57.1k
  return error;
798
57.1k
}
799
800
/*
801
given the code lengths (as stored in the PNG file), generate the tree as defined
802
by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
803
return value is error.
804
*/
805
static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
806
57.1k
                                            size_t numcodes, unsigned maxbitlen) {
807
57.1k
  unsigned i;
808
57.1k
  tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
809
57.1k
  if(!tree->lengths) return 83; /*alloc fail*/
810
8.26M
  for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
811
57.1k
  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
812
57.1k
  tree->maxbitlen = maxbitlen;
813
57.1k
  return HuffmanTree_makeFromLengths2(tree);
814
57.1k
}
815
816
#ifdef LODEPNG_COMPILE_ENCODER
817
818
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
819
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
820
821
/*chain node for boundary package merge*/
822
typedef struct BPMNode {
823
  int weight; /*the sum of all weights in this chain*/
824
  unsigned index; /*index of this leaf node (called "count" in the paper)*/
825
  struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
826
  int in_use;
827
} BPMNode;
828
829
/*lists of chains*/
830
typedef struct BPMLists {
831
  /*memory pool*/
832
  unsigned memsize;
833
  BPMNode* memory;
834
  unsigned numfree;
835
  unsigned nextfree;
836
  BPMNode** freelist;
837
  /*two heads of lookahead chains per list*/
838
  unsigned listsize;
839
  BPMNode** chains0;
840
  BPMNode** chains1;
841
} BPMLists;
842
843
/*creates a new chain node with the given parameters, from the memory in the lists */
844
0
static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {
845
0
  unsigned i;
846
0
  BPMNode* result;
847
848
  /*memory full, so garbage collect*/
849
0
  if(lists->nextfree >= lists->numfree) {
850
    /*mark only those that are in use*/
851
0
    for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
852
0
    for(i = 0; i != lists->listsize; ++i) {
853
0
      BPMNode* node;
854
0
      for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
855
0
      for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
856
0
    }
857
    /*collect those that are free*/
858
0
    lists->numfree = 0;
859
0
    for(i = 0; i != lists->memsize; ++i) {
860
0
      if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
861
0
    }
862
0
    lists->nextfree = 0;
863
0
  }
864
865
0
  result = lists->freelist[lists->nextfree++];
866
0
  result->weight = weight;
867
0
  result->index = index;
868
0
  result->tail = tail;
869
0
  return result;
870
0
}
871
872
/*sort the leaves with stable mergesort*/
873
0
static void bpmnode_sort(BPMNode* leaves, size_t num) {
874
0
  BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
875
0
  size_t width, counter = 0;
876
0
  for(width = 1; width < num; width *= 2) {
877
0
    BPMNode* a = (counter & 1) ? mem : leaves;
878
0
    BPMNode* b = (counter & 1) ? leaves : mem;
879
0
    size_t p;
880
0
    for(p = 0; p < num; p += 2 * width) {
881
0
      size_t q = (p + width > num) ? num : (p + width);
882
0
      size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
883
0
      size_t i = p, j = q, k;
884
0
      for(k = p; k < r; k++) {
885
0
        if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
886
0
        else b[k] = a[j++];
887
0
      }
888
0
    }
889
0
    counter++;
890
0
  }
891
0
  if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num);
892
0
  lodepng_free(mem);
893
0
}
894
895
/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
896
0
static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {
897
0
  unsigned lastindex = lists->chains1[c]->index;
898
899
0
  if(c == 0) {
900
0
    if(lastindex >= numpresent) return;
901
0
    lists->chains0[c] = lists->chains1[c];
902
0
    lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
903
0
  } else {
904
    /*sum of the weights of the head nodes of the previous lookahead chains.*/
905
0
    int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
906
0
    lists->chains0[c] = lists->chains1[c];
907
0
    if(lastindex < numpresent && sum > leaves[lastindex].weight) {
908
0
      lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
909
0
      return;
910
0
    }
911
0
    lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
912
    /*in the end we are only interested in the chain of the last list, so no
913
    need to recurse if we're at the last one (this gives measurable speedup)*/
914
0
    if(num + 1 < (int)(2 * numpresent - 2)) {
915
0
      boundaryPM(lists, leaves, numpresent, c - 1, num);
916
0
      boundaryPM(lists, leaves, numpresent, c - 1, num);
917
0
    }
918
0
  }
919
0
}
920
921
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
922
0
                                      size_t numcodes, unsigned maxbitlen) {
923
0
  unsigned error = 0;
924
0
  unsigned i;
925
0
  size_t numpresent = 0; /*number of symbols with non-zero frequency*/
926
0
  BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
927
928
0
  if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
929
0
  if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
930
931
0
  leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
932
0
  if(!leaves) return 83; /*alloc fail*/
933
934
0
  for(i = 0; i != numcodes; ++i) {
935
0
    if(frequencies[i] > 0) {
936
0
      leaves[numpresent].weight = (int)frequencies[i];
937
0
      leaves[numpresent].index = i;
938
0
      ++numpresent;
939
0
    }
940
0
  }
941
942
0
  lodepng_memset(lengths, 0, numcodes * sizeof(*lengths));
943
944
  /*ensure at least two present symbols. There should be at least one symbol
945
  according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
946
  make these work as well ensure there are at least two symbols. The
947
  Package-Merge code below also doesn't work correctly if there's only one
948
  symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/
949
0
  if(numpresent == 0) {
950
0
    lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
951
0
  } else if(numpresent == 1) {
952
0
    lengths[leaves[0].index] = 1;
953
0
    lengths[leaves[0].index == 0 ? 1 : 0] = 1;
954
0
  } else {
955
0
    BPMLists lists;
956
0
    BPMNode* node;
957
958
0
    bpmnode_sort(leaves, numpresent);
959
960
0
    lists.listsize = maxbitlen;
961
0
    lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
962
0
    lists.nextfree = 0;
963
0
    lists.numfree = lists.memsize;
964
0
    lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
965
0
    lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
966
0
    lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
967
0
    lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
968
0
    if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
969
970
0
    if(!error) {
971
0
      for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
972
973
0
      bpmnode_create(&lists, leaves[0].weight, 1, 0);
974
0
      bpmnode_create(&lists, leaves[1].weight, 2, 0);
975
976
0
      for(i = 0; i != lists.listsize; ++i) {
977
0
        lists.chains0[i] = &lists.memory[0];
978
0
        lists.chains1[i] = &lists.memory[1];
979
0
      }
980
981
      /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
982
0
      for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
983
984
0
      for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
985
0
        for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
986
0
      }
987
0
    }
988
989
0
    lodepng_free(lists.memory);
990
0
    lodepng_free(lists.freelist);
991
0
    lodepng_free(lists.chains0);
992
0
    lodepng_free(lists.chains1);
993
0
  }
994
995
0
  lodepng_free(leaves);
996
0
  return error;
997
0
}
998
999
/*Create the Huffman tree given the symbol frequencies*/
1000
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
1001
0
                                                size_t mincodes, size_t numcodes, unsigned maxbitlen) {
1002
0
  unsigned error = 0;
1003
0
  while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
1004
0
  tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
1005
0
  if(!tree->lengths) return 83; /*alloc fail*/
1006
0
  tree->maxbitlen = maxbitlen;
1007
0
  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
1008
1009
0
  error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
1010
0
  if(!error) error = HuffmanTree_makeFromLengths2(tree);
1011
0
  return error;
1012
0
}
1013
#endif /*LODEPNG_COMPILE_ENCODER*/
1014
1015
/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
1016
18.7k
static unsigned generateFixedLitLenTree(HuffmanTree* tree) {
1017
18.7k
  unsigned i, error = 0;
1018
18.7k
  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
1019
18.7k
  if(!bitlen) return 83; /*alloc fail*/
1020
1021
  /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
1022
2.72M
  for(i =   0; i <= 143; ++i) bitlen[i] = 8;
1023
2.12M
  for(i = 144; i <= 255; ++i) bitlen[i] = 9;
1024
469k
  for(i = 256; i <= 279; ++i) bitlen[i] = 7;
1025
169k
  for(i = 280; i <= 287; ++i) bitlen[i] = 8;
1026
1027
18.7k
  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
1028
1029
18.7k
  lodepng_free(bitlen);
1030
18.7k
  return error;
1031
18.7k
}
1032
1033
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
1034
18.7k
static unsigned generateFixedDistanceTree(HuffmanTree* tree) {
1035
18.7k
  unsigned i, error = 0;
1036
18.7k
  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
1037
18.7k
  if(!bitlen) return 83; /*alloc fail*/
1038
1039
  /*there are 32 distance codes, but 30-31 are unused*/
1040
619k
  for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
1041
18.7k
  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
1042
1043
18.7k
  lodepng_free(bitlen);
1044
18.7k
  return error;
1045
18.7k
}
1046
1047
#ifdef LODEPNG_COMPILE_DECODER
1048
1049
/*
1050
returns the code. The bit reader must already have been ensured at least 15 bits
1051
*/
1052
46.0M
static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) {
1053
46.0M
  unsigned short code = peekBits(reader, FIRSTBITS);
1054
46.0M
  unsigned short l = codetree->table_len[code];
1055
46.0M
  unsigned short value = codetree->table_value[code];
1056
46.0M
  if(l <= FIRSTBITS) {
1057
45.8M
    advanceBits(reader, l);
1058
45.8M
    return value;
1059
45.8M
  } else {
1060
159k
    advanceBits(reader, FIRSTBITS);
1061
159k
    value += peekBits(reader, l - FIRSTBITS);
1062
159k
    advanceBits(reader, codetree->table_len[value] - FIRSTBITS);
1063
159k
    return codetree->table_value[value];
1064
159k
  }
1065
46.0M
}
1066
#endif /*LODEPNG_COMPILE_DECODER*/
1067
1068
#ifdef LODEPNG_COMPILE_DECODER
1069
1070
/* ////////////////////////////////////////////////////////////////////////// */
1071
/* / Inflator (Decompressor)                                                / */
1072
/* ////////////////////////////////////////////////////////////////////////// */
1073
1074
/*get the tree of a deflated block with fixed tree, as specified in the deflate specification
1075
Returns error code.*/
1076
18.7k
static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {
1077
18.7k
  unsigned error = generateFixedLitLenTree(tree_ll);
1078
18.7k
  if(error) return error;
1079
18.7k
  return generateFixedDistanceTree(tree_d);
1080
18.7k
}
1081
1082
/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
1083
static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
1084
6.76k
                                      LodePNGBitReader* reader) {
1085
  /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
1086
6.76k
  unsigned error = 0;
1087
6.76k
  unsigned n, HLIT, HDIST, HCLEN, i;
1088
1089
  /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
1090
6.76k
  unsigned* bitlen_ll = 0; /*lit,len code lengths*/
1091
6.76k
  unsigned* bitlen_d = 0; /*dist code lengths*/
1092
  /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
1093
6.76k
  unsigned* bitlen_cl = 0;
1094
6.76k
  HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
1095
1096
6.76k
  if(reader->bitsize - reader->bp < 14) return 49; /*error: the bit pointer is or will go past the memory*/
1097
6.74k
  ensureBits17(reader, 14);
1098
1099
  /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
1100
6.74k
  HLIT =  readBits(reader, 5) + 257;
1101
  /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
1102
6.74k
  HDIST = readBits(reader, 5) + 1;
1103
  /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
1104
6.74k
  HCLEN = readBits(reader, 4) + 4;
1105
1106
6.74k
  bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
1107
6.74k
  if(!bitlen_cl) return 83 /*alloc fail*/;
1108
1109
6.74k
  HuffmanTree_init(&tree_cl);
1110
1111
6.74k
  while(!error) {
1112
    /*read the code length codes out of 3 * (amount of code length codes) bits*/
1113
6.74k
    if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {
1114
48
      ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/
1115
0
    }
1116
111k
    for(i = 0; i != HCLEN; ++i) {
1117
105k
      ensureBits9(reader, 3); /*out of bounds already checked above */
1118
105k
      bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);
1119
105k
    }
1120
28.8k
    for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {
1121
22.1k
      bitlen_cl[CLCL_ORDER[i]] = 0;
1122
22.1k
    }
1123
1124
6.69k
    error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
1125
6.69k
    if(error) break;
1126
1127
    /*now we can use this tree to read the lengths for the tree that this function will return*/
1128
6.62k
    bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
1129
6.62k
    bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
1130
6.62k
    if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
1131
6.62k
    lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll));
1132
6.62k
    lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d));
1133
1134
    /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1135
6.62k
    i = 0;
1136
393k
    while(i < HLIT + HDIST) {
1137
387k
      unsigned code;
1138
387k
      ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/
1139
387k
      code = huffmanDecodeSymbol(reader, &tree_cl);
1140
387k
      if(code <= 15) /*a length code*/ {
1141
336k
        if(i < HLIT) bitlen_ll[i] = code;
1142
95.8k
        else bitlen_d[i - HLIT] = code;
1143
336k
        ++i;
1144
336k
      } else if(code == 16) /*repeat previous*/ {
1145
7.30k
        unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1146
7.30k
        unsigned value; /*set value to the previous code*/
1147
1148
7.30k
        if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1149
1150
7.30k
        replength += readBits(reader, 2);
1151
1152
7.30k
        if(i < HLIT + 1) value = bitlen_ll[i - 1];
1153
1.50k
        else value = bitlen_d[i - HLIT - 1];
1154
        /*repeat this value in the next lengths*/
1155
36.7k
        for(n = 0; n < replength; ++n) {
1156
29.4k
          if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1157
29.4k
          if(i < HLIT) bitlen_ll[i] = value;
1158
4.72k
          else bitlen_d[i - HLIT] = value;
1159
29.4k
          ++i;
1160
29.4k
        }
1161
43.5k
      } else if(code == 17) /*repeat "0" 3-10 times*/ {
1162
24.9k
        unsigned replength = 3; /*read in the bits that indicate repeat length*/
1163
24.9k
        replength += readBits(reader, 3);
1164
1165
        /*repeat this value in the next lengths*/
1166
139k
        for(n = 0; n < replength; ++n) {
1167
114k
          if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1168
1169
114k
          if(i < HLIT) bitlen_ll[i] = 0;
1170
13.5k
          else bitlen_d[i - HLIT] = 0;
1171
114k
          ++i;
1172
114k
        }
1173
24.9k
      } else if(code == 18) /*repeat "0" 11-138 times*/ {
1174
18.5k
        unsigned replength = 11; /*read in the bits that indicate repeat length*/
1175
18.5k
        replength += readBits(reader, 7);
1176
1177
        /*repeat this value in the next lengths*/
1178
1.51M
        for(n = 0; n < replength; ++n) {
1179
1.49M
          if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1180
1181
1.49M
          if(i < HLIT) bitlen_ll[i] = 0;
1182
18.5k
          else bitlen_d[i - HLIT] = 0;
1183
1.49M
          ++i;
1184
1.49M
        }
1185
18.5k
      } else /*if(code == INVALIDSYMBOL)*/ {
1186
19
        ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
1187
0
      }
1188
      /*check if any of the ensureBits above went out of bounds*/
1189
387k
      if(reader->bp > reader->bitsize) {
1190
        /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1191
        (10=no endcode, 11=wrong jump outside of tree)*/
1192
        /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
1193
123
        ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1194
0
      }
1195
387k
    }
1196
6.62k
    if(error) break;
1197
1198
6.47k
    if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1199
1200
    /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1201
6.46k
    error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
1202
6.46k
    if(error) break;
1203
6.41k
    error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
1204
1205
6.41k
    break; /*end of error-while*/
1206
6.46k
  }
1207
1208
6.74k
  lodepng_free(bitlen_cl);
1209
6.74k
  lodepng_free(bitlen_ll);
1210
6.74k
  lodepng_free(bitlen_d);
1211
6.74k
  HuffmanTree_cleanup(&tree_cl);
1212
1213
6.74k
  return error;
1214
6.74k
}
1215
1216
/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/
1217
static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader,
1218
25.5k
                                    unsigned btype, size_t max_output_size) {
1219
25.5k
  unsigned error = 0;
1220
25.5k
  HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
1221
25.5k
  HuffmanTree tree_d; /*the huffman tree for distance codes*/
1222
25.5k
  const size_t reserved_size = 260; /* must be at least 258 for max length, and a few extra for adding a few extra literals */
1223
25.5k
  int done = 0;
1224
1225
25.5k
  if(!ucvector_reserve(out, out->size + reserved_size)) return 83; /*alloc fail*/
1226
1227
25.5k
  HuffmanTree_init(&tree_ll);
1228
25.5k
  HuffmanTree_init(&tree_d);
1229
1230
25.5k
  if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d);
1231
6.76k
  else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);
1232
1233
1234
21.6M
  while(!error && !done) /*decode all symbols until end reached, breaks at end code*/ {
1235
    /*code_ll is literal, length or end code*/
1236
21.6M
    unsigned code_ll;
1237
    /* ensure enough bits for 2 huffman code reads (15 bits each): if the first is a literal, a second literal is read at once. This
1238
    appears to be slightly faster, than ensuring 20 bits here for 1 huffman symbol and the potential 5 extra bits for the length symbol.*/
1239
21.6M
    ensureBits32(reader, 30);
1240
21.6M
    code_ll = huffmanDecodeSymbol(reader, &tree_ll);
1241
21.6M
    if(code_ll <= 255) {
1242
      /*slightly faster code path if multiple literals in a row*/
1243
5.81M
      out->data[out->size++] = (unsigned char)code_ll;
1244
5.81M
      code_ll = huffmanDecodeSymbol(reader, &tree_ll);
1245
5.81M
    }
1246
21.6M
    if(code_ll <= 255) /*literal symbol*/ {
1247
3.51M
      out->data[out->size++] = (unsigned char)code_ll;
1248
18.1M
    } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {
1249
18.1M
      unsigned code_d, distance;
1250
18.1M
      unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
1251
18.1M
      size_t start, backward, length;
1252
1253
      /*part 1: get length base*/
1254
18.1M
      length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
1255
1256
      /*part 2: get extra bits and add the value of that to length*/
1257
18.1M
      numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
1258
18.1M
      if(numextrabits_l != 0) {
1259
        /* bits already ensured above */
1260
2.18M
        ensureBits25(reader, 5);
1261
2.18M
        length += readBits(reader, numextrabits_l);
1262
2.18M
      }
1263
1264
      /*part 3: get distance code*/
1265
18.1M
      ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */
1266
18.1M
      code_d = huffmanDecodeSymbol(reader, &tree_d);
1267
18.1M
      if(code_d > 29) {
1268
9
        if(code_d <= 31) {
1269
4
          ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/
1270
5
        } else /* if(code_d == INVALIDSYMBOL) */{
1271
5
          ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
1272
0
        }
1273
9
      }
1274
18.1M
      distance = DISTANCEBASE[code_d];
1275
1276
      /*part 4: get extra bits from distance*/
1277
18.1M
      numextrabits_d = DISTANCEEXTRA[code_d];
1278
18.1M
      if(numextrabits_d != 0) {
1279
        /* bits already ensured above */
1280
4.58M
        distance += readBits(reader, numextrabits_d);
1281
4.58M
      }
1282
1283
      /*part 5: fill in all the out[n] values based on the length and dist*/
1284
18.1M
      start = out->size;
1285
18.1M
      if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
1286
18.1M
      backward = start - distance;
1287
1288
18.1M
      out->size += length;
1289
18.1M
      if(distance < length) {
1290
14.0M
        size_t forward;
1291
14.0M
        lodepng_memcpy(out->data + start, out->data + backward, distance);
1292
14.0M
        start += distance;
1293
3.50G
        for(forward = distance; forward < length; ++forward) {
1294
3.49G
          out->data[start++] = out->data[backward++];
1295
3.49G
        }
1296
14.0M
      } else {
1297
4.04M
        lodepng_memcpy(out->data + start, out->data + backward, length);
1298
4.04M
      }
1299
18.1M
    } else if(code_ll == 256) {
1300
24.8k
      done = 1; /*end code, finish the loop*/
1301
24.8k
    } else /*if(code_ll == INVALIDSYMBOL)*/ {
1302
11
      ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
1303
0
    }
1304
21.6M
    if(out->allocsize - out->size < reserved_size) {
1305
15.8k
      if(!ucvector_reserve(out, out->size + reserved_size)) ERROR_BREAK(83); /*alloc fail*/
1306
15.8k
    }
1307
    /*check if any of the ensureBits above went out of bounds*/
1308
21.6M
    if(reader->bp > reader->bitsize) {
1309
      /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1310
      (10=no endcode, 11=wrong jump outside of tree)*/
1311
      /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
1312
282
      ERROR_BREAK(51); /*error, bit pointer jumps past memory*/
1313
0
    }
1314
21.6M
    if(max_output_size && out->size > max_output_size) {
1315
20
      ERROR_BREAK(109); /*error, larger than max size*/
1316
0
    }
1317
21.6M
  }
1318
1319
25.5k
  HuffmanTree_cleanup(&tree_ll);
1320
25.5k
  HuffmanTree_cleanup(&tree_d);
1321
1322
25.5k
  return error;
1323
25.5k
}
1324
1325
static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader,
1326
5.63k
                                     const LodePNGDecompressSettings* settings) {
1327
5.63k
  size_t bytepos;
1328
5.63k
  size_t size = reader->size;
1329
5.63k
  unsigned LEN, NLEN, error = 0;
1330
1331
  /*go to first boundary of byte*/
1332
5.63k
  bytepos = (reader->bp + 7u) >> 3u;
1333
1334
  /*read LEN (2 bytes) and NLEN (2 bytes)*/
1335
5.63k
  if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/
1336
5.60k
  LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
1337
5.60k
  NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
1338
1339
  /*check if 16-bit NLEN is really the one's complement of LEN*/
1340
5.60k
  if(!settings->ignore_nlen && LEN + NLEN != 65535) {
1341
0
    return 21; /*error: NLEN is not one's complement of LEN*/
1342
0
  }
1343
1344
5.60k
  if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/
1345
1346
  /*read the literal data: LEN bytes are now stored in the out buffer*/
1347
5.60k
  if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/
1348
1349
  /*out->data can be NULL (when LEN is zero), and arithmetics on NULL ptr is undefined*/
1350
5.46k
  if (LEN) {
1351
701
    lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN);
1352
701
    bytepos += LEN;
1353
701
  }
1354
1355
5.46k
  reader->bp = bytepos << 3u;
1356
1357
5.46k
  return error;
1358
5.60k
}
1359
1360
static unsigned lodepng_inflatev(ucvector* out,
1361
                                 const unsigned char* in, size_t insize,
1362
8.84k
                                 const LodePNGDecompressSettings* settings) {
1363
8.84k
  unsigned BFINAL = 0;
1364
8.84k
  LodePNGBitReader reader;
1365
8.84k
  unsigned error = LodePNGBitReader_init(&reader, in, insize);
1366
1367
8.84k
  if(error) return error;
1368
1369
39.1k
  while(!BFINAL) {
1370
31.2k
    unsigned BTYPE;
1371
31.2k
    if(reader.bitsize - reader.bp < 3) return 52; /*error, bit pointer will jump past memory*/
1372
31.1k
    ensureBits9(&reader, 3);
1373
31.1k
    BFINAL = readBits(&reader, 1);
1374
31.1k
    BTYPE = readBits(&reader, 2);
1375
1376
31.1k
    if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
1377
31.1k
    else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/
1378
25.5k
    else error = inflateHuffmanBlock(out, &reader, BTYPE, settings->max_output_size); /*compression, BTYPE 01 or 10*/
1379
31.1k
    if(!error && settings->max_output_size && out->size > settings->max_output_size) error = 109;
1380
31.1k
    if(error) break;
1381
31.1k
  }
1382
1383
8.81k
  return error;
1384
8.84k
}
1385
1386
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
1387
                         const unsigned char* in, size_t insize,
1388
0
                         const LodePNGDecompressSettings* settings) {
1389
0
  ucvector v = ucvector_init(*out, *outsize);
1390
0
  unsigned error = lodepng_inflatev(&v, in, insize, settings);
1391
0
  *out = v.data;
1392
0
  *outsize = v.size;
1393
0
  return error;
1394
0
}
1395
1396
static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize,
1397
8.84k
                        const LodePNGDecompressSettings* settings) {
1398
8.84k
  if(settings->custom_inflate) {
1399
0
    unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings);
1400
0
    out->allocsize = out->size;
1401
0
    if(error) {
1402
      /*the custom inflate is allowed to have its own error codes, however, we translate it to code 110*/
1403
0
      error = 110;
1404
      /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/
1405
0
      if(settings->max_output_size && out->size > settings->max_output_size) error = 109;
1406
0
    }
1407
0
    return error;
1408
8.84k
  } else {
1409
8.84k
    return lodepng_inflatev(out, in, insize, settings);
1410
8.84k
  }
1411
8.84k
}
1412
1413
#endif /*LODEPNG_COMPILE_DECODER*/
1414
1415
#ifdef LODEPNG_COMPILE_ENCODER
1416
1417
/* ////////////////////////////////////////////////////////////////////////// */
1418
/* / Deflator (Compressor)                                                  / */
1419
/* ////////////////////////////////////////////////////////////////////////// */
1420
1421
static const unsigned MAX_SUPPORTED_DEFLATE_LENGTH = 258;
1422
1423
/*search the index in the array, that has the largest value smaller than or equal to the given value,
1424
given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1425
0
static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) {
1426
  /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
1427
0
  size_t left = 1;
1428
0
  size_t right = array_size - 1;
1429
1430
0
  while(left <= right) {
1431
0
    size_t mid = (left + right) >> 1;
1432
0
    if(array[mid] >= value) right = mid - 1;
1433
0
    else left = mid + 1;
1434
0
  }
1435
0
  if(left >= array_size || array[left] > value) left--;
1436
0
  return left;
1437
0
}
1438
1439
0
static void addLengthDistance(uivector* values, size_t length, size_t distance) {
1440
  /*values in encoded vector are those used by deflate:
1441
  0-255: literal bytes
1442
  256: end
1443
  257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1444
  286-287: invalid*/
1445
1446
0
  unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
1447
0
  unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
1448
0
  unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
1449
0
  unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
1450
1451
0
  size_t pos = values->size;
1452
  /*TODO: return error when this fails (out of memory)*/
1453
0
  unsigned ok = uivector_resize(values, values->size + 4);
1454
0
  if(ok) {
1455
0
    values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX;
1456
0
    values->data[pos + 1] = extra_length;
1457
0
    values->data[pos + 2] = dist_code;
1458
0
    values->data[pos + 3] = extra_distance;
1459
0
  }
1460
0
}
1461
1462
/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
1463
bytes as input because 3 is the minimum match length for deflate*/
1464
static const unsigned HASH_NUM_VALUES = 65536;
1465
static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
1466
1467
typedef struct Hash {
1468
  int* head; /*hash value to head circular pos - can be outdated if went around window*/
1469
  /*circular pos to prev circular pos*/
1470
  unsigned short* chain;
1471
  int* val; /*circular pos to hash value*/
1472
1473
  /*TODO: do this not only for zeros but for any repeated byte. However for PNG
1474
  it's always going to be the zeros that dominate, so not important for PNG*/
1475
  int* headz; /*similar to head, but for chainz*/
1476
  unsigned short* chainz; /*those with same amount of zeros*/
1477
  unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
1478
} Hash;
1479
1480
0
static unsigned hash_init(Hash* hash, unsigned windowsize) {
1481
0
  unsigned i;
1482
0
  hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
1483
0
  hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
1484
0
  hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1485
1486
0
  hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1487
0
  hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
1488
0
  hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
1489
1490
0
  if(!hash->head || !hash->chain || !hash->val  || !hash->headz|| !hash->chainz || !hash->zeros) {
1491
0
    return 83; /*alloc fail*/
1492
0
  }
1493
1494
  /*initialize hash table*/
1495
0
  for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
1496
0
  for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
1497
0
  for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
1498
1499
0
  for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
1500
0
  for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
1501
1502
0
  return 0;
1503
0
}
1504
1505
0
static void hash_cleanup(Hash* hash) {
1506
0
  lodepng_free(hash->head);
1507
0
  lodepng_free(hash->val);
1508
0
  lodepng_free(hash->chain);
1509
1510
0
  lodepng_free(hash->zeros);
1511
0
  lodepng_free(hash->headz);
1512
0
  lodepng_free(hash->chainz);
1513
0
}
1514
1515
1516
1517
0
static unsigned getHash(const unsigned char* data, size_t size, size_t pos) {
1518
0
  unsigned result = 0;
1519
0
  if(pos + 2 < size) {
1520
    /*A simple shift and xor hash is used. Since the data of PNGs is dominated
1521
    by zeroes due to the filters, a better hash does not have a significant
1522
    effect on speed in traversing the chain, and causes more time spend on
1523
    calculating the hash.*/
1524
0
    result ^= ((unsigned)data[pos + 0] << 0u);
1525
0
    result ^= ((unsigned)data[pos + 1] << 4u);
1526
0
    result ^= ((unsigned)data[pos + 2] << 8u);
1527
0
  } else {
1528
0
    size_t amount, i;
1529
0
    if(pos >= size) return 0;
1530
0
    amount = size - pos;
1531
0
    for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u));
1532
0
  }
1533
0
  return result & HASH_BIT_MASK;
1534
0
}
1535
1536
0
static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) {
1537
0
  const unsigned char* start = data + pos;
1538
0
  const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
1539
0
  if(end > data + size) end = data + size;
1540
0
  data = start;
1541
0
  while(data != end && *data == 0) ++data;
1542
  /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
1543
0
  return (unsigned)(data - start);
1544
0
}
1545
1546
/*wpos = pos & (windowsize - 1)*/
1547
0
static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) {
1548
0
  hash->val[wpos] = (int)hashval;
1549
0
  if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
1550
0
  hash->head[hashval] = (int)wpos;
1551
1552
0
  hash->zeros[wpos] = numzeros;
1553
0
  if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
1554
0
  hash->headz[numzeros] = (int)wpos;
1555
0
}
1556
1557
/*
1558
LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1559
is in the form of unsigned integers with codes representing for example literal bytes, or
1560
length/distance pairs.
1561
It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1562
sliding window (of windowsize) is used, and all past bytes in that window can be used as
1563
the "dictionary". A brute force search through all possible distances would be slow, and
1564
this hash technique is one out of several ways to speed this up.
1565
*/
1566
static unsigned encodeLZ77(uivector* out, Hash* hash,
1567
                           const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
1568
0
                           unsigned minmatch, unsigned nicematch, unsigned lazymatching) {
1569
0
  size_t pos;
1570
0
  unsigned i, error = 0;
1571
  /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1572
0
  unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u;
1573
0
  unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
1574
1575
0
  unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
1576
0
  unsigned numzeros = 0;
1577
1578
0
  unsigned offset; /*the offset represents the distance in LZ77 terminology*/
1579
0
  unsigned length;
1580
0
  unsigned lazy = 0;
1581
0
  unsigned lazylength = 0, lazyoffset = 0;
1582
0
  unsigned hashval;
1583
0
  unsigned current_offset, current_length;
1584
0
  unsigned prev_offset;
1585
0
  const unsigned char *lastptr, *foreptr, *backptr;
1586
0
  unsigned hashpos;
1587
1588
0
  if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
1589
0
  if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
1590
1591
0
  if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
1592
1593
0
  for(pos = inpos; pos < insize; ++pos) {
1594
0
    size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
1595
0
    unsigned chainlength = 0;
1596
1597
0
    hashval = getHash(in, insize, pos);
1598
1599
0
    if(usezeros && hashval == 0) {
1600
0
      if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1601
0
      else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1602
0
    } else {
1603
0
      numzeros = 0;
1604
0
    }
1605
1606
0
    updateHashChain(hash, wpos, hashval, numzeros);
1607
1608
    /*the length and offset found for the current position*/
1609
0
    length = 0;
1610
0
    offset = 0;
1611
1612
0
    hashpos = hash->chain[wpos];
1613
1614
0
    lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
1615
1616
    /*search for the longest string*/
1617
0
    prev_offset = 0;
1618
0
    for(;;) {
1619
0
      if(chainlength++ >= maxchainlength) break;
1620
0
      current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);
1621
1622
0
      if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
1623
0
      prev_offset = current_offset;
1624
0
      if(current_offset > 0) {
1625
        /*test the next characters*/
1626
0
        foreptr = &in[pos];
1627
0
        backptr = &in[pos - current_offset];
1628
1629
        /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1630
0
        if(numzeros >= 3) {
1631
0
          unsigned skip = hash->zeros[hashpos];
1632
0
          if(skip > numzeros) skip = numzeros;
1633
0
          backptr += skip;
1634
0
          foreptr += skip;
1635
0
        }
1636
1637
0
        while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ {
1638
0
          ++backptr;
1639
0
          ++foreptr;
1640
0
        }
1641
0
        current_length = (unsigned)(foreptr - &in[pos]);
1642
1643
0
        if(current_length > length) {
1644
0
          length = current_length; /*the longest length*/
1645
0
          offset = current_offset; /*the offset that is related to this longest length*/
1646
          /*jump out once a length of max length is found (speed gain). This also jumps
1647
          out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
1648
0
          if(current_length >= nicematch) break;
1649
0
        }
1650
0
      }
1651
1652
0
      if(hashpos == hash->chain[hashpos]) break;
1653
1654
0
      if(numzeros >= 3 && length > numzeros) {
1655
0
        hashpos = hash->chainz[hashpos];
1656
0
        if(hash->zeros[hashpos] != numzeros) break;
1657
0
      } else {
1658
0
        hashpos = hash->chain[hashpos];
1659
        /*outdated hash value, happens if particular value was not encountered in whole last window*/
1660
0
        if(hash->val[hashpos] != (int)hashval) break;
1661
0
      }
1662
0
    }
1663
1664
0
    if(lazymatching) {
1665
0
      if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {
1666
0
        lazy = 1;
1667
0
        lazylength = length;
1668
0
        lazyoffset = offset;
1669
0
        continue; /*try the next byte*/
1670
0
      }
1671
0
      if(lazy) {
1672
0
        lazy = 0;
1673
0
        if(pos == 0) ERROR_BREAK(81);
1674
0
        if(length > lazylength + 1) {
1675
          /*push the previous character as literal*/
1676
0
          if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
1677
0
        } else {
1678
0
          length = lazylength;
1679
0
          offset = lazyoffset;
1680
0
          hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1681
0
          hash->headz[numzeros] = -1; /*idem*/
1682
0
          --pos;
1683
0
        }
1684
0
      }
1685
0
    }
1686
0
    if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1687
1688
    /*encode it as length/distance pair or literal value*/
1689
0
    if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ {
1690
0
      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1691
0
    } else if(length < minmatch || (length == 3 && offset > 4096)) {
1692
      /*compensate for the fact that longer offsets have more extra bits, a
1693
      length of only 3 may be not worth it then*/
1694
0
      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1695
0
    } else {
1696
0
      addLengthDistance(out, length, offset);
1697
0
      for(i = 1; i < length; ++i) {
1698
0
        ++pos;
1699
0
        wpos = pos & (windowsize - 1);
1700
0
        hashval = getHash(in, insize, pos);
1701
0
        if(usezeros && hashval == 0) {
1702
0
          if(numzeros == 0) numzeros = countZeros(in, insize, pos);
1703
0
          else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
1704
0
        } else {
1705
0
          numzeros = 0;
1706
0
        }
1707
0
        updateHashChain(hash, wpos, hashval, numzeros);
1708
0
      }
1709
0
    }
1710
0
  } /*end of the loop through each character of input*/
1711
1712
0
  return error;
1713
0
}
1714
1715
/* /////////////////////////////////////////////////////////////////////////// */
1716
1717
0
static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) {
1718
  /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1719
  2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1720
1721
0
  size_t i, numdeflateblocks = (datasize + 65534u) / 65535u;
1722
0
  size_t datapos = 0;
1723
0
  for(i = 0; i != numdeflateblocks; ++i) {
1724
0
    unsigned BFINAL, BTYPE, LEN, NLEN;
1725
0
    unsigned char firstbyte;
1726
0
    size_t pos = out->size;
1727
1728
0
    BFINAL = (i == numdeflateblocks - 1);
1729
0
    BTYPE = 0;
1730
1731
0
    LEN = 65535;
1732
0
    if(datasize - datapos < 65535u) LEN = (unsigned)datasize - (unsigned)datapos;
1733
0
    NLEN = 65535 - LEN;
1734
1735
0
    if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/
1736
1737
0
    firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u));
1738
0
    out->data[pos + 0] = firstbyte;
1739
0
    out->data[pos + 1] = (unsigned char)(LEN & 255);
1740
0
    out->data[pos + 2] = (unsigned char)(LEN >> 8u);
1741
0
    out->data[pos + 3] = (unsigned char)(NLEN & 255);
1742
0
    out->data[pos + 4] = (unsigned char)(NLEN >> 8u);
1743
0
    lodepng_memcpy(out->data + pos + 5, data + datapos, LEN);
1744
0
    datapos += LEN;
1745
0
  }
1746
1747
0
  return 0;
1748
0
}
1749
1750
/*
1751
write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1752
tree_ll: the tree for lit and len codes.
1753
tree_d: the tree for distance codes.
1754
*/
1755
static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded,
1756
0
                          const HuffmanTree* tree_ll, const HuffmanTree* tree_d) {
1757
0
  size_t i = 0;
1758
0
  for(i = 0; i != lz77_encoded->size; ++i) {
1759
0
    unsigned val = lz77_encoded->data[i];
1760
0
    writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[val]);
1761
0
    if(val > 256) /*for a length code, 3 more things have to be added*/ {
1762
0
      unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
1763
0
      unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
1764
0
      unsigned length_extra_bits = lz77_encoded->data[++i];
1765
1766
0
      unsigned distance_code = lz77_encoded->data[++i];
1767
1768
0
      unsigned distance_index = distance_code;
1769
0
      unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
1770
0
      unsigned distance_extra_bits = lz77_encoded->data[++i];
1771
1772
0
      writeBits(writer, length_extra_bits, n_length_extra_bits);
1773
0
      writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]);
1774
0
      writeBits(writer, distance_extra_bits, n_distance_extra_bits);
1775
0
    }
1776
0
  }
1777
0
}
1778
1779
/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1780
static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash,
1781
                               const unsigned char* data, size_t datapos, size_t dataend,
1782
0
                               const LodePNGCompressSettings* settings, unsigned final) {
1783
0
  unsigned error = 0;
1784
1785
  /*
1786
  A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1787
  literal bytes and length/distance pairs. This is then huffman compressed with
1788
  two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1789
  another huffman tree is used for the dist values ("d"). These two trees are
1790
  stored using their code lengths, and to compress even more these code lengths
1791
  are also run-length encoded and huffman compressed. This gives a huffman tree
1792
  of code lengths "cl". The code lengths used to describe this third tree are
1793
  the code length code lengths ("clcl").
1794
  */
1795
1796
  /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1797
0
  uivector lz77_encoded;
1798
0
  HuffmanTree tree_ll; /*tree for lit,len values*/
1799
0
  HuffmanTree tree_d; /*tree for distance codes*/
1800
0
  HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1801
0
  unsigned* frequencies_ll = 0; /*frequency of lit,len codes*/
1802
0
  unsigned* frequencies_d = 0; /*frequency of dist codes*/
1803
0
  unsigned* frequencies_cl = 0; /*frequency of code length codes*/
1804
0
  unsigned* bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/
1805
0
  unsigned* bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/
1806
0
  size_t datasize = dataend - datapos;
1807
1808
  /*
1809
  If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent
1810
  tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are
1811
  some analogies:
1812
  bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1813
  bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1814
  bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1815
  */
1816
1817
0
  unsigned BFINAL = final;
1818
0
  size_t i;
1819
0
  size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl;
1820
0
  unsigned HLIT, HDIST, HCLEN;
1821
1822
0
  uivector_init(&lz77_encoded);
1823
0
  HuffmanTree_init(&tree_ll);
1824
0
  HuffmanTree_init(&tree_d);
1825
0
  HuffmanTree_init(&tree_cl);
1826
  /* could fit on stack, but >1KB is on the larger side so allocate instead */
1827
0
  frequencies_ll = (unsigned*)lodepng_malloc(286 * sizeof(*frequencies_ll));
1828
0
  frequencies_d = (unsigned*)lodepng_malloc(30 * sizeof(*frequencies_d));
1829
0
  frequencies_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));
1830
1831
0
  if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/
1832
1833
  /*This while loop never loops due to a break at the end, it is here to
1834
  allow breaking out of it to the cleanup phase on error conditions.*/
1835
0
  while(!error) {
1836
0
    lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll));
1837
0
    lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d));
1838
0
    lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));
1839
1840
0
    if(settings->use_lz77) {
1841
0
      error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
1842
0
                         settings->minmatch, settings->nicematch, settings->lazymatching);
1843
0
      if(error) break;
1844
0
    } else {
1845
0
      if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
1846
0
      for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
1847
0
    }
1848
1849
    /*Count the frequencies of lit, len and dist codes*/
1850
0
    for(i = 0; i != lz77_encoded.size; ++i) {
1851
0
      unsigned symbol = lz77_encoded.data[i];
1852
0
      ++frequencies_ll[symbol];
1853
0
      if(symbol > 256) {
1854
0
        unsigned dist = lz77_encoded.data[i + 2];
1855
0
        ++frequencies_d[dist];
1856
0
        i += 3;
1857
0
      }
1858
0
    }
1859
0
    frequencies_ll[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
1860
1861
    /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
1862
0
    error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll, 257, 286, 15);
1863
0
    if(error) break;
1864
    /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
1865
0
    error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d, 2, 30, 15);
1866
0
    if(error) break;
1867
1868
0
    numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286);
1869
0
    numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30);
1870
    /*store the code lengths of both generated trees in bitlen_lld*/
1871
0
    numcodes_lld = numcodes_ll + numcodes_d;
1872
0
    bitlen_lld = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld));
1873
    /*numcodes_lld_e never needs more size than bitlen_lld*/
1874
0
    bitlen_lld_e = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e));
1875
0
    if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/
1876
0
    numcodes_lld_e = 0;
1877
1878
0
    for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i];
1879
0
    for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[i];
1880
1881
    /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
1882
    17 (3-10 zeroes), 18 (11-138 zeroes)*/
1883
0
    for(i = 0; i != numcodes_lld; ++i) {
1884
0
      unsigned j = 0; /*amount of repetitions*/
1885
0
      while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j;
1886
1887
0
      if(bitlen_lld[i] == 0 && j >= 2) /*repeat code for zeroes*/ {
1888
0
        ++j; /*include the first zero*/
1889
0
        if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ {
1890
0
          bitlen_lld_e[numcodes_lld_e++] = 17;
1891
0
          bitlen_lld_e[numcodes_lld_e++] = j - 3;
1892
0
        } else /*repeat code 18 supports max 138 zeroes*/ {
1893
0
          if(j > 138) j = 138;
1894
0
          bitlen_lld_e[numcodes_lld_e++] = 18;
1895
0
          bitlen_lld_e[numcodes_lld_e++] = j - 11;
1896
0
        }
1897
0
        i += (j - 1);
1898
0
      } else if(j >= 3) /*repeat code for value other than zero*/ {
1899
0
        size_t k;
1900
0
        unsigned num = j / 6u, rest = j % 6u;
1901
0
        bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];
1902
0
        for(k = 0; k < num; ++k) {
1903
0
          bitlen_lld_e[numcodes_lld_e++] = 16;
1904
0
          bitlen_lld_e[numcodes_lld_e++] = 6 - 3;
1905
0
        }
1906
0
        if(rest >= 3) {
1907
0
          bitlen_lld_e[numcodes_lld_e++] = 16;
1908
0
          bitlen_lld_e[numcodes_lld_e++] = rest - 3;
1909
0
        }
1910
0
        else j -= rest;
1911
0
        i += j;
1912
0
      } else /*too short to benefit from repeat code*/ {
1913
0
        bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];
1914
0
      }
1915
0
    }
1916
1917
    /*generate tree_cl, the huffmantree of huffmantrees*/
1918
0
    for(i = 0; i != numcodes_lld_e; ++i) {
1919
0
      ++frequencies_cl[bitlen_lld_e[i]];
1920
      /*after a repeat code come the bits that specify the number of repetitions,
1921
      those don't need to be in the frequencies_cl calculation*/
1922
0
      if(bitlen_lld_e[i] >= 16) ++i;
1923
0
    }
1924
1925
0
    error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl,
1926
0
                                            NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7);
1927
0
    if(error) break;
1928
1929
    /*compute amount of code-length-code-lengths to output*/
1930
0
    numcodes_cl = NUM_CODE_LENGTH_CODES;
1931
    /*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/
1932
0
    while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) {
1933
0
      numcodes_cl--;
1934
0
    }
1935
1936
    /*
1937
    Write everything into the output
1938
1939
    After the BFINAL and BTYPE, the dynamic block consists out of the following:
1940
    - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
1941
    - (HCLEN+4)*3 bits code lengths of code length alphabet
1942
    - HLIT + 257 code lengths of lit/length alphabet (encoded using the code length
1943
      alphabet, + possible repetition codes 16, 17, 18)
1944
    - HDIST + 1 code lengths of distance alphabet (encoded using the code length
1945
      alphabet, + possible repetition codes 16, 17, 18)
1946
    - compressed data
1947
    - 256 (end code)
1948
    */
1949
1950
    /*Write block type*/
1951
0
    writeBits(writer, BFINAL, 1);
1952
0
    writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/
1953
0
    writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/
1954
1955
    /*write the HLIT, HDIST and HCLEN values*/
1956
    /*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies
1957
    or in the loop for numcodes_cl above, which saves space. */
1958
0
    HLIT = (unsigned)(numcodes_ll - 257);
1959
0
    HDIST = (unsigned)(numcodes_d - 1);
1960
0
    HCLEN = (unsigned)(numcodes_cl - 4);
1961
0
    writeBits(writer, HLIT, 5);
1962
0
    writeBits(writer, HDIST, 5);
1963
0
    writeBits(writer, HCLEN, 4);
1964
1965
    /*write the code lengths of the code length alphabet ("bitlen_cl")*/
1966
0
    for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3);
1967
1968
    /*write the lengths of the lit/len AND the dist alphabet*/
1969
0
    for(i = 0; i != numcodes_lld_e; ++i) {
1970
0
      writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]);
1971
      /*extra bits of repeat codes*/
1972
0
      if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2);
1973
0
      else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3);
1974
0
      else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7);
1975
0
    }
1976
1977
    /*write the compressed data symbols*/
1978
0
    writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
1979
    /*error: the length of the end code 256 must be larger than 0*/
1980
0
    if(tree_ll.lengths[256] == 0) ERROR_BREAK(64);
1981
1982
    /*write the end code*/
1983
0
    writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]);
1984
1985
0
    break; /*end of error-while*/
1986
0
  }
1987
1988
  /*cleanup*/
1989
0
  uivector_cleanup(&lz77_encoded);
1990
0
  HuffmanTree_cleanup(&tree_ll);
1991
0
  HuffmanTree_cleanup(&tree_d);
1992
0
  HuffmanTree_cleanup(&tree_cl);
1993
0
  lodepng_free(frequencies_ll);
1994
0
  lodepng_free(frequencies_d);
1995
0
  lodepng_free(frequencies_cl);
1996
0
  lodepng_free(bitlen_lld);
1997
0
  lodepng_free(bitlen_lld_e);
1998
1999
0
  return error;
2000
0
}
2001
2002
static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash,
2003
                             const unsigned char* data,
2004
                             size_t datapos, size_t dataend,
2005
0
                             const LodePNGCompressSettings* settings, unsigned final) {
2006
0
  HuffmanTree tree_ll; /*tree for literal values and length codes*/
2007
0
  HuffmanTree tree_d; /*tree for distance codes*/
2008
2009
0
  unsigned BFINAL = final;
2010
0
  unsigned error = 0;
2011
0
  size_t i;
2012
2013
0
  HuffmanTree_init(&tree_ll);
2014
0
  HuffmanTree_init(&tree_d);
2015
2016
0
  error = generateFixedLitLenTree(&tree_ll);
2017
0
  if(!error) error = generateFixedDistanceTree(&tree_d);
2018
2019
0
  if(!error) {
2020
0
    writeBits(writer, BFINAL, 1);
2021
0
    writeBits(writer, 1, 1); /*first bit of BTYPE*/
2022
0
    writeBits(writer, 0, 1); /*second bit of BTYPE*/
2023
2024
0
    if(settings->use_lz77) /*LZ77 encoded*/ {
2025
0
      uivector lz77_encoded;
2026
0
      uivector_init(&lz77_encoded);
2027
0
      error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
2028
0
                         settings->minmatch, settings->nicematch, settings->lazymatching);
2029
0
      if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
2030
0
      uivector_cleanup(&lz77_encoded);
2031
0
    } else /*no LZ77, but still will be Huffman compressed*/ {
2032
0
      for(i = datapos; i < dataend; ++i) {
2033
0
        writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]);
2034
0
      }
2035
0
    }
2036
    /*add END code*/
2037
0
    if(!error) writeBitsReversed(writer,tree_ll.codes[256], tree_ll.lengths[256]);
2038
0
  }
2039
2040
  /*cleanup*/
2041
0
  HuffmanTree_cleanup(&tree_ll);
2042
0
  HuffmanTree_cleanup(&tree_d);
2043
2044
0
  return error;
2045
0
}
2046
2047
static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
2048
0
                                 const LodePNGCompressSettings* settings) {
2049
0
  unsigned error = 0;
2050
0
  size_t i, blocksize, numdeflateblocks;
2051
0
  Hash hash;
2052
0
  LodePNGBitWriter writer;
2053
2054
0
  LodePNGBitWriter_init(&writer, out);
2055
2056
0
  if(settings->btype > 2) return 61;
2057
0
  else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
2058
0
  else if(settings->btype == 1) blocksize = insize;
2059
0
  else /*if(settings->btype == 2)*/ {
2060
    /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
2061
0
    blocksize = insize / 8u + 8;
2062
0
    if(blocksize < 65536) blocksize = 65536;
2063
0
    if(blocksize > 262144) blocksize = 262144;
2064
0
  }
2065
2066
0
  numdeflateblocks = (insize + blocksize - 1) / blocksize;
2067
0
  if(numdeflateblocks == 0) numdeflateblocks = 1;
2068
2069
0
  error = hash_init(&hash, settings->windowsize);
2070
2071
0
  if(!error) {
2072
0
    for(i = 0; i != numdeflateblocks && !error; ++i) {
2073
0
      unsigned final = (i == numdeflateblocks - 1);
2074
0
      size_t start = i * blocksize;
2075
0
      size_t end = start + blocksize;
2076
0
      if(end > insize) end = insize;
2077
2078
0
      if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final);
2079
0
      else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final);
2080
0
    }
2081
0
  }
2082
2083
0
  hash_cleanup(&hash);
2084
2085
0
  return error;
2086
0
}
2087
2088
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
2089
                         const unsigned char* in, size_t insize,
2090
0
                         const LodePNGCompressSettings* settings) {
2091
0
  ucvector v = ucvector_init(*out, *outsize);
2092
0
  unsigned error = lodepng_deflatev(&v, in, insize, settings);
2093
0
  *out = v.data;
2094
0
  *outsize = v.size;
2095
0
  return error;
2096
0
}
2097
2098
static unsigned deflate(unsigned char** out, size_t* outsize,
2099
                        const unsigned char* in, size_t insize,
2100
0
                        const LodePNGCompressSettings* settings) {
2101
0
  if(settings->custom_deflate) {
2102
0
    unsigned error = settings->custom_deflate(out, outsize, in, insize, settings);
2103
    /*the custom deflate is allowed to have its own error codes, however, we translate it to code 111*/
2104
0
    return error ? 111 : 0;
2105
0
  } else {
2106
0
    return lodepng_deflate(out, outsize, in, insize, settings);
2107
0
  }
2108
0
}
2109
2110
#endif /*LODEPNG_COMPILE_DECODER*/
2111
2112
/* ////////////////////////////////////////////////////////////////////////// */
2113
/* / Adler32                                                                / */
2114
/* ////////////////////////////////////////////////////////////////////////// */
2115
2116
0
static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) {
2117
0
  unsigned s1 = adler & 0xffffu;
2118
0
  unsigned s2 = (adler >> 16u) & 0xffffu;
2119
2120
0
  while(len != 0u) {
2121
0
    unsigned i;
2122
    /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
2123
0
    unsigned amount = len > 5552u ? 5552u : len;
2124
0
    len -= amount;
2125
0
    for(i = 0; i != amount; ++i) {
2126
0
      s1 += (*data++);
2127
0
      s2 += s1;
2128
0
    }
2129
0
    s1 %= 65521u;
2130
0
    s2 %= 65521u;
2131
0
  }
2132
2133
0
  return (s2 << 16u) | s1;
2134
0
}
2135
2136
/*Return the adler32 of the bytes data[0..len-1]*/
2137
0
static unsigned adler32(const unsigned char* data, unsigned len) {
2138
0
  return update_adler32(1u, data, len);
2139
0
}
2140
2141
/* ////////////////////////////////////////////////////////////////////////// */
2142
/* / Zlib                                                                   / */
2143
/* ////////////////////////////////////////////////////////////////////////// */
2144
2145
#ifdef LODEPNG_COMPILE_DECODER
2146
2147
static unsigned lodepng_zlib_decompressv(ucvector* out,
2148
                                         const unsigned char* in, size_t insize,
2149
9.55k
                                         const LodePNGDecompressSettings* settings) {
2150
9.55k
  unsigned error = 0;
2151
9.55k
  unsigned CM, CINFO, FDICT;
2152
2153
9.55k
  if(insize < 2) return 53; /*error, size of zlib data too small*/
2154
  /*read information from zlib header*/
2155
8.92k
  if((in[0] * 256 + in[1]) % 31 != 0) {
2156
    /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2157
44
    return 24;
2158
44
  }
2159
2160
8.87k
  CM = in[0] & 15;
2161
8.87k
  CINFO = (in[0] >> 4) & 15;
2162
  /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2163
8.87k
  FDICT = (in[1] >> 5) & 1;
2164
  /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2165
2166
8.87k
  if(CM != 8 || CINFO > 7) {
2167
    /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2168
31
    return 25;
2169
31
  }
2170
8.84k
  if(FDICT != 0) {
2171
    /*error: the specification of PNG says about the zlib stream:
2172
      "The additional flags shall not specify a preset dictionary."*/
2173
2
    return 26;
2174
2
  }
2175
2176
8.84k
  error = inflatev(out, in + 2, insize - 2, settings);
2177
8.84k
  if(error) return error;
2178
2179
7.90k
  if(!settings->ignore_adler32) {
2180
0
    unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
2181
0
    unsigned checksum = adler32(out->data, (unsigned)(out->size));
2182
0
    if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
2183
0
  }
2184
2185
7.90k
  return 0; /*no error*/
2186
7.90k
}
2187
2188
2189
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2190
0
                                 size_t insize, const LodePNGDecompressSettings* settings) {
2191
0
  ucvector v = ucvector_init(*out, *outsize);
2192
0
  unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings);
2193
0
  *out = v.data;
2194
0
  *outsize = v.size;
2195
0
  return error;
2196
0
}
2197
2198
/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */
2199
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size,
2200
9.55k
                                const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) {
2201
9.55k
  unsigned error;
2202
9.55k
  if(settings->custom_zlib) {
2203
0
    error = settings->custom_zlib(out, outsize, in, insize, settings);
2204
0
    if(error) {
2205
      /*the custom zlib is allowed to have its own error codes, however, we translate it to code 110*/
2206
0
      error = 110;
2207
      /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/
2208
0
      if(settings->max_output_size && *outsize > settings->max_output_size) error = 109;
2209
0
    }
2210
9.55k
  } else {
2211
9.55k
    ucvector v = ucvector_init(*out, *outsize);
2212
9.55k
    if(expected_size) {
2213
      /*reserve the memory to avoid intermediate reallocations*/
2214
6.89k
      ucvector_resize(&v, *outsize + expected_size);
2215
6.89k
      v.size = *outsize;
2216
6.89k
    }
2217
9.55k
    error = lodepng_zlib_decompressv(&v, in, insize, settings);
2218
9.55k
    *out = v.data;
2219
9.55k
    *outsize = v.size;
2220
9.55k
  }
2221
9.55k
  return error;
2222
9.55k
}
2223
2224
#endif /*LODEPNG_COMPILE_DECODER*/
2225
2226
#ifdef LODEPNG_COMPILE_ENCODER
2227
2228
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2229
0
                               size_t insize, const LodePNGCompressSettings* settings) {
2230
0
  size_t i;
2231
0
  unsigned error;
2232
0
  unsigned char* deflatedata = 0;
2233
0
  size_t deflatesize = 0;
2234
2235
0
  error = deflate(&deflatedata, &deflatesize, in, insize, settings);
2236
2237
0
  *out = NULL;
2238
0
  *outsize = 0;
2239
0
  if(!error) {
2240
0
    *outsize = deflatesize + 6;
2241
0
    *out = (unsigned char*)lodepng_malloc(*outsize);
2242
0
    if(!*out) error = 83; /*alloc fail*/
2243
0
  }
2244
2245
0
  if(!error) {
2246
0
    unsigned ADLER32 = adler32(in, (unsigned)insize);
2247
    /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2248
0
    unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2249
0
    unsigned FLEVEL = 0;
2250
0
    unsigned FDICT = 0;
2251
0
    unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
2252
0
    unsigned FCHECK = 31 - CMFFLG % 31;
2253
0
    CMFFLG += FCHECK;
2254
2255
0
    (*out)[0] = (unsigned char)(CMFFLG >> 8);
2256
0
    (*out)[1] = (unsigned char)(CMFFLG & 255);
2257
0
    for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i];
2258
0
    lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32);
2259
0
  }
2260
2261
0
  lodepng_free(deflatedata);
2262
0
  return error;
2263
0
}
2264
2265
/* compress using the default or custom zlib function */
2266
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2267
0
                              size_t insize, const LodePNGCompressSettings* settings) {
2268
0
  if(settings->custom_zlib) {
2269
0
    unsigned error = settings->custom_zlib(out, outsize, in, insize, settings);
2270
    /*the custom zlib is allowed to have its own error codes, however, we translate it to code 111*/
2271
0
    return error ? 111 : 0;
2272
0
  } else {
2273
0
    return lodepng_zlib_compress(out, outsize, in, insize, settings);
2274
0
  }
2275
0
}
2276
2277
#endif /*LODEPNG_COMPILE_ENCODER*/
2278
2279
#else /*no LODEPNG_COMPILE_ZLIB*/
2280
2281
#ifdef LODEPNG_COMPILE_DECODER
2282
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size,
2283
                                const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) {
2284
  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2285
  (void)expected_size;
2286
  return settings->custom_zlib(out, outsize, in, insize, settings);
2287
}
2288
#endif /*LODEPNG_COMPILE_DECODER*/
2289
#ifdef LODEPNG_COMPILE_ENCODER
2290
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2291
                              size_t insize, const LodePNGCompressSettings* settings) {
2292
  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
2293
  return settings->custom_zlib(out, outsize, in, insize, settings);
2294
}
2295
#endif /*LODEPNG_COMPILE_ENCODER*/
2296
2297
#endif /*LODEPNG_COMPILE_ZLIB*/
2298
2299
/* ////////////////////////////////////////////////////////////////////////// */
2300
2301
#ifdef LODEPNG_COMPILE_ENCODER
2302
2303
/*this is a good tradeoff between speed and compression ratio*/
2304
4.88k
#define DEFAULT_WINDOWSIZE 2048
2305
2306
4.88k
void lodepng_compress_settings_init(LodePNGCompressSettings* settings) {
2307
  /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2308
4.88k
  settings->btype = 2;
2309
4.88k
  settings->use_lz77 = 1;
2310
4.88k
  settings->windowsize = DEFAULT_WINDOWSIZE;
2311
4.88k
  settings->minmatch = 3;
2312
4.88k
  settings->nicematch = 128;
2313
4.88k
  settings->lazymatching = 1;
2314
2315
4.88k
  settings->custom_zlib = 0;
2316
4.88k
  settings->custom_deflate = 0;
2317
4.88k
  settings->custom_context = 0;
2318
4.88k
}
2319
2320
const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
2321
2322
2323
#endif /*LODEPNG_COMPILE_ENCODER*/
2324
2325
#ifdef LODEPNG_COMPILE_DECODER
2326
2327
4.88k
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) {
2328
4.88k
  settings->ignore_adler32 = 0;
2329
4.88k
  settings->ignore_nlen = 0;
2330
4.88k
  settings->max_output_size = 0;
2331
2332
4.88k
  settings->custom_zlib = 0;
2333
4.88k
  settings->custom_inflate = 0;
2334
4.88k
  settings->custom_context = 0;
2335
4.88k
}
2336
2337
const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0, 0};
2338
2339
#endif /*LODEPNG_COMPILE_DECODER*/
2340
2341
/* ////////////////////////////////////////////////////////////////////////// */
2342
/* ////////////////////////////////////////////////////////////////////////// */
2343
/* // End of Zlib related code. Begin of PNG related code.                 // */
2344
/* ////////////////////////////////////////////////////////////////////////// */
2345
/* ////////////////////////////////////////////////////////////////////////// */
2346
2347
#ifdef LODEPNG_COMPILE_PNG
2348
2349
/* ////////////////////////////////////////////////////////////////////////// */
2350
/* / CRC32                                                                  / */
2351
/* ////////////////////////////////////////////////////////////////////////// */
2352
2353
2354
#ifdef LODEPNG_COMPILE_CRC
2355
2356
static const unsigned lodepng_crc32_table0[256] = {
2357
  0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u,
2358
  0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u,
2359
  0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u,
2360
  0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u,
2361
  0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu,
2362
  0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u,
2363
  0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu,
2364
  0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du,
2365
  0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u,
2366
  0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u,
2367
  0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u,
2368
  0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u,
2369
  0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu,
2370
  0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u,
2371
  0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu,
2372
  0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu,
2373
  0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u,
2374
  0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u,
2375
  0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u,
2376
  0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u,
2377
  0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu,
2378
  0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u,
2379
  0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu,
2380
  0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du,
2381
  0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u,
2382
  0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u,
2383
  0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u,
2384
  0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u,
2385
  0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu,
2386
  0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u,
2387
  0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu,
2388
  0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du
2389
};
2390
2391
static const unsigned lodepng_crc32_table1[256] = {
2392
  0x00000000u, 0x191b3141u, 0x32366282u, 0x2b2d53c3u, 0x646cc504u, 0x7d77f445u, 0x565aa786u, 0x4f4196c7u,
2393
  0xc8d98a08u, 0xd1c2bb49u, 0xfaefe88au, 0xe3f4d9cbu, 0xacb54f0cu, 0xb5ae7e4du, 0x9e832d8eu, 0x87981ccfu,
2394
  0x4ac21251u, 0x53d92310u, 0x78f470d3u, 0x61ef4192u, 0x2eaed755u, 0x37b5e614u, 0x1c98b5d7u, 0x05838496u,
2395
  0x821b9859u, 0x9b00a918u, 0xb02dfadbu, 0xa936cb9au, 0xe6775d5du, 0xff6c6c1cu, 0xd4413fdfu, 0xcd5a0e9eu,
2396
  0x958424a2u, 0x8c9f15e3u, 0xa7b24620u, 0xbea97761u, 0xf1e8e1a6u, 0xe8f3d0e7u, 0xc3de8324u, 0xdac5b265u,
2397
  0x5d5daeaau, 0x44469febu, 0x6f6bcc28u, 0x7670fd69u, 0x39316baeu, 0x202a5aefu, 0x0b07092cu, 0x121c386du,
2398
  0xdf4636f3u, 0xc65d07b2u, 0xed705471u, 0xf46b6530u, 0xbb2af3f7u, 0xa231c2b6u, 0x891c9175u, 0x9007a034u,
2399
  0x179fbcfbu, 0x0e848dbau, 0x25a9de79u, 0x3cb2ef38u, 0x73f379ffu, 0x6ae848beu, 0x41c51b7du, 0x58de2a3cu,
2400
  0xf0794f05u, 0xe9627e44u, 0xc24f2d87u, 0xdb541cc6u, 0x94158a01u, 0x8d0ebb40u, 0xa623e883u, 0xbf38d9c2u,
2401
  0x38a0c50du, 0x21bbf44cu, 0x0a96a78fu, 0x138d96ceu, 0x5ccc0009u, 0x45d73148u, 0x6efa628bu, 0x77e153cau,
2402
  0xbabb5d54u, 0xa3a06c15u, 0x888d3fd6u, 0x91960e97u, 0xded79850u, 0xc7cca911u, 0xece1fad2u, 0xf5facb93u,
2403
  0x7262d75cu, 0x6b79e61du, 0x4054b5deu, 0x594f849fu, 0x160e1258u, 0x0f152319u, 0x243870dau, 0x3d23419bu,
2404
  0x65fd6ba7u, 0x7ce65ae6u, 0x57cb0925u, 0x4ed03864u, 0x0191aea3u, 0x188a9fe2u, 0x33a7cc21u, 0x2abcfd60u,
2405
  0xad24e1afu, 0xb43fd0eeu, 0x9f12832du, 0x8609b26cu, 0xc94824abu, 0xd05315eau, 0xfb7e4629u, 0xe2657768u,
2406
  0x2f3f79f6u, 0x362448b7u, 0x1d091b74u, 0x04122a35u, 0x4b53bcf2u, 0x52488db3u, 0x7965de70u, 0x607eef31u,
2407
  0xe7e6f3feu, 0xfefdc2bfu, 0xd5d0917cu, 0xcccba03du, 0x838a36fau, 0x9a9107bbu, 0xb1bc5478u, 0xa8a76539u,
2408
  0x3b83984bu, 0x2298a90au, 0x09b5fac9u, 0x10aecb88u, 0x5fef5d4fu, 0x46f46c0eu, 0x6dd93fcdu, 0x74c20e8cu,
2409
  0xf35a1243u, 0xea412302u, 0xc16c70c1u, 0xd8774180u, 0x9736d747u, 0x8e2de606u, 0xa500b5c5u, 0xbc1b8484u,
2410
  0x71418a1au, 0x685abb5bu, 0x4377e898u, 0x5a6cd9d9u, 0x152d4f1eu, 0x0c367e5fu, 0x271b2d9cu, 0x3e001cddu,
2411
  0xb9980012u, 0xa0833153u, 0x8bae6290u, 0x92b553d1u, 0xddf4c516u, 0xc4eff457u, 0xefc2a794u, 0xf6d996d5u,
2412
  0xae07bce9u, 0xb71c8da8u, 0x9c31de6bu, 0x852aef2au, 0xca6b79edu, 0xd37048acu, 0xf85d1b6fu, 0xe1462a2eu,
2413
  0x66de36e1u, 0x7fc507a0u, 0x54e85463u, 0x4df36522u, 0x02b2f3e5u, 0x1ba9c2a4u, 0x30849167u, 0x299fa026u,
2414
  0xe4c5aeb8u, 0xfdde9ff9u, 0xd6f3cc3au, 0xcfe8fd7bu, 0x80a96bbcu, 0x99b25afdu, 0xb29f093eu, 0xab84387fu,
2415
  0x2c1c24b0u, 0x350715f1u, 0x1e2a4632u, 0x07317773u, 0x4870e1b4u, 0x516bd0f5u, 0x7a468336u, 0x635db277u,
2416
  0xcbfad74eu, 0xd2e1e60fu, 0xf9ccb5ccu, 0xe0d7848du, 0xaf96124au, 0xb68d230bu, 0x9da070c8u, 0x84bb4189u,
2417
  0x03235d46u, 0x1a386c07u, 0x31153fc4u, 0x280e0e85u, 0x674f9842u, 0x7e54a903u, 0x5579fac0u, 0x4c62cb81u,
2418
  0x8138c51fu, 0x9823f45eu, 0xb30ea79du, 0xaa1596dcu, 0xe554001bu, 0xfc4f315au, 0xd7626299u, 0xce7953d8u,
2419
  0x49e14f17u, 0x50fa7e56u, 0x7bd72d95u, 0x62cc1cd4u, 0x2d8d8a13u, 0x3496bb52u, 0x1fbbe891u, 0x06a0d9d0u,
2420
  0x5e7ef3ecu, 0x4765c2adu, 0x6c48916eu, 0x7553a02fu, 0x3a1236e8u, 0x230907a9u, 0x0824546au, 0x113f652bu,
2421
  0x96a779e4u, 0x8fbc48a5u, 0xa4911b66u, 0xbd8a2a27u, 0xf2cbbce0u, 0xebd08da1u, 0xc0fdde62u, 0xd9e6ef23u,
2422
  0x14bce1bdu, 0x0da7d0fcu, 0x268a833fu, 0x3f91b27eu, 0x70d024b9u, 0x69cb15f8u, 0x42e6463bu, 0x5bfd777au,
2423
  0xdc656bb5u, 0xc57e5af4u, 0xee530937u, 0xf7483876u, 0xb809aeb1u, 0xa1129ff0u, 0x8a3fcc33u, 0x9324fd72u
2424
};
2425
2426
static const unsigned lodepng_crc32_table2[256] = {
2427
  0x00000000u, 0x01c26a37u, 0x0384d46eu, 0x0246be59u, 0x0709a8dcu, 0x06cbc2ebu, 0x048d7cb2u, 0x054f1685u,
2428
  0x0e1351b8u, 0x0fd13b8fu, 0x0d9785d6u, 0x0c55efe1u, 0x091af964u, 0x08d89353u, 0x0a9e2d0au, 0x0b5c473du,
2429
  0x1c26a370u, 0x1de4c947u, 0x1fa2771eu, 0x1e601d29u, 0x1b2f0bacu, 0x1aed619bu, 0x18abdfc2u, 0x1969b5f5u,
2430
  0x1235f2c8u, 0x13f798ffu, 0x11b126a6u, 0x10734c91u, 0x153c5a14u, 0x14fe3023u, 0x16b88e7au, 0x177ae44du,
2431
  0x384d46e0u, 0x398f2cd7u, 0x3bc9928eu, 0x3a0bf8b9u, 0x3f44ee3cu, 0x3e86840bu, 0x3cc03a52u, 0x3d025065u,
2432
  0x365e1758u, 0x379c7d6fu, 0x35dac336u, 0x3418a901u, 0x3157bf84u, 0x3095d5b3u, 0x32d36beau, 0x331101ddu,
2433
  0x246be590u, 0x25a98fa7u, 0x27ef31feu, 0x262d5bc9u, 0x23624d4cu, 0x22a0277bu, 0x20e69922u, 0x2124f315u,
2434
  0x2a78b428u, 0x2bbade1fu, 0x29fc6046u, 0x283e0a71u, 0x2d711cf4u, 0x2cb376c3u, 0x2ef5c89au, 0x2f37a2adu,
2435
  0x709a8dc0u, 0x7158e7f7u, 0x731e59aeu, 0x72dc3399u, 0x7793251cu, 0x76514f2bu, 0x7417f172u, 0x75d59b45u,
2436
  0x7e89dc78u, 0x7f4bb64fu, 0x7d0d0816u, 0x7ccf6221u, 0x798074a4u, 0x78421e93u, 0x7a04a0cau, 0x7bc6cafdu,
2437
  0x6cbc2eb0u, 0x6d7e4487u, 0x6f38fadeu, 0x6efa90e9u, 0x6bb5866cu, 0x6a77ec5bu, 0x68315202u, 0x69f33835u,
2438
  0x62af7f08u, 0x636d153fu, 0x612bab66u, 0x60e9c151u, 0x65a6d7d4u, 0x6464bde3u, 0x662203bau, 0x67e0698du,
2439
  0x48d7cb20u, 0x4915a117u, 0x4b531f4eu, 0x4a917579u, 0x4fde63fcu, 0x4e1c09cbu, 0x4c5ab792u, 0x4d98dda5u,
2440
  0x46c49a98u, 0x4706f0afu, 0x45404ef6u, 0x448224c1u, 0x41cd3244u, 0x400f5873u, 0x4249e62au, 0x438b8c1du,
2441
  0x54f16850u, 0x55330267u, 0x5775bc3eu, 0x56b7d609u, 0x53f8c08cu, 0x523aaabbu, 0x507c14e2u, 0x51be7ed5u,
2442
  0x5ae239e8u, 0x5b2053dfu, 0x5966ed86u, 0x58a487b1u, 0x5deb9134u, 0x5c29fb03u, 0x5e6f455au, 0x5fad2f6du,
2443
  0xe1351b80u, 0xe0f771b7u, 0xe2b1cfeeu, 0xe373a5d9u, 0xe63cb35cu, 0xe7fed96bu, 0xe5b86732u, 0xe47a0d05u,
2444
  0xef264a38u, 0xeee4200fu, 0xeca29e56u, 0xed60f461u, 0xe82fe2e4u, 0xe9ed88d3u, 0xebab368au, 0xea695cbdu,
2445
  0xfd13b8f0u, 0xfcd1d2c7u, 0xfe976c9eu, 0xff5506a9u, 0xfa1a102cu, 0xfbd87a1bu, 0xf99ec442u, 0xf85cae75u,
2446
  0xf300e948u, 0xf2c2837fu, 0xf0843d26u, 0xf1465711u, 0xf4094194u, 0xf5cb2ba3u, 0xf78d95fau, 0xf64fffcdu,
2447
  0xd9785d60u, 0xd8ba3757u, 0xdafc890eu, 0xdb3ee339u, 0xde71f5bcu, 0xdfb39f8bu, 0xddf521d2u, 0xdc374be5u,
2448
  0xd76b0cd8u, 0xd6a966efu, 0xd4efd8b6u, 0xd52db281u, 0xd062a404u, 0xd1a0ce33u, 0xd3e6706au, 0xd2241a5du,
2449
  0xc55efe10u, 0xc49c9427u, 0xc6da2a7eu, 0xc7184049u, 0xc25756ccu, 0xc3953cfbu, 0xc1d382a2u, 0xc011e895u,
2450
  0xcb4dafa8u, 0xca8fc59fu, 0xc8c97bc6u, 0xc90b11f1u, 0xcc440774u, 0xcd866d43u, 0xcfc0d31au, 0xce02b92du,
2451
  0x91af9640u, 0x906dfc77u, 0x922b422eu, 0x93e92819u, 0x96a63e9cu, 0x976454abu, 0x9522eaf2u, 0x94e080c5u,
2452
  0x9fbcc7f8u, 0x9e7eadcfu, 0x9c381396u, 0x9dfa79a1u, 0x98b56f24u, 0x99770513u, 0x9b31bb4au, 0x9af3d17du,
2453
  0x8d893530u, 0x8c4b5f07u, 0x8e0de15eu, 0x8fcf8b69u, 0x8a809decu, 0x8b42f7dbu, 0x89044982u, 0x88c623b5u,
2454
  0x839a6488u, 0x82580ebfu, 0x801eb0e6u, 0x81dcdad1u, 0x8493cc54u, 0x8551a663u, 0x8717183au, 0x86d5720du,
2455
  0xa9e2d0a0u, 0xa820ba97u, 0xaa6604ceu, 0xaba46ef9u, 0xaeeb787cu, 0xaf29124bu, 0xad6fac12u, 0xacadc625u,
2456
  0xa7f18118u, 0xa633eb2fu, 0xa4755576u, 0xa5b73f41u, 0xa0f829c4u, 0xa13a43f3u, 0xa37cfdaau, 0xa2be979du,
2457
  0xb5c473d0u, 0xb40619e7u, 0xb640a7beu, 0xb782cd89u, 0xb2cddb0cu, 0xb30fb13bu, 0xb1490f62u, 0xb08b6555u,
2458
  0xbbd72268u, 0xba15485fu, 0xb853f606u, 0xb9919c31u, 0xbcde8ab4u, 0xbd1ce083u, 0xbf5a5edau, 0xbe9834edu
2459
};
2460
2461
static const unsigned lodepng_crc32_table3[256] = {
2462
  0x00000000u, 0xb8bc6765u, 0xaa09c88bu, 0x12b5afeeu, 0x8f629757u, 0x37def032u, 0x256b5fdcu, 0x9dd738b9u,
2463
  0xc5b428efu, 0x7d084f8au, 0x6fbde064u, 0xd7018701u, 0x4ad6bfb8u, 0xf26ad8ddu, 0xe0df7733u, 0x58631056u,
2464
  0x5019579fu, 0xe8a530fau, 0xfa109f14u, 0x42acf871u, 0xdf7bc0c8u, 0x67c7a7adu, 0x75720843u, 0xcdce6f26u,
2465
  0x95ad7f70u, 0x2d111815u, 0x3fa4b7fbu, 0x8718d09eu, 0x1acfe827u, 0xa2738f42u, 0xb0c620acu, 0x087a47c9u,
2466
  0xa032af3eu, 0x188ec85bu, 0x0a3b67b5u, 0xb28700d0u, 0x2f503869u, 0x97ec5f0cu, 0x8559f0e2u, 0x3de59787u,
2467
  0x658687d1u, 0xdd3ae0b4u, 0xcf8f4f5au, 0x7733283fu, 0xeae41086u, 0x525877e3u, 0x40edd80du, 0xf851bf68u,
2468
  0xf02bf8a1u, 0x48979fc4u, 0x5a22302au, 0xe29e574fu, 0x7f496ff6u, 0xc7f50893u, 0xd540a77du, 0x6dfcc018u,
2469
  0x359fd04eu, 0x8d23b72bu, 0x9f9618c5u, 0x272a7fa0u, 0xbafd4719u, 0x0241207cu, 0x10f48f92u, 0xa848e8f7u,
2470
  0x9b14583du, 0x23a83f58u, 0x311d90b6u, 0x89a1f7d3u, 0x1476cf6au, 0xaccaa80fu, 0xbe7f07e1u, 0x06c36084u,
2471
  0x5ea070d2u, 0xe61c17b7u, 0xf4a9b859u, 0x4c15df3cu, 0xd1c2e785u, 0x697e80e0u, 0x7bcb2f0eu, 0xc377486bu,
2472
  0xcb0d0fa2u, 0x73b168c7u, 0x6104c729u, 0xd9b8a04cu, 0x446f98f5u, 0xfcd3ff90u, 0xee66507eu, 0x56da371bu,
2473
  0x0eb9274du, 0xb6054028u, 0xa4b0efc6u, 0x1c0c88a3u, 0x81dbb01au, 0x3967d77fu, 0x2bd27891u, 0x936e1ff4u,
2474
  0x3b26f703u, 0x839a9066u, 0x912f3f88u, 0x299358edu, 0xb4446054u, 0x0cf80731u, 0x1e4da8dfu, 0xa6f1cfbau,
2475
  0xfe92dfecu, 0x462eb889u, 0x549b1767u, 0xec277002u, 0x71f048bbu, 0xc94c2fdeu, 0xdbf98030u, 0x6345e755u,
2476
  0x6b3fa09cu, 0xd383c7f9u, 0xc1366817u, 0x798a0f72u, 0xe45d37cbu, 0x5ce150aeu, 0x4e54ff40u, 0xf6e89825u,
2477
  0xae8b8873u, 0x1637ef16u, 0x048240f8u, 0xbc3e279du, 0x21e91f24u, 0x99557841u, 0x8be0d7afu, 0x335cb0cau,
2478
  0xed59b63bu, 0x55e5d15eu, 0x47507eb0u, 0xffec19d5u, 0x623b216cu, 0xda874609u, 0xc832e9e7u, 0x708e8e82u,
2479
  0x28ed9ed4u, 0x9051f9b1u, 0x82e4565fu, 0x3a58313au, 0xa78f0983u, 0x1f336ee6u, 0x0d86c108u, 0xb53aa66du,
2480
  0xbd40e1a4u, 0x05fc86c1u, 0x1749292fu, 0xaff54e4au, 0x322276f3u, 0x8a9e1196u, 0x982bbe78u, 0x2097d91du,
2481
  0x78f4c94bu, 0xc048ae2eu, 0xd2fd01c0u, 0x6a4166a5u, 0xf7965e1cu, 0x4f2a3979u, 0x5d9f9697u, 0xe523f1f2u,
2482
  0x4d6b1905u, 0xf5d77e60u, 0xe762d18eu, 0x5fdeb6ebu, 0xc2098e52u, 0x7ab5e937u, 0x680046d9u, 0xd0bc21bcu,
2483
  0x88df31eau, 0x3063568fu, 0x22d6f961u, 0x9a6a9e04u, 0x07bda6bdu, 0xbf01c1d8u, 0xadb46e36u, 0x15080953u,
2484
  0x1d724e9au, 0xa5ce29ffu, 0xb77b8611u, 0x0fc7e174u, 0x9210d9cdu, 0x2aacbea8u, 0x38191146u, 0x80a57623u,
2485
  0xd8c66675u, 0x607a0110u, 0x72cfaefeu, 0xca73c99bu, 0x57a4f122u, 0xef189647u, 0xfdad39a9u, 0x45115eccu,
2486
  0x764dee06u, 0xcef18963u, 0xdc44268du, 0x64f841e8u, 0xf92f7951u, 0x41931e34u, 0x5326b1dau, 0xeb9ad6bfu,
2487
  0xb3f9c6e9u, 0x0b45a18cu, 0x19f00e62u, 0xa14c6907u, 0x3c9b51beu, 0x842736dbu, 0x96929935u, 0x2e2efe50u,
2488
  0x2654b999u, 0x9ee8defcu, 0x8c5d7112u, 0x34e11677u, 0xa9362eceu, 0x118a49abu, 0x033fe645u, 0xbb838120u,
2489
  0xe3e09176u, 0x5b5cf613u, 0x49e959fdu, 0xf1553e98u, 0x6c820621u, 0xd43e6144u, 0xc68bceaau, 0x7e37a9cfu,
2490
  0xd67f4138u, 0x6ec3265du, 0x7c7689b3u, 0xc4caeed6u, 0x591dd66fu, 0xe1a1b10au, 0xf3141ee4u, 0x4ba87981u,
2491
  0x13cb69d7u, 0xab770eb2u, 0xb9c2a15cu, 0x017ec639u, 0x9ca9fe80u, 0x241599e5u, 0x36a0360bu, 0x8e1c516eu,
2492
  0x866616a7u, 0x3eda71c2u, 0x2c6fde2cu, 0x94d3b949u, 0x090481f0u, 0xb1b8e695u, 0xa30d497bu, 0x1bb12e1eu,
2493
  0x43d23e48u, 0xfb6e592du, 0xe9dbf6c3u, 0x516791a6u, 0xccb0a91fu, 0x740cce7au, 0x66b96194u, 0xde0506f1u
2494
};
2495
2496
static const unsigned lodepng_crc32_table4[256] = {
2497
  0x00000000u, 0x3d6029b0u, 0x7ac05360u, 0x47a07ad0u, 0xf580a6c0u, 0xc8e08f70u, 0x8f40f5a0u, 0xb220dc10u,
2498
  0x30704bc1u, 0x0d106271u, 0x4ab018a1u, 0x77d03111u, 0xc5f0ed01u, 0xf890c4b1u, 0xbf30be61u, 0x825097d1u,
2499
  0x60e09782u, 0x5d80be32u, 0x1a20c4e2u, 0x2740ed52u, 0x95603142u, 0xa80018f2u, 0xefa06222u, 0xd2c04b92u,
2500
  0x5090dc43u, 0x6df0f5f3u, 0x2a508f23u, 0x1730a693u, 0xa5107a83u, 0x98705333u, 0xdfd029e3u, 0xe2b00053u,
2501
  0xc1c12f04u, 0xfca106b4u, 0xbb017c64u, 0x866155d4u, 0x344189c4u, 0x0921a074u, 0x4e81daa4u, 0x73e1f314u,
2502
  0xf1b164c5u, 0xccd14d75u, 0x8b7137a5u, 0xb6111e15u, 0x0431c205u, 0x3951ebb5u, 0x7ef19165u, 0x4391b8d5u,
2503
  0xa121b886u, 0x9c419136u, 0xdbe1ebe6u, 0xe681c256u, 0x54a11e46u, 0x69c137f6u, 0x2e614d26u, 0x13016496u,
2504
  0x9151f347u, 0xac31daf7u, 0xeb91a027u, 0xd6f18997u, 0x64d15587u, 0x59b17c37u, 0x1e1106e7u, 0x23712f57u,
2505
  0x58f35849u, 0x659371f9u, 0x22330b29u, 0x1f532299u, 0xad73fe89u, 0x9013d739u, 0xd7b3ade9u, 0xead38459u,
2506
  0x68831388u, 0x55e33a38u, 0x124340e8u, 0x2f236958u, 0x9d03b548u, 0xa0639cf8u, 0xe7c3e628u, 0xdaa3cf98u,
2507
  0x3813cfcbu, 0x0573e67bu, 0x42d39cabu, 0x7fb3b51bu, 0xcd93690bu, 0xf0f340bbu, 0xb7533a6bu, 0x8a3313dbu,
2508
  0x0863840au, 0x3503adbau, 0x72a3d76au, 0x4fc3fedau, 0xfde322cau, 0xc0830b7au, 0x872371aau, 0xba43581au,
2509
  0x9932774du, 0xa4525efdu, 0xe3f2242du, 0xde920d9du, 0x6cb2d18du, 0x51d2f83du, 0x167282edu, 0x2b12ab5du,
2510
  0xa9423c8cu, 0x9422153cu, 0xd3826fecu, 0xeee2465cu, 0x5cc29a4cu, 0x61a2b3fcu, 0x2602c92cu, 0x1b62e09cu,
2511
  0xf9d2e0cfu, 0xc4b2c97fu, 0x8312b3afu, 0xbe729a1fu, 0x0c52460fu, 0x31326fbfu, 0x7692156fu, 0x4bf23cdfu,
2512
  0xc9a2ab0eu, 0xf4c282beu, 0xb362f86eu, 0x8e02d1deu, 0x3c220dceu, 0x0142247eu, 0x46e25eaeu, 0x7b82771eu,
2513
  0xb1e6b092u, 0x8c869922u, 0xcb26e3f2u, 0xf646ca42u, 0x44661652u, 0x79063fe2u, 0x3ea64532u, 0x03c66c82u,
2514
  0x8196fb53u, 0xbcf6d2e3u, 0xfb56a833u, 0xc6368183u, 0x74165d93u, 0x49767423u, 0x0ed60ef3u, 0x33b62743u,
2515
  0xd1062710u, 0xec660ea0u, 0xabc67470u, 0x96a65dc0u, 0x248681d0u, 0x19e6a860u, 0x5e46d2b0u, 0x6326fb00u,
2516
  0xe1766cd1u, 0xdc164561u, 0x9bb63fb1u, 0xa6d61601u, 0x14f6ca11u, 0x2996e3a1u, 0x6e369971u, 0x5356b0c1u,
2517
  0x70279f96u, 0x4d47b626u, 0x0ae7ccf6u, 0x3787e546u, 0x85a73956u, 0xb8c710e6u, 0xff676a36u, 0xc2074386u,
2518
  0x4057d457u, 0x7d37fde7u, 0x3a978737u, 0x07f7ae87u, 0xb5d77297u, 0x88b75b27u, 0xcf1721f7u, 0xf2770847u,
2519
  0x10c70814u, 0x2da721a4u, 0x6a075b74u, 0x576772c4u, 0xe547aed4u, 0xd8278764u, 0x9f87fdb4u, 0xa2e7d404u,
2520
  0x20b743d5u, 0x1dd76a65u, 0x5a7710b5u, 0x67173905u, 0xd537e515u, 0xe857cca5u, 0xaff7b675u, 0x92979fc5u,
2521
  0xe915e8dbu, 0xd475c16bu, 0x93d5bbbbu, 0xaeb5920bu, 0x1c954e1bu, 0x21f567abu, 0x66551d7bu, 0x5b3534cbu,
2522
  0xd965a31au, 0xe4058aaau, 0xa3a5f07au, 0x9ec5d9cau, 0x2ce505dau, 0x11852c6au, 0x562556bau, 0x6b457f0au,
2523
  0x89f57f59u, 0xb49556e9u, 0xf3352c39u, 0xce550589u, 0x7c75d999u, 0x4115f029u, 0x06b58af9u, 0x3bd5a349u,
2524
  0xb9853498u, 0x84e51d28u, 0xc34567f8u, 0xfe254e48u, 0x4c059258u, 0x7165bbe8u, 0x36c5c138u, 0x0ba5e888u,
2525
  0x28d4c7dfu, 0x15b4ee6fu, 0x521494bfu, 0x6f74bd0fu, 0xdd54611fu, 0xe03448afu, 0xa794327fu, 0x9af41bcfu,
2526
  0x18a48c1eu, 0x25c4a5aeu, 0x6264df7eu, 0x5f04f6ceu, 0xed242adeu, 0xd044036eu, 0x97e479beu, 0xaa84500eu,
2527
  0x4834505du, 0x755479edu, 0x32f4033du, 0x0f942a8du, 0xbdb4f69du, 0x80d4df2du, 0xc774a5fdu, 0xfa148c4du,
2528
  0x78441b9cu, 0x4524322cu, 0x028448fcu, 0x3fe4614cu, 0x8dc4bd5cu, 0xb0a494ecu, 0xf704ee3cu, 0xca64c78cu
2529
};
2530
2531
static const unsigned lodepng_crc32_table5[256] = {
2532
  0x00000000u, 0xcb5cd3a5u, 0x4dc8a10bu, 0x869472aeu, 0x9b914216u, 0x50cd91b3u, 0xd659e31du, 0x1d0530b8u,
2533
  0xec53826du, 0x270f51c8u, 0xa19b2366u, 0x6ac7f0c3u, 0x77c2c07bu, 0xbc9e13deu, 0x3a0a6170u, 0xf156b2d5u,
2534
  0x03d6029bu, 0xc88ad13eu, 0x4e1ea390u, 0x85427035u, 0x9847408du, 0x531b9328u, 0xd58fe186u, 0x1ed33223u,
2535
  0xef8580f6u, 0x24d95353u, 0xa24d21fdu, 0x6911f258u, 0x7414c2e0u, 0xbf481145u, 0x39dc63ebu, 0xf280b04eu,
2536
  0x07ac0536u, 0xccf0d693u, 0x4a64a43du, 0x81387798u, 0x9c3d4720u, 0x57619485u, 0xd1f5e62bu, 0x1aa9358eu,
2537
  0xebff875bu, 0x20a354feu, 0xa6372650u, 0x6d6bf5f5u, 0x706ec54du, 0xbb3216e8u, 0x3da66446u, 0xf6fab7e3u,
2538
  0x047a07adu, 0xcf26d408u, 0x49b2a6a6u, 0x82ee7503u, 0x9feb45bbu, 0x54b7961eu, 0xd223e4b0u, 0x197f3715u,
2539
  0xe82985c0u, 0x23755665u, 0xa5e124cbu, 0x6ebdf76eu, 0x73b8c7d6u, 0xb8e41473u, 0x3e7066ddu, 0xf52cb578u,
2540
  0x0f580a6cu, 0xc404d9c9u, 0x4290ab67u, 0x89cc78c2u, 0x94c9487au, 0x5f959bdfu, 0xd901e971u, 0x125d3ad4u,
2541
  0xe30b8801u, 0x28575ba4u, 0xaec3290au, 0x659ffaafu, 0x789aca17u, 0xb3c619b2u, 0x35526b1cu, 0xfe0eb8b9u,
2542
  0x0c8e08f7u, 0xc7d2db52u, 0x4146a9fcu, 0x8a1a7a59u, 0x971f4ae1u, 0x5c439944u, 0xdad7ebeau, 0x118b384fu,
2543
  0xe0dd8a9au, 0x2b81593fu, 0xad152b91u, 0x6649f834u, 0x7b4cc88cu, 0xb0101b29u, 0x36846987u, 0xfdd8ba22u,
2544
  0x08f40f5au, 0xc3a8dcffu, 0x453cae51u, 0x8e607df4u, 0x93654d4cu, 0x58399ee9u, 0xdeadec47u, 0x15f13fe2u,
2545
  0xe4a78d37u, 0x2ffb5e92u, 0xa96f2c3cu, 0x6233ff99u, 0x7f36cf21u, 0xb46a1c84u, 0x32fe6e2au, 0xf9a2bd8fu,
2546
  0x0b220dc1u, 0xc07ede64u, 0x46eaaccau, 0x8db67f6fu, 0x90b34fd7u, 0x5bef9c72u, 0xdd7beedcu, 0x16273d79u,
2547
  0xe7718facu, 0x2c2d5c09u, 0xaab92ea7u, 0x61e5fd02u, 0x7ce0cdbau, 0xb7bc1e1fu, 0x31286cb1u, 0xfa74bf14u,
2548
  0x1eb014d8u, 0xd5ecc77du, 0x5378b5d3u, 0x98246676u, 0x852156ceu, 0x4e7d856bu, 0xc8e9f7c5u, 0x03b52460u,
2549
  0xf2e396b5u, 0x39bf4510u, 0xbf2b37beu, 0x7477e41bu, 0x6972d4a3u, 0xa22e0706u, 0x24ba75a8u, 0xefe6a60du,
2550
  0x1d661643u, 0xd63ac5e6u, 0x50aeb748u, 0x9bf264edu, 0x86f75455u, 0x4dab87f0u, 0xcb3ff55eu, 0x006326fbu,
2551
  0xf135942eu, 0x3a69478bu, 0xbcfd3525u, 0x77a1e680u, 0x6aa4d638u, 0xa1f8059du, 0x276c7733u, 0xec30a496u,
2552
  0x191c11eeu, 0xd240c24bu, 0x54d4b0e5u, 0x9f886340u, 0x828d53f8u, 0x49d1805du, 0xcf45f2f3u, 0x04192156u,
2553
  0xf54f9383u, 0x3e134026u, 0xb8873288u, 0x73dbe12du, 0x6eded195u, 0xa5820230u, 0x2316709eu, 0xe84aa33bu,
2554
  0x1aca1375u, 0xd196c0d0u, 0x5702b27eu, 0x9c5e61dbu, 0x815b5163u, 0x4a0782c6u, 0xcc93f068u, 0x07cf23cdu,
2555
  0xf6999118u, 0x3dc542bdu, 0xbb513013u, 0x700de3b6u, 0x6d08d30eu, 0xa65400abu, 0x20c07205u, 0xeb9ca1a0u,
2556
  0x11e81eb4u, 0xdab4cd11u, 0x5c20bfbfu, 0x977c6c1au, 0x8a795ca2u, 0x41258f07u, 0xc7b1fda9u, 0x0ced2e0cu,
2557
  0xfdbb9cd9u, 0x36e74f7cu, 0xb0733dd2u, 0x7b2fee77u, 0x662adecfu, 0xad760d6au, 0x2be27fc4u, 0xe0beac61u,
2558
  0x123e1c2fu, 0xd962cf8au, 0x5ff6bd24u, 0x94aa6e81u, 0x89af5e39u, 0x42f38d9cu, 0xc467ff32u, 0x0f3b2c97u,
2559
  0xfe6d9e42u, 0x35314de7u, 0xb3a53f49u, 0x78f9ececu, 0x65fcdc54u, 0xaea00ff1u, 0x28347d5fu, 0xe368aefau,
2560
  0x16441b82u, 0xdd18c827u, 0x5b8cba89u, 0x90d0692cu, 0x8dd55994u, 0x46898a31u, 0xc01df89fu, 0x0b412b3au,
2561
  0xfa1799efu, 0x314b4a4au, 0xb7df38e4u, 0x7c83eb41u, 0x6186dbf9u, 0xaada085cu, 0x2c4e7af2u, 0xe712a957u,
2562
  0x15921919u, 0xdececabcu, 0x585ab812u, 0x93066bb7u, 0x8e035b0fu, 0x455f88aau, 0xc3cbfa04u, 0x089729a1u,
2563
  0xf9c19b74u, 0x329d48d1u, 0xb4093a7fu, 0x7f55e9dau, 0x6250d962u, 0xa90c0ac7u, 0x2f987869u, 0xe4c4abccu
2564
};
2565
2566
static const unsigned lodepng_crc32_table6[256] = {
2567
  0x00000000u, 0xa6770bb4u, 0x979f1129u, 0x31e81a9du, 0xf44f2413u, 0x52382fa7u, 0x63d0353au, 0xc5a73e8eu,
2568
  0x33ef4e67u, 0x959845d3u, 0xa4705f4eu, 0x020754fau, 0xc7a06a74u, 0x61d761c0u, 0x503f7b5du, 0xf64870e9u,
2569
  0x67de9cceu, 0xc1a9977au, 0xf0418de7u, 0x56368653u, 0x9391b8ddu, 0x35e6b369u, 0x040ea9f4u, 0xa279a240u,
2570
  0x5431d2a9u, 0xf246d91du, 0xc3aec380u, 0x65d9c834u, 0xa07ef6bau, 0x0609fd0eu, 0x37e1e793u, 0x9196ec27u,
2571
  0xcfbd399cu, 0x69ca3228u, 0x582228b5u, 0xfe552301u, 0x3bf21d8fu, 0x9d85163bu, 0xac6d0ca6u, 0x0a1a0712u,
2572
  0xfc5277fbu, 0x5a257c4fu, 0x6bcd66d2u, 0xcdba6d66u, 0x081d53e8u, 0xae6a585cu, 0x9f8242c1u, 0x39f54975u,
2573
  0xa863a552u, 0x0e14aee6u, 0x3ffcb47bu, 0x998bbfcfu, 0x5c2c8141u, 0xfa5b8af5u, 0xcbb39068u, 0x6dc49bdcu,
2574
  0x9b8ceb35u, 0x3dfbe081u, 0x0c13fa1cu, 0xaa64f1a8u, 0x6fc3cf26u, 0xc9b4c492u, 0xf85cde0fu, 0x5e2bd5bbu,
2575
  0x440b7579u, 0xe27c7ecdu, 0xd3946450u, 0x75e36fe4u, 0xb044516au, 0x16335adeu, 0x27db4043u, 0x81ac4bf7u,
2576
  0x77e43b1eu, 0xd19330aau, 0xe07b2a37u, 0x460c2183u, 0x83ab1f0du, 0x25dc14b9u, 0x14340e24u, 0xb2430590u,
2577
  0x23d5e9b7u, 0x85a2e203u, 0xb44af89eu, 0x123df32au, 0xd79acda4u, 0x71edc610u, 0x4005dc8du, 0xe672d739u,
2578
  0x103aa7d0u, 0xb64dac64u, 0x87a5b6f9u, 0x21d2bd4du, 0xe47583c3u, 0x42028877u, 0x73ea92eau, 0xd59d995eu,
2579
  0x8bb64ce5u, 0x2dc14751u, 0x1c295dccu, 0xba5e5678u, 0x7ff968f6u, 0xd98e6342u, 0xe86679dfu, 0x4e11726bu,
2580
  0xb8590282u, 0x1e2e0936u, 0x2fc613abu, 0x89b1181fu, 0x4c162691u, 0xea612d25u, 0xdb8937b8u, 0x7dfe3c0cu,
2581
  0xec68d02bu, 0x4a1fdb9fu, 0x7bf7c102u, 0xdd80cab6u, 0x1827f438u, 0xbe50ff8cu, 0x8fb8e511u, 0x29cfeea5u,
2582
  0xdf879e4cu, 0x79f095f8u, 0x48188f65u, 0xee6f84d1u, 0x2bc8ba5fu, 0x8dbfb1ebu, 0xbc57ab76u, 0x1a20a0c2u,
2583
  0x8816eaf2u, 0x2e61e146u, 0x1f89fbdbu, 0xb9fef06fu, 0x7c59cee1u, 0xda2ec555u, 0xebc6dfc8u, 0x4db1d47cu,
2584
  0xbbf9a495u, 0x1d8eaf21u, 0x2c66b5bcu, 0x8a11be08u, 0x4fb68086u, 0xe9c18b32u, 0xd82991afu, 0x7e5e9a1bu,
2585
  0xefc8763cu, 0x49bf7d88u, 0x78576715u, 0xde206ca1u, 0x1b87522fu, 0xbdf0599bu, 0x8c184306u, 0x2a6f48b2u,
2586
  0xdc27385bu, 0x7a5033efu, 0x4bb82972u, 0xedcf22c6u, 0x28681c48u, 0x8e1f17fcu, 0xbff70d61u, 0x198006d5u,
2587
  0x47abd36eu, 0xe1dcd8dau, 0xd034c247u, 0x7643c9f3u, 0xb3e4f77du, 0x1593fcc9u, 0x247be654u, 0x820cede0u,
2588
  0x74449d09u, 0xd23396bdu, 0xe3db8c20u, 0x45ac8794u, 0x800bb91au, 0x267cb2aeu, 0x1794a833u, 0xb1e3a387u,
2589
  0x20754fa0u, 0x86024414u, 0xb7ea5e89u, 0x119d553du, 0xd43a6bb3u, 0x724d6007u, 0x43a57a9au, 0xe5d2712eu,
2590
  0x139a01c7u, 0xb5ed0a73u, 0x840510eeu, 0x22721b5au, 0xe7d525d4u, 0x41a22e60u, 0x704a34fdu, 0xd63d3f49u,
2591
  0xcc1d9f8bu, 0x6a6a943fu, 0x5b828ea2u, 0xfdf58516u, 0x3852bb98u, 0x9e25b02cu, 0xafcdaab1u, 0x09baa105u,
2592
  0xfff2d1ecu, 0x5985da58u, 0x686dc0c5u, 0xce1acb71u, 0x0bbdf5ffu, 0xadcafe4bu, 0x9c22e4d6u, 0x3a55ef62u,
2593
  0xabc30345u, 0x0db408f1u, 0x3c5c126cu, 0x9a2b19d8u, 0x5f8c2756u, 0xf9fb2ce2u, 0xc813367fu, 0x6e643dcbu,
2594
  0x982c4d22u, 0x3e5b4696u, 0x0fb35c0bu, 0xa9c457bfu, 0x6c636931u, 0xca146285u, 0xfbfc7818u, 0x5d8b73acu,
2595
  0x03a0a617u, 0xa5d7ada3u, 0x943fb73eu, 0x3248bc8au, 0xf7ef8204u, 0x519889b0u, 0x6070932du, 0xc6079899u,
2596
  0x304fe870u, 0x9638e3c4u, 0xa7d0f959u, 0x01a7f2edu, 0xc400cc63u, 0x6277c7d7u, 0x539fdd4au, 0xf5e8d6feu,
2597
  0x647e3ad9u, 0xc209316du, 0xf3e12bf0u, 0x55962044u, 0x90311ecau, 0x3646157eu, 0x07ae0fe3u, 0xa1d90457u,
2598
  0x579174beu, 0xf1e67f0au, 0xc00e6597u, 0x66796e23u, 0xa3de50adu, 0x05a95b19u, 0x34414184u, 0x92364a30u
2599
};
2600
2601
static const unsigned lodepng_crc32_table7[256] = {
2602
  0x00000000u, 0xccaa009eu, 0x4225077du, 0x8e8f07e3u, 0x844a0efau, 0x48e00e64u, 0xc66f0987u, 0x0ac50919u,
2603
  0xd3e51bb5u, 0x1f4f1b2bu, 0x91c01cc8u, 0x5d6a1c56u, 0x57af154fu, 0x9b0515d1u, 0x158a1232u, 0xd92012acu,
2604
  0x7cbb312bu, 0xb01131b5u, 0x3e9e3656u, 0xf23436c8u, 0xf8f13fd1u, 0x345b3f4fu, 0xbad438acu, 0x767e3832u,
2605
  0xaf5e2a9eu, 0x63f42a00u, 0xed7b2de3u, 0x21d12d7du, 0x2b142464u, 0xe7be24fau, 0x69312319u, 0xa59b2387u,
2606
  0xf9766256u, 0x35dc62c8u, 0xbb53652bu, 0x77f965b5u, 0x7d3c6cacu, 0xb1966c32u, 0x3f196bd1u, 0xf3b36b4fu,
2607
  0x2a9379e3u, 0xe639797du, 0x68b67e9eu, 0xa41c7e00u, 0xaed97719u, 0x62737787u, 0xecfc7064u, 0x205670fau,
2608
  0x85cd537du, 0x496753e3u, 0xc7e85400u, 0x0b42549eu, 0x01875d87u, 0xcd2d5d19u, 0x43a25afau, 0x8f085a64u,
2609
  0x562848c8u, 0x9a824856u, 0x140d4fb5u, 0xd8a74f2bu, 0xd2624632u, 0x1ec846acu, 0x9047414fu, 0x5ced41d1u,
2610
  0x299dc2edu, 0xe537c273u, 0x6bb8c590u, 0xa712c50eu, 0xadd7cc17u, 0x617dcc89u, 0xeff2cb6au, 0x2358cbf4u,
2611
  0xfa78d958u, 0x36d2d9c6u, 0xb85dde25u, 0x74f7debbu, 0x7e32d7a2u, 0xb298d73cu, 0x3c17d0dfu, 0xf0bdd041u,
2612
  0x5526f3c6u, 0x998cf358u, 0x1703f4bbu, 0xdba9f425u, 0xd16cfd3cu, 0x1dc6fda2u, 0x9349fa41u, 0x5fe3fadfu,
2613
  0x86c3e873u, 0x4a69e8edu, 0xc4e6ef0eu, 0x084cef90u, 0x0289e689u, 0xce23e617u, 0x40ace1f4u, 0x8c06e16au,
2614
  0xd0eba0bbu, 0x1c41a025u, 0x92cea7c6u, 0x5e64a758u, 0x54a1ae41u, 0x980baedfu, 0x1684a93cu, 0xda2ea9a2u,
2615
  0x030ebb0eu, 0xcfa4bb90u, 0x412bbc73u, 0x8d81bcedu, 0x8744b5f4u, 0x4beeb56au, 0xc561b289u, 0x09cbb217u,
2616
  0xac509190u, 0x60fa910eu, 0xee7596edu, 0x22df9673u, 0x281a9f6au, 0xe4b09ff4u, 0x6a3f9817u, 0xa6959889u,
2617
  0x7fb58a25u, 0xb31f8abbu, 0x3d908d58u, 0xf13a8dc6u, 0xfbff84dfu, 0x37558441u, 0xb9da83a2u, 0x7570833cu,
2618
  0x533b85dau, 0x9f918544u, 0x111e82a7u, 0xddb48239u, 0xd7718b20u, 0x1bdb8bbeu, 0x95548c5du, 0x59fe8cc3u,
2619
  0x80de9e6fu, 0x4c749ef1u, 0xc2fb9912u, 0x0e51998cu, 0x04949095u, 0xc83e900bu, 0x46b197e8u, 0x8a1b9776u,
2620
  0x2f80b4f1u, 0xe32ab46fu, 0x6da5b38cu, 0xa10fb312u, 0xabcaba0bu, 0x6760ba95u, 0xe9efbd76u, 0x2545bde8u,
2621
  0xfc65af44u, 0x30cfafdau, 0xbe40a839u, 0x72eaa8a7u, 0x782fa1beu, 0xb485a120u, 0x3a0aa6c3u, 0xf6a0a65du,
2622
  0xaa4de78cu, 0x66e7e712u, 0xe868e0f1u, 0x24c2e06fu, 0x2e07e976u, 0xe2ade9e8u, 0x6c22ee0bu, 0xa088ee95u,
2623
  0x79a8fc39u, 0xb502fca7u, 0x3b8dfb44u, 0xf727fbdau, 0xfde2f2c3u, 0x3148f25du, 0xbfc7f5beu, 0x736df520u,
2624
  0xd6f6d6a7u, 0x1a5cd639u, 0x94d3d1dau, 0x5879d144u, 0x52bcd85du, 0x9e16d8c3u, 0x1099df20u, 0xdc33dfbeu,
2625
  0x0513cd12u, 0xc9b9cd8cu, 0x4736ca6fu, 0x8b9ccaf1u, 0x8159c3e8u, 0x4df3c376u, 0xc37cc495u, 0x0fd6c40bu,
2626
  0x7aa64737u, 0xb60c47a9u, 0x3883404au, 0xf42940d4u, 0xfeec49cdu, 0x32464953u, 0xbcc94eb0u, 0x70634e2eu,
2627
  0xa9435c82u, 0x65e95c1cu, 0xeb665bffu, 0x27cc5b61u, 0x2d095278u, 0xe1a352e6u, 0x6f2c5505u, 0xa386559bu,
2628
  0x061d761cu, 0xcab77682u, 0x44387161u, 0x889271ffu, 0x825778e6u, 0x4efd7878u, 0xc0727f9bu, 0x0cd87f05u,
2629
  0xd5f86da9u, 0x19526d37u, 0x97dd6ad4u, 0x5b776a4au, 0x51b26353u, 0x9d1863cdu, 0x1397642eu, 0xdf3d64b0u,
2630
  0x83d02561u, 0x4f7a25ffu, 0xc1f5221cu, 0x0d5f2282u, 0x079a2b9bu, 0xcb302b05u, 0x45bf2ce6u, 0x89152c78u,
2631
  0x50353ed4u, 0x9c9f3e4au, 0x121039a9u, 0xdeba3937u, 0xd47f302eu, 0x18d530b0u, 0x965a3753u, 0x5af037cdu,
2632
  0xff6b144au, 0x33c114d4u, 0xbd4e1337u, 0x71e413a9u, 0x7b211ab0u, 0xb78b1a2eu, 0x39041dcdu, 0xf5ae1d53u,
2633
  0x2c8e0fffu, 0xe0240f61u, 0x6eab0882u, 0xa201081cu, 0xa8c40105u, 0x646e019bu, 0xeae10678u, 0x264b06e6u
2634
};
2635
2636
/* Computes the cyclic redundancy check as used by PNG chunks*/
2637
0
unsigned lodepng_crc32(const unsigned char* data, size_t length) {
2638
  /*Using the Slicing by Eight algorithm*/
2639
0
  unsigned r = 0xffffffffu;
2640
0
  while(length >= 8) {
2641
0
    r = lodepng_crc32_table7[(data[0] ^ (r & 0xffu))] ^
2642
0
        lodepng_crc32_table6[(data[1] ^ ((r >> 8) & 0xffu))] ^
2643
0
        lodepng_crc32_table5[(data[2] ^ ((r >> 16) & 0xffu))] ^
2644
0
        lodepng_crc32_table4[(data[3] ^ ((r >> 24) & 0xffu))] ^
2645
0
        lodepng_crc32_table3[data[4]] ^
2646
0
        lodepng_crc32_table2[data[5]] ^
2647
0
        lodepng_crc32_table1[data[6]] ^
2648
0
        lodepng_crc32_table0[data[7]];
2649
0
    data += 8;
2650
0
    length -= 8;
2651
0
  }
2652
0
  while(length--) {
2653
0
    r = lodepng_crc32_table0[(r ^ *data++) & 0xffu] ^ (r >> 8);
2654
0
  }
2655
0
  return r ^ 0xffffffffu;
2656
0
}
2657
#else /* LODEPNG_COMPILE_CRC */
2658
/*in this case, the function is only declared here, and must be defined externally
2659
so that it will be linked in.
2660
2661
Example implementation that uses a much smaller lookup table for memory constrained cases:
2662
2663
unsigned lodepng_crc32(const unsigned char* data, size_t length) {
2664
  unsigned r = 0xffffffffu;
2665
  static const unsigned table[16] = {
2666
    0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
2667
    0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
2668
  };
2669
  while(length--) {
2670
    r = table[(r ^ *data) & 0xf] ^ (r >> 4);
2671
    r = table[(r ^ (*data >> 4)) & 0xf] ^ (r >> 4);
2672
    data++;
2673
  }
2674
  return r ^ 0xffffffffu;
2675
}
2676
*/
2677
unsigned lodepng_crc32(const unsigned char* data, size_t length);
2678
#endif /* LODEPNG_COMPILE_CRC */
2679
2680
/* ////////////////////////////////////////////////////////////////////////// */
2681
/* / Reading and writing PNG color channel bits                             / */
2682
/* ////////////////////////////////////////////////////////////////////////// */
2683
2684
/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,
2685
so LodePNGBitWriter and LodePNGBitReader can't be used for those. */
2686
2687
487M
static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) {
2688
487M
  unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2689
487M
  ++(*bitpointer);
2690
487M
  return result;
2691
487M
}
2692
2693
/* TODO: make this faster */
2694
58.5M
static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
2695
58.5M
  unsigned result = 0;
2696
58.5M
  size_t i;
2697
117M
  for(i = 0 ; i < nbits; ++i) {
2698
58.6M
    result <<= 1u;
2699
58.6M
    result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
2700
58.6M
  }
2701
58.5M
  return result;
2702
58.5M
}
2703
2704
428M
static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {
2705
  /*the current bit in bitstream may be 0 or 1 for this to work*/
2706
428M
  if(bit == 0) bitstream[(*bitpointer) >> 3u] &=  (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u))));
2707
57.9M
  else         bitstream[(*bitpointer) >> 3u] |=  (1u << (7u - ((*bitpointer) & 7u)));
2708
428M
  ++(*bitpointer);
2709
428M
}
2710
2711
/* ////////////////////////////////////////////////////////////////////////// */
2712
/* / PNG chunks                                                             / */
2713
/* ////////////////////////////////////////////////////////////////////////// */
2714
2715
443k
unsigned lodepng_chunk_length(const unsigned char* chunk) {
2716
443k
  return lodepng_read32bitInt(chunk);
2717
443k
}
2718
2719
0
void lodepng_chunk_type(char type[5], const unsigned char* chunk) {
2720
0
  unsigned i;
2721
0
  for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
2722
0
  type[4] = 0; /*null termination char*/
2723
0
}
2724
2725
1.54M
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) {
2726
1.54M
  if(lodepng_strlen(type) != 4) return 0;
2727
1.54M
  return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2728
1.54M
}
2729
2730
/* chunk type name must exist only out of alphabetic characters a-z or A-Z */
2731
4.22k
static unsigned char lodepng_chunk_type_name_valid(const unsigned char* chunk) {
2732
4.22k
  unsigned i;
2733
20.9k
  for(i = 0; i != 4; ++i) {
2734
16.7k
    char c = (char)chunk[4 + i];
2735
16.7k
    if(!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
2736
90
      return 0; /* not valid */
2737
90
    }
2738
16.7k
  }
2739
4.13k
  return 1; /* valid */
2740
4.22k
}
2741
2742
4.13k
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) {
2743
4.13k
  return((chunk[4] & 32) != 0);
2744
4.13k
}
2745
2746
0
unsigned char lodepng_chunk_private(const unsigned char* chunk) {
2747
0
  return((chunk[5] & 32) != 0);
2748
0
}
2749
2750
/* this is an error if it is reserved: the third character must be uppercase in the PNG standard,
2751
lowercasing this character is reserved for possible future extension by the spec*/
2752
4.13k
static unsigned char lodepng_chunk_reserved(const unsigned char* chunk) {
2753
4.13k
  return((chunk[6] & 32) != 0);
2754
4.13k
}
2755
2756
0
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) {
2757
0
  return((chunk[7] & 32) != 0);
2758
0
}
2759
2760
0
unsigned char* lodepng_chunk_data(unsigned char* chunk) {
2761
0
  return &chunk[8];
2762
0
}
2763
2764
218k
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) {
2765
218k
  return &chunk[8];
2766
218k
}
2767
2768
0
unsigned lodepng_chunk_check_crc(const unsigned char* chunk) {
2769
0
  unsigned length = lodepng_chunk_length(chunk);
2770
0
  unsigned crc = lodepng_read32bitInt(&chunk[length + 8]);
2771
  /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2772
0
  unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2773
0
  if(crc != checksum) return 1;
2774
0
  else return 0;
2775
0
}
2776
2777
0
void lodepng_chunk_generate_crc(unsigned char* chunk) {
2778
0
  unsigned length = lodepng_chunk_length(chunk);
2779
0
  unsigned crc = lodepng_crc32(&chunk[4], length + 4);
2780
0
  lodepng_set32bitInt(chunk + 8 + length, crc);
2781
0
}
2782
2783
0
unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end) {
2784
0
  size_t available_size = (size_t)(end - chunk);
2785
0
  if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/
2786
0
  if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
2787
0
    && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
2788
    /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
2789
0
    return chunk + 8;
2790
0
  } else {
2791
0
    size_t total_chunk_length;
2792
0
    if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;
2793
0
    if(total_chunk_length > available_size) return end; /*outside of range*/
2794
0
    return chunk + total_chunk_length;
2795
0
  }
2796
0
}
2797
2798
217k
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end) {
2799
217k
  size_t available_size = (size_t)(end - chunk);
2800
217k
  if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/
2801
217k
  if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
2802
0
    && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
2803
    /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
2804
0
    return chunk + 8;
2805
217k
  } else {
2806
217k
    size_t total_chunk_length;
2807
217k
    if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;
2808
217k
    if(total_chunk_length > available_size) return end; /*outside of range*/
2809
217k
    return chunk + total_chunk_length;
2810
217k
  }
2811
217k
}
2812
2813
0
unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]) {
2814
0
  for(;;) {
2815
0
    if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */
2816
0
    if(lodepng_chunk_type_equals(chunk, type)) return chunk;
2817
0
    chunk = lodepng_chunk_next(chunk, end);
2818
0
  }
2819
0
}
2820
2821
0
const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) {
2822
0
  for(;;) {
2823
0
    if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */
2824
0
    if(lodepng_chunk_type_equals(chunk, type)) return chunk;
2825
0
    chunk = lodepng_chunk_next_const(chunk, end);
2826
0
  }
2827
0
}
2828
2829
0
unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk) {
2830
0
  unsigned i;
2831
0
  size_t total_chunk_length, new_length;
2832
0
  unsigned char *chunk_start, *new_buffer;
2833
2834
0
  if(!lodepng_chunk_type_name_valid(chunk)) {
2835
0
    return 121; /* invalid chunk type name */
2836
0
  }
2837
0
  if(lodepng_chunk_reserved(chunk)) {
2838
0
    return 122; /* invalid third lowercase character */
2839
0
  }
2840
2841
0
  if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77;
2842
0
  if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77;
2843
2844
0
  new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
2845
0
  if(!new_buffer) return 83; /*alloc fail*/
2846
0
  (*out) = new_buffer;
2847
0
  (*outsize) = new_length;
2848
0
  chunk_start = &(*out)[new_length - total_chunk_length];
2849
2850
0
  for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
2851
2852
0
  return 0;
2853
0
}
2854
2855
/*Sets length and name and allocates the space for data and crc but does not
2856
set data or crc yet. Returns the start of the chunk in chunk. The start of
2857
the data is at chunk + 8. To finalize chunk, add the data, then use
2858
lodepng_chunk_generate_crc */
2859
static unsigned lodepng_chunk_init(unsigned char** chunk,
2860
                                   ucvector* out,
2861
0
                                   size_t length, const char* type) {
2862
0
  size_t new_length = out->size;
2863
0
  if(lodepng_addofl(new_length, length, &new_length)) return 77;
2864
0
  if(lodepng_addofl(new_length, 12, &new_length)) return 77;
2865
0
  if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/
2866
0
  *chunk = out->data + new_length - length - 12u;
2867
2868
  /*1: length*/
2869
0
  lodepng_set32bitInt(*chunk, (unsigned)length);
2870
2871
  /*2: chunk name (4 letters)*/
2872
0
  lodepng_memcpy(*chunk + 4, type, 4);
2873
2874
0
  return 0;
2875
0
}
2876
2877
/* like lodepng_chunk_create but with custom allocsize */
2878
static unsigned lodepng_chunk_createv(ucvector* out,
2879
0
                                      size_t length, const char* type, const unsigned char* data) {
2880
0
  unsigned char* chunk;
2881
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type));
2882
2883
  /*3: the data*/
2884
0
  lodepng_memcpy(chunk + 8, data, length);
2885
2886
  /*4: CRC (of the chunkname characters and the data)*/
2887
0
  lodepng_chunk_generate_crc(chunk);
2888
2889
0
  return 0;
2890
0
}
2891
2892
unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize,
2893
0
                              size_t length, const char* type, const unsigned char* data) {
2894
0
  ucvector v = ucvector_init(*out, *outsize);
2895
0
  unsigned error = lodepng_chunk_createv(&v, length, type, data);
2896
0
  *out = v.data;
2897
0
  *outsize = v.size;
2898
0
  return error;
2899
0
}
2900
2901
/* ////////////////////////////////////////////////////////////////////////// */
2902
/* / Color types, channels, bits                                            / */
2903
/* ////////////////////////////////////////////////////////////////////////// */
2904
2905
/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.
2906
Return value is a LodePNG error code.*/
2907
8.12k
static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) {
2908
8.12k
  switch(colortype) {
2909
2.99k
    case LCT_GREY:       if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break;
2910
2.97k
    case LCT_RGB:        if(!(                                 bd == 8 || bd == 16)) return 37; break;
2911
2.85k
    case LCT_PALETTE:    if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8            )) return 37; break;
2912
818
    case LCT_GREY_ALPHA: if(!(                                 bd == 8 || bd == 16)) return 37; break;
2913
836
    case LCT_RGBA:       if(!(                                 bd == 8 || bd == 16)) return 37; break;
2914
824
    case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */
2915
4
    default: return 31; /* invalid color type */
2916
8.12k
  }
2917
8.04k
  return 0; /*allowed color type / bits combination*/
2918
8.12k
}
2919
2920
48.0k
static unsigned getNumColorChannels(LodePNGColorType colortype) {
2921
48.0k
  switch(colortype) {
2922
12.4k
    case LCT_GREY: return 1;
2923
15.2k
    case LCT_RGB: return 3;
2924
2.78k
    case LCT_PALETTE: return 1;
2925
3.78k
    case LCT_GREY_ALPHA: return 2;
2926
13.7k
    case LCT_RGBA: return 4;
2927
0
    case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */
2928
0
    default: return 0; /*invalid color type*/
2929
48.0k
  }
2930
48.0k
}
2931
2932
48.0k
static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) {
2933
  /*bits per pixel is amount of channels * bits per channel*/
2934
48.0k
  return getNumColorChannels(colortype) * bitdepth;
2935
48.0k
}
2936
2937
/* ////////////////////////////////////////////////////////////////////////// */
2938
2939
18.0k
void lodepng_color_mode_init(LodePNGColorMode* info) {
2940
18.0k
  info->key_defined = 0;
2941
18.0k
  info->key_r = info->key_g = info->key_b = 0;
2942
18.0k
  info->colortype = LCT_RGBA;
2943
18.0k
  info->bitdepth = 8;
2944
18.0k
  info->palette = 0;
2945
18.0k
  info->palettesize = 0;
2946
18.0k
}
2947
2948
/*allocates palette memory if needed, and initializes all colors to black*/
2949
2.87k
static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) {
2950
2.87k
  size_t i;
2951
  /*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/
2952
  /*the palette must have room for up to 256 colors with 4 bytes each.*/
2953
2.87k
  if(!info->palette) info->palette = (unsigned char*)lodepng_malloc(1024);
2954
2.87k
  if(!info->palette) return; /*alloc fail*/
2955
739k
  for(i = 0; i != 256; ++i) {
2956
    /*Initialize all unused colors with black, the value used for invalid palette indices.
2957
    This is an error according to the PNG spec, but common PNG decoders make it black instead.
2958
    That makes color conversion slightly faster due to no error handling needed.*/
2959
736k
    info->palette[i * 4 + 0] = 0;
2960
736k
    info->palette[i * 4 + 1] = 0;
2961
736k
    info->palette[i * 4 + 2] = 0;
2962
736k
    info->palette[i * 4 + 3] = 255;
2963
736k
  }
2964
2.87k
}
2965
2966
19.8k
void lodepng_color_mode_cleanup(LodePNGColorMode* info) {
2967
19.8k
  lodepng_palette_clear(info);
2968
19.8k
}
2969
2970
1.72k
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) {
2971
1.72k
  lodepng_color_mode_cleanup(dest);
2972
1.72k
  lodepng_memcpy(dest, source, sizeof(LodePNGColorMode));
2973
1.72k
  if(source->palette) {
2974
178
    dest->palette = (unsigned char*)lodepng_malloc(1024);
2975
178
    if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2976
178
    lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4);
2977
178
  }
2978
1.72k
  return 0;
2979
1.72k
}
2980
2981
0
LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) {
2982
0
  LodePNGColorMode result;
2983
0
  lodepng_color_mode_init(&result);
2984
0
  result.colortype = colortype;
2985
0
  result.bitdepth = bitdepth;
2986
0
  return result;
2987
0
}
2988
2989
4.92k
static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) {
2990
4.92k
  size_t i;
2991
4.92k
  if(a->colortype != b->colortype) return 0;
2992
2.12k
  if(a->bitdepth != b->bitdepth) return 0;
2993
1.76k
  if(a->key_defined != b->key_defined) return 0;
2994
1.76k
  if(a->key_defined) {
2995
494
    if(a->key_r != b->key_r) return 0;
2996
494
    if(a->key_g != b->key_g) return 0;
2997
494
    if(a->key_b != b->key_b) return 0;
2998
494
  }
2999
1.76k
  if(a->palettesize != b->palettesize) return 0;
3000
14.8k
  for(i = 0; i != a->palettesize * 4; ++i) {
3001
13.1k
    if(a->palette[i] != b->palette[i]) return 0;
3002
13.1k
  }
3003
1.76k
  return 1;
3004
1.76k
}
3005
3006
19.8k
void lodepng_palette_clear(LodePNGColorMode* info) {
3007
19.8k
  if(info->palette) lodepng_free(info->palette);
3008
19.8k
  info->palette = 0;
3009
19.8k
  info->palettesize = 0;
3010
19.8k
}
3011
3012
unsigned lodepng_palette_add(LodePNGColorMode* info,
3013
0
                             unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
3014
0
  if(!info->palette) /*allocate palette if empty*/ {
3015
0
    lodepng_color_mode_alloc_palette(info);
3016
0
    if(!info->palette) return 83; /*alloc fail*/
3017
0
  }
3018
0
  if(info->palettesize >= 256) {
3019
0
    return 108; /*too many palette values*/
3020
0
  }
3021
0
  info->palette[4 * info->palettesize + 0] = r;
3022
0
  info->palette[4 * info->palettesize + 1] = g;
3023
0
  info->palette[4 * info->palettesize + 2] = b;
3024
0
  info->palette[4 * info->palettesize + 3] = a;
3025
0
  ++info->palettesize;
3026
0
  return 0;
3027
0
}
3028
3029
/*calculate bits per pixel out of colortype and bitdepth*/
3030
36.3k
unsigned lodepng_get_bpp(const LodePNGColorMode* info) {
3031
36.3k
  return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
3032
36.3k
}
3033
3034
0
unsigned lodepng_get_channels(const LodePNGColorMode* info) {
3035
0
  return getNumColorChannels(info->colortype);
3036
0
}
3037
3038
0
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) {
3039
0
  return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
3040
0
}
3041
3042
0
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) {
3043
0
  return (info->colortype & 4) != 0; /*4 or 6*/
3044
0
}
3045
3046
0
unsigned lodepng_is_palette_type(const LodePNGColorMode* info) {
3047
0
  return info->colortype == LCT_PALETTE;
3048
0
}
3049
3050
0
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) {
3051
0
  size_t i;
3052
0
  for(i = 0; i != info->palettesize; ++i) {
3053
0
    if(info->palette[i * 4 + 3] < 255) return 1;
3054
0
  }
3055
0
  return 0;
3056
0
}
3057
3058
0
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) {
3059
0
  return info->key_defined
3060
0
      || lodepng_is_alpha_type(info)
3061
0
      || lodepng_has_palette_alpha(info);
3062
0
}
3063
3064
11.7k
static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
3065
11.7k
  size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
3066
11.7k
  size_t n = (size_t)w * (size_t)h;
3067
11.7k
  return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;
3068
11.7k
}
3069
3070
11.7k
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) {
3071
11.7k
  return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
3072
11.7k
}
3073
3074
3075
#ifdef LODEPNG_COMPILE_PNG
3076
3077
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
3078
and in addition has one extra byte per line: the filter byte. So this gives a larger
3079
result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */
3080
31.8k
static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp) {
3081
  /* + 1 for the filter byte, and possibly plus padding bits per line. */
3082
  /* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */
3083
31.8k
  size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;
3084
31.8k
  return (size_t)h * line;
3085
31.8k
}
3086
3087
#ifdef LODEPNG_COMPILE_DECODER
3088
/*Safely checks whether size_t overflow can be caused due to amount of pixels.
3089
This check is overcautious rather than precise. If this check indicates no overflow,
3090
you can safely compute in a size_t (but not an unsigned):
3091
-(size_t)w * (size_t)h * 8
3092
-amount of bytes in IDAT (including filter, padding and Adam7 bytes)
3093
-amount of bytes in raw color model
3094
Returns 1 if overflow possible, 0 if not.
3095
*/
3096
static int lodepng_pixel_overflow(unsigned w, unsigned h,
3097
8.01k
                                  const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) {
3098
8.01k
  size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));
3099
8.01k
  size_t numpixels, total;
3100
8.01k
  size_t line; /* bytes per line in worst case */
3101
3102
8.01k
  if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
3103
8.01k
  if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
3104
3105
  /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */
3106
7.97k
  if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;
3107
7.97k
  if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;
3108
3109
7.97k
  if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
3110
7.97k
  if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
3111
3112
7.95k
  return 0; /* no overflow */
3113
7.97k
}
3114
#endif /*LODEPNG_COMPILE_DECODER*/
3115
#endif /*LODEPNG_COMPILE_PNG*/
3116
3117
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3118
3119
13.2k
static void LodePNGUnknownChunks_init(LodePNGInfo* info) {
3120
13.2k
  unsigned i;
3121
52.8k
  for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
3122
52.8k
  for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
3123
13.2k
}
3124
3125
13.2k
static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) {
3126
13.2k
  unsigned i;
3127
52.8k
  for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
3128
13.2k
}
3129
3130
0
static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) {
3131
0
  unsigned i;
3132
3133
0
  LodePNGUnknownChunks_cleanup(dest);
3134
3135
0
  for(i = 0; i != 3; ++i) {
3136
0
    size_t j;
3137
0
    dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
3138
0
    dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
3139
0
    if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
3140
0
    for(j = 0; j < src->unknown_chunks_size[i]; ++j) {
3141
0
      dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
3142
0
    }
3143
0
  }
3144
3145
0
  return 0;
3146
0
}
3147
3148
/******************************************************************************/
3149
3150
13.2k
static void LodePNGText_init(LodePNGInfo* info) {
3151
13.2k
  info->text_num = 0;
3152
13.2k
  info->text_keys = NULL;
3153
13.2k
  info->text_strings = NULL;
3154
13.2k
}
3155
3156
13.2k
static void LodePNGText_cleanup(LodePNGInfo* info) {
3157
13.2k
  size_t i;
3158
109k
  for(i = 0; i != info->text_num; ++i) {
3159
96.3k
    lodepng_free(info->text_keys[i]);
3160
96.3k
    lodepng_free(info->text_strings[i]);
3161
96.3k
  }
3162
13.2k
  lodepng_free(info->text_keys);
3163
13.2k
  lodepng_free(info->text_strings);
3164
13.2k
}
3165
3166
0
static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
3167
0
  size_t i = 0;
3168
0
  dest->text_keys = NULL;
3169
0
  dest->text_strings = NULL;
3170
0
  dest->text_num = 0;
3171
0
  for(i = 0; i != source->text_num; ++i) {
3172
0
    CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
3173
0
  }
3174
0
  return 0;
3175
0
}
3176
3177
96.3k
static unsigned lodepng_add_text_sized(LodePNGInfo* info, const char* key, const char* str, size_t size) {
3178
96.3k
  char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
3179
96.3k
  char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
3180
3181
96.3k
  if(new_keys) info->text_keys = new_keys;
3182
96.3k
  if(new_strings) info->text_strings = new_strings;
3183
3184
96.3k
  if(!new_keys || !new_strings) return 83; /*alloc fail*/
3185
3186
96.3k
  ++info->text_num;
3187
96.3k
  info->text_keys[info->text_num - 1] = alloc_string(key);
3188
96.3k
  info->text_strings[info->text_num - 1] = alloc_string_sized(str, size);
3189
96.3k
  if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/
3190
3191
96.3k
  return 0;
3192
96.3k
}
3193
3194
95.5k
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) {
3195
95.5k
  return lodepng_add_text_sized(info, key, str, lodepng_strlen(str));
3196
95.5k
}
3197
3198
0
void lodepng_clear_text(LodePNGInfo* info) {
3199
0
  LodePNGText_cleanup(info);
3200
  /*cleanup only deconstructs, need to init again to set appropriate pointers to NULL*/
3201
0
  LodePNGText_init(info);
3202
0
}
3203
3204
/******************************************************************************/
3205
3206
13.2k
static void LodePNGIText_init(LodePNGInfo* info) {
3207
13.2k
  info->itext_num = 0;
3208
13.2k
  info->itext_keys = NULL;
3209
13.2k
  info->itext_langtags = NULL;
3210
13.2k
  info->itext_transkeys = NULL;
3211
13.2k
  info->itext_strings = NULL;
3212
13.2k
}
3213
3214
13.2k
static void LodePNGIText_cleanup(LodePNGInfo* info) {
3215
13.2k
  size_t i;
3216
108k
  for(i = 0; i != info->itext_num; ++i) {
3217
95.0k
    lodepng_free(info->itext_keys[i]);
3218
95.0k
    lodepng_free(info->itext_langtags[i]);
3219
95.0k
    lodepng_free(info->itext_transkeys[i]);
3220
95.0k
    lodepng_free(info->itext_strings[i]);
3221
95.0k
  }
3222
13.2k
  lodepng_free(info->itext_keys);
3223
13.2k
  lodepng_free(info->itext_langtags);
3224
13.2k
  lodepng_free(info->itext_transkeys);
3225
13.2k
  lodepng_free(info->itext_strings);
3226
13.2k
}
3227
3228
0
static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
3229
0
  size_t i = 0;
3230
0
  dest->itext_keys = NULL;
3231
0
  dest->itext_langtags = NULL;
3232
0
  dest->itext_transkeys = NULL;
3233
0
  dest->itext_strings = NULL;
3234
0
  dest->itext_num = 0;
3235
0
  for(i = 0; i != source->itext_num; ++i) {
3236
0
    CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
3237
0
                                        source->itext_transkeys[i], source->itext_strings[i]));
3238
0
  }
3239
0
  return 0;
3240
0
}
3241
3242
0
void lodepng_clear_itext(LodePNGInfo* info) {
3243
0
  LodePNGIText_cleanup(info);
3244
  /*cleanup only deconstructs, need to init again to set appropriate pointers to NULL*/
3245
0
  LodePNGIText_init(info);
3246
0
}
3247
3248
static unsigned lodepng_add_itext_sized(LodePNGInfo* info, const char* key, const char* langtag,
3249
95.0k
                                        const char* transkey, const char* str, size_t size) {
3250
95.0k
  char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
3251
95.0k
  char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
3252
95.0k
  char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
3253
95.0k
  char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
3254
3255
95.0k
  if(new_keys) info->itext_keys = new_keys;
3256
95.0k
  if(new_langtags) info->itext_langtags = new_langtags;
3257
95.0k
  if(new_transkeys) info->itext_transkeys = new_transkeys;
3258
95.0k
  if(new_strings) info->itext_strings = new_strings;
3259
3260
95.0k
  if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/
3261
3262
95.0k
  ++info->itext_num;
3263
3264
95.0k
  info->itext_keys[info->itext_num - 1] = alloc_string(key);
3265
95.0k
  info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);
3266
95.0k
  info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);
3267
95.0k
  info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size);
3268
3269
95.0k
  return 0;
3270
95.0k
}
3271
3272
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
3273
0
                           const char* transkey, const char* str) {
3274
0
  return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str));
3275
0
}
3276
3277
0
unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
3278
0
  if(info->iccp_defined) lodepng_clear_icc(info);
3279
3280
0
  if(profile_size == 0) return 123; /*invalid ICC profile size*/
3281
3282
0
  info->iccp_name = alloc_string(name);
3283
0
  if(!info->iccp_name) return 83; /*alloc fail*/
3284
3285
0
  info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size);
3286
0
  if(!info->iccp_profile) {
3287
0
    lodepng_free(info->iccp_name);
3288
0
    return 83; /*alloc fail*/
3289
0
  }
3290
3291
0
  lodepng_memcpy(info->iccp_profile, profile, profile_size);
3292
0
  info->iccp_profile_size = profile_size;
3293
0
  info->iccp_defined = 1;
3294
3295
0
  return 0; /*ok*/
3296
0
}
3297
3298
27.3k
static void lodepng_init_icc(LodePNGInfo* info) {
3299
27.3k
  info->iccp_defined = 0;
3300
27.3k
  info->iccp_name = NULL;
3301
27.3k
  info->iccp_profile = NULL;
3302
27.3k
  info->iccp_profile_size = 0;
3303
27.3k
}
3304
3305
14.1k
void lodepng_clear_icc(LodePNGInfo* info) {
3306
14.1k
  lodepng_free(info->iccp_name);
3307
14.1k
  lodepng_free(info->iccp_profile);
3308
14.1k
  lodepng_init_icc(info);
3309
14.1k
}
3310
3311
944
unsigned lodepng_set_exif(LodePNGInfo* info, const unsigned char* exif, unsigned exif_size) {
3312
944
  if(info->exif_defined) lodepng_clear_exif(info);
3313
944
  info->exif = (unsigned char*)lodepng_malloc(exif_size);
3314
3315
944
  if(!info->exif) return 83; /*alloc fail*/
3316
3317
944
  lodepng_memcpy(info->exif, exif, exif_size);
3318
944
  info->exif_size = exif_size;
3319
944
  info->exif_defined = 1;
3320
3321
944
  return 0; /*ok*/
3322
944
}
3323
3324
27.2k
static void lodepng_init_exif(LodePNGInfo* info) {
3325
27.2k
  info->exif_defined = 0;
3326
27.2k
  info->exif = NULL;
3327
27.2k
  info->exif_size = 0;
3328
27.2k
}
3329
3330
14.0k
void lodepng_clear_exif(LodePNGInfo* info) {
3331
14.0k
  lodepng_free(info->exif);
3332
14.0k
  lodepng_init_exif(info);
3333
14.0k
}
3334
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3335
3336
13.2k
void lodepng_info_init(LodePNGInfo* info) {
3337
13.2k
  lodepng_color_mode_init(&info->color);
3338
13.2k
  info->interlace_method = 0;
3339
13.2k
  info->compression_method = 0;
3340
13.2k
  info->filter_method = 0;
3341
13.2k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3342
13.2k
  info->background_defined = 0;
3343
13.2k
  info->background_r = info->background_g = info->background_b = 0;
3344
3345
13.2k
  LodePNGText_init(info);
3346
13.2k
  LodePNGIText_init(info);
3347
13.2k
  lodepng_init_icc(info);
3348
13.2k
  lodepng_init_exif(info);
3349
3350
13.2k
  info->time_defined = 0;
3351
13.2k
  info->phys_defined = 0;
3352
3353
13.2k
  info->gama_defined = 0;
3354
13.2k
  info->chrm_defined = 0;
3355
13.2k
  info->srgb_defined = 0;
3356
13.2k
  info->cicp_defined = 0;
3357
13.2k
  info->cicp_color_primaries = 0;
3358
13.2k
  info->cicp_transfer_function = 0;
3359
13.2k
  info->cicp_matrix_coefficients = 0;
3360
13.2k
  info->cicp_video_full_range_flag = 0;
3361
13.2k
  info->mdcv_defined = 0;
3362
13.2k
  info->mdcv_red_x = 0;
3363
13.2k
  info->mdcv_red_y = 0;
3364
13.2k
  info->mdcv_green_x = 0;
3365
13.2k
  info->mdcv_green_y = 0;
3366
13.2k
  info->mdcv_blue_x = 0;
3367
13.2k
  info->mdcv_blue_y = 0;
3368
13.2k
  info->mdcv_white_x = 0;
3369
13.2k
  info->mdcv_white_y = 0;
3370
13.2k
  info->mdcv_max_luminance = 0;
3371
13.2k
  info->mdcv_min_luminance = 0;
3372
13.2k
  info->clli_defined = 0;
3373
13.2k
  info->clli_max_cll = 0;
3374
13.2k
  info->clli_max_fall = 0;
3375
3376
13.2k
  info->sbit_defined = 0;
3377
13.2k
  info->sbit_r = info->sbit_g = info->sbit_b = info->sbit_a = 0;
3378
3379
13.2k
  LodePNGUnknownChunks_init(info);
3380
13.2k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3381
13.2k
}
3382
3383
13.2k
void lodepng_info_cleanup(LodePNGInfo* info) {
3384
13.2k
  lodepng_color_mode_cleanup(&info->color);
3385
13.2k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3386
13.2k
  LodePNGText_cleanup(info);
3387
13.2k
  LodePNGIText_cleanup(info);
3388
3389
13.2k
  lodepng_clear_icc(info);
3390
13.2k
  lodepng_clear_exif(info);
3391
3392
13.2k
  LodePNGUnknownChunks_cleanup(info);
3393
13.2k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3394
13.2k
}
3395
3396
0
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
3397
0
  lodepng_info_cleanup(dest);
3398
0
  lodepng_memcpy(dest, source, sizeof(LodePNGInfo));
3399
3400
  /*ensure to initialize all fields pointing to allocated data to NULL first*/
3401
0
  lodepng_color_mode_init(&dest->color);
3402
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3403
0
  LodePNGText_init(dest);
3404
0
  LodePNGIText_init(dest);
3405
0
  lodepng_init_icc(dest);
3406
0
  lodepng_init_exif(dest);
3407
0
  LodePNGUnknownChunks_init(dest);
3408
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3409
3410
0
  CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
3411
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3412
0
  CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
3413
0
  CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
3414
0
  if(source->iccp_defined) {
3415
0
    CERROR_TRY_RETURN(lodepng_set_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));
3416
0
  }
3417
0
  if(source->exif_defined) {
3418
0
    CERROR_TRY_RETURN(lodepng_set_exif(dest, source->exif, source->exif_size));
3419
0
  }
3420
0
  CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
3421
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3422
3423
0
  return 0;
3424
0
}
3425
3426
/* ////////////////////////////////////////////////////////////////////////// */
3427
3428
/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
3429
0
static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) {
3430
0
  unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
3431
  /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
3432
0
  unsigned p = index & m;
3433
0
  in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
3434
0
  in = in << (bits * (m - p));
3435
0
  if(p == 0) out[index * bits / 8u] = in;
3436
0
  else out[index * bits / 8u] |= in;
3437
0
}
3438
3439
typedef struct ColorTree ColorTree;
3440
3441
/*
3442
One node of a color tree
3443
This is the data structure used to count the number of unique colors and to get a palette
3444
index for a color. It's like an octree, but because the alpha channel is used too, each
3445
node has 16 instead of 8 children.
3446
*/
3447
struct ColorTree {
3448
  ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
3449
  int index; /*the payload. Only has a meaningful value if this is in the last level*/
3450
};
3451
3452
10.2k
static void color_tree_init(ColorTree* tree) {
3453
10.2k
  lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children));
3454
10.2k
  tree->index = -1;
3455
10.2k
}
3456
3457
10.2k
static void color_tree_cleanup(ColorTree* tree) {
3458
10.2k
  int i;
3459
174k
  for(i = 0; i != 16; ++i) {
3460
164k
    if(tree->children[i]) {
3461
10.1k
      color_tree_cleanup(tree->children[i]);
3462
10.1k
      lodepng_free(tree->children[i]);
3463
10.1k
    }
3464
164k
  }
3465
10.2k
}
3466
3467
/*returns -1 if color not present, its index otherwise*/
3468
1.57k
static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
3469
1.57k
  int bit = 0;
3470
13.3k
  for(bit = 0; bit < 8; ++bit) {
3471
11.8k
    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3472
11.8k
    if(!tree->children[i]) return -1;
3473
11.7k
    else tree = tree->children[i];
3474
11.8k
  }
3475
1.45k
  return tree ? tree->index : -1;
3476
1.57k
}
3477
3478
#ifdef LODEPNG_COMPILE_ENCODER
3479
0
static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
3480
0
  return color_tree_get(tree, r, g, b, a) >= 0;
3481
0
}
3482
#endif /*LODEPNG_COMPILE_ENCODER*/
3483
3484
/*color is not allowed to already exist.
3485
Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")
3486
Returns error code, or 0 if ok*/
3487
static unsigned color_tree_add(ColorTree* tree,
3488
2.33k
                               unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) {
3489
2.33k
  int bit;
3490
20.9k
  for(bit = 0; bit < 8; ++bit) {
3491
18.6k
    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
3492
18.6k
    if(!tree->children[i]) {
3493
10.1k
      tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
3494
10.1k
      if(!tree->children[i]) return 83; /*alloc fail*/
3495
10.1k
      color_tree_init(tree->children[i]);
3496
10.1k
    }
3497
18.6k
    tree = tree->children[i];
3498
18.6k
  }
3499
2.33k
  tree->index = (int)index;
3500
2.33k
  return 0;
3501
2.33k
}
3502
3503
/*put a pixel, given its RGBA color, into image of any color type*/
3504
static unsigned rgba8ToPixel(unsigned char* out, size_t i,
3505
                             const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
3506
43.0M
                             unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
3507
43.0M
  if(mode->colortype == LCT_GREY) {
3508
14.0M
    unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
3509
14.0M
    if(mode->bitdepth == 8) out[i] = gray;
3510
0
    else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
3511
0
    else {
3512
      /*take the most significant bits of gray*/
3513
0
      gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u);
3514
0
      addColorBits(out, i, mode->bitdepth, gray);
3515
0
    }
3516
28.9M
  } else if(mode->colortype == LCT_RGB) {
3517
14.4M
    if(mode->bitdepth == 8) {
3518
0
      out[i * 3 + 0] = r;
3519
0
      out[i * 3 + 1] = g;
3520
0
      out[i * 3 + 2] = b;
3521
14.4M
    } else {
3522
14.4M
      out[i * 6 + 0] = out[i * 6 + 1] = r;
3523
14.4M
      out[i * 6 + 2] = out[i * 6 + 3] = g;
3524
14.4M
      out[i * 6 + 4] = out[i * 6 + 5] = b;
3525
14.4M
    }
3526
14.5M
  } else if(mode->colortype == LCT_PALETTE) {
3527
1.57k
    int index = color_tree_get(tree, r, g, b, a);
3528
1.57k
    if(index < 0) return 82; /*color not in palette*/
3529
1.45k
    if(mode->bitdepth == 8) out[i] = index;
3530
0
    else addColorBits(out, i, mode->bitdepth, (unsigned)index);
3531
14.5M
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3532
14.4M
    unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
3533
14.4M
    if(mode->bitdepth == 8) {
3534
14.4M
      out[i * 2 + 0] = gray;
3535
14.4M
      out[i * 2 + 1] = a;
3536
14.4M
    } else if(mode->bitdepth == 16) {
3537
0
      out[i * 4 + 0] = out[i * 4 + 1] = gray;
3538
0
      out[i * 4 + 2] = out[i * 4 + 3] = a;
3539
0
    }
3540
14.4M
  } else if(mode->colortype == LCT_RGBA) {
3541
104k
    if(mode->bitdepth == 8) {
3542
0
      out[i * 4 + 0] = r;
3543
0
      out[i * 4 + 1] = g;
3544
0
      out[i * 4 + 2] = b;
3545
0
      out[i * 4 + 3] = a;
3546
104k
    } else {
3547
104k
      out[i * 8 + 0] = out[i * 8 + 1] = r;
3548
104k
      out[i * 8 + 2] = out[i * 8 + 3] = g;
3549
104k
      out[i * 8 + 4] = out[i * 8 + 5] = b;
3550
104k
      out[i * 8 + 6] = out[i * 8 + 7] = a;
3551
104k
    }
3552
104k
  }
3553
3554
43.0M
  return 0; /*no error*/
3555
43.0M
}
3556
3557
/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3558
static void rgba16ToPixel(unsigned char* out, size_t i,
3559
                         const LodePNGColorMode* mode,
3560
110k
                         unsigned short r, unsigned short g, unsigned short b, unsigned short a) {
3561
110k
  if(mode->colortype == LCT_GREY) {
3562
0
    unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
3563
0
    out[i * 2 + 0] = (gray >> 8) & 255;
3564
0
    out[i * 2 + 1] = gray & 255;
3565
110k
  } else if(mode->colortype == LCT_RGB) {
3566
66.2k
    out[i * 6 + 0] = (r >> 8) & 255;
3567
66.2k
    out[i * 6 + 1] = r & 255;
3568
66.2k
    out[i * 6 + 2] = (g >> 8) & 255;
3569
66.2k
    out[i * 6 + 3] = g & 255;
3570
66.2k
    out[i * 6 + 4] = (b >> 8) & 255;
3571
66.2k
    out[i * 6 + 5] = b & 255;
3572
66.2k
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3573
0
    unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
3574
0
    out[i * 4 + 0] = (gray >> 8) & 255;
3575
0
    out[i * 4 + 1] = gray & 255;
3576
0
    out[i * 4 + 2] = (a >> 8) & 255;
3577
0
    out[i * 4 + 3] = a & 255;
3578
44.5k
  } else if(mode->colortype == LCT_RGBA) {
3579
44.5k
    out[i * 8 + 0] = (r >> 8) & 255;
3580
44.5k
    out[i * 8 + 1] = r & 255;
3581
44.5k
    out[i * 8 + 2] = (g >> 8) & 255;
3582
44.5k
    out[i * 8 + 3] = g & 255;
3583
44.5k
    out[i * 8 + 4] = (b >> 8) & 255;
3584
44.5k
    out[i * 8 + 5] = b & 255;
3585
44.5k
    out[i * 8 + 6] = (a >> 8) & 255;
3586
44.5k
    out[i * 8 + 7] = a & 255;
3587
44.5k
  }
3588
110k
}
3589
3590
/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3591
static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
3592
                               unsigned char* b, unsigned char* a,
3593
                               const unsigned char* in, size_t i,
3594
43.0M
                               const LodePNGColorMode* mode) {
3595
43.0M
  if(mode->colortype == LCT_GREY) {
3596
43.0M
    if(mode->bitdepth == 8) {
3597
84.8k
      *r = *g = *b = in[i];
3598
84.8k
      if(mode->key_defined && *r == mode->key_r) *a = 0;
3599
84.5k
      else *a = 255;
3600
42.9M
    } else if(mode->bitdepth == 16) {
3601
2.02k
      *r = *g = *b = in[i * 2 + 0];
3602
2.02k
      if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3603
1.77k
      else *a = 255;
3604
42.9M
    } else {
3605
42.9M
      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3606
42.9M
      size_t j = i * mode->bitdepth;
3607
42.9M
      unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3608
42.9M
      *r = *g = *b = (value * 255) / highest;
3609
42.9M
      if(mode->key_defined && value == mode->key_r) *a = 0;
3610
42.9M
      else *a = 255;
3611
42.9M
    }
3612
43.0M
  } else if(mode->colortype == LCT_RGB) {
3613
9.49k
    if(mode->bitdepth == 8) {
3614
4.38k
      *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3615
4.38k
      if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3616
4.08k
      else *a = 255;
3617
5.11k
    } else {
3618
5.11k
      *r = in[i * 6 + 0];
3619
5.11k
      *g = in[i * 6 + 2];
3620
5.11k
      *b = in[i * 6 + 4];
3621
5.11k
      if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3622
819
         && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3623
482
         && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3624
4.90k
      else *a = 255;
3625
5.11k
    }
3626
37.6k
  } else if(mode->colortype == LCT_PALETTE) {
3627
1.60k
    unsigned index;
3628
1.60k
    if(mode->bitdepth == 8) index = in[i];
3629
1.28k
    else {
3630
1.28k
      size_t j = i * mode->bitdepth;
3631
1.28k
      index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3632
1.28k
    }
3633
    /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
3634
1.60k
    *r = mode->palette[index * 4 + 0];
3635
1.60k
    *g = mode->palette[index * 4 + 1];
3636
1.60k
    *b = mode->palette[index * 4 + 2];
3637
1.60k
    *a = mode->palette[index * 4 + 3];
3638
35.9k
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3639
33.7k
    if(mode->bitdepth == 8) {
3640
1.41k
      *r = *g = *b = in[i * 2 + 0];
3641
1.41k
      *a = in[i * 2 + 1];
3642
32.3k
    } else {
3643
32.3k
      *r = *g = *b = in[i * 4 + 0];
3644
32.3k
      *a = in[i * 4 + 2];
3645
32.3k
    }
3646
33.7k
  } else if(mode->colortype == LCT_RGBA) {
3647
2.26k
    if(mode->bitdepth == 8) {
3648
1.46k
      *r = in[i * 4 + 0];
3649
1.46k
      *g = in[i * 4 + 1];
3650
1.46k
      *b = in[i * 4 + 2];
3651
1.46k
      *a = in[i * 4 + 3];
3652
1.46k
    } else {
3653
800
      *r = in[i * 8 + 0];
3654
800
      *g = in[i * 8 + 2];
3655
800
      *b = in[i * 8 + 4];
3656
800
      *a = in[i * 8 + 6];
3657
800
    }
3658
2.26k
  }
3659
43.0M
}
3660
3661
/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
3662
mode test cases, optimized to convert the colors much faster, when converting
3663
to the common case of RGBA with 8 bit per channel. buffer must be RGBA with
3664
enough memory.*/
3665
static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
3666
                                const unsigned char* LODEPNG_RESTRICT in,
3667
428
                                const LodePNGColorMode* mode) {
3668
428
  unsigned num_channels = 4;
3669
428
  size_t i;
3670
428
  if(mode->colortype == LCT_GREY) {
3671
155
    if(mode->bitdepth == 8) {
3672
134k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3673
134k
        buffer[0] = buffer[1] = buffer[2] = in[i];
3674
134k
        buffer[3] = 255;
3675
134k
      }
3676
42
      if(mode->key_defined) {
3677
23
        buffer -= numpixels * num_channels;
3678
2.41k
        for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3679
2.39k
          if(buffer[0] == mode->key_r) buffer[3] = 0;
3680
2.39k
        }
3681
23
      }
3682
113
    } else if(mode->bitdepth == 16) {
3683
2.25k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3684
2.22k
        buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3685
2.22k
        buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
3686
2.22k
      }
3687
75
    } else {
3688
75
      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3689
75
      size_t j = 0;
3690
898k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3691
898k
        unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3692
898k
        buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3693
898k
        buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
3694
898k
      }
3695
75
    }
3696
273
  } else if(mode->colortype == LCT_RGB) {
3697
191
    if(mode->bitdepth == 8) {
3698
3.65k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3699
3.55k
        lodepng_memcpy(buffer, &in[i * 3], 3);
3700
3.55k
        buffer[3] = 255;
3701
3.55k
      }
3702
103
      if(mode->key_defined) {
3703
80
        buffer -= numpixels * num_channels;
3704
2.11k
        for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3705
2.03k
          if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;
3706
2.03k
        }
3707
80
      }
3708
103
    } else {
3709
3.28k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3710
3.19k
        buffer[0] = in[i * 6 + 0];
3711
3.19k
        buffer[1] = in[i * 6 + 2];
3712
3.19k
        buffer[2] = in[i * 6 + 4];
3713
3.19k
        buffer[3] = mode->key_defined
3714
2.59k
           && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3715
782
           && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3716
3.12k
           && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
3717
3.19k
      }
3718
88
    }
3719
191
  } else if(mode->colortype == LCT_PALETTE) {
3720
28
    if(mode->bitdepth == 8) {
3721
338
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3722
329
        unsigned index = in[i];
3723
        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
3724
329
        lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
3725
329
      }
3726
19
    } else {
3727
19
      size_t j = 0;
3728
3.18k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3729
3.16k
        unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3730
        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
3731
3.16k
        lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
3732
3.16k
      }
3733
19
    }
3734
54
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3735
36
    if(mode->bitdepth == 8) {
3736
924
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3737
902
        buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3738
902
        buffer[3] = in[i * 2 + 1];
3739
902
      }
3740
22
    } else {
3741
103k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3742
103k
        buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3743
103k
        buffer[3] = in[i * 4 + 2];
3744
103k
      }
3745
14
    }
3746
36
  } else if(mode->colortype == LCT_RGBA) {
3747
18
    if(mode->bitdepth == 8) {
3748
0
      lodepng_memcpy(buffer, in, numpixels * 4);
3749
18
    } else {
3750
35.2k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3751
35.2k
        buffer[0] = in[i * 8 + 0];
3752
35.2k
        buffer[1] = in[i * 8 + 2];
3753
35.2k
        buffer[2] = in[i * 8 + 4];
3754
35.2k
        buffer[3] = in[i * 8 + 6];
3755
35.2k
      }
3756
18
    }
3757
18
  }
3758
428
}
3759
3760
/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/
3761
static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
3762
                               const unsigned char* LODEPNG_RESTRICT in,
3763
207
                               const LodePNGColorMode* mode) {
3764
207
  const unsigned num_channels = 3;
3765
207
  size_t i;
3766
207
  if(mode->colortype == LCT_GREY) {
3767
88
    if(mode->bitdepth == 8) {
3768
132k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3769
132k
        buffer[0] = buffer[1] = buffer[2] = in[i];
3770
132k
      }
3771
65
    } else if(mode->bitdepth == 16) {
3772
1.73k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3773
1.71k
        buffer[0] = buffer[1] = buffer[2] = in[i * 2];
3774
1.71k
      }
3775
42
    } else {
3776
42
      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3777
42
      size_t j = 0;
3778
14.6M
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3779
14.6M
        unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3780
14.6M
        buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
3781
14.6M
      }
3782
42
    }
3783
119
  } else if(mode->colortype == LCT_RGB) {
3784
22
    if(mode->bitdepth == 8) {
3785
0
      lodepng_memcpy(buffer, in, numpixels * 3);
3786
22
    } else {
3787
1.03k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3788
1.01k
        buffer[0] = in[i * 6 + 0];
3789
1.01k
        buffer[1] = in[i * 6 + 2];
3790
1.01k
        buffer[2] = in[i * 6 + 4];
3791
1.01k
      }
3792
22
    }
3793
97
  } else if(mode->colortype == LCT_PALETTE) {
3794
35
    if(mode->bitdepth == 8) {
3795
22.8k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3796
22.8k
        unsigned index = in[i];
3797
        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
3798
22.8k
        lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
3799
22.8k
      }
3800
21
    } else {
3801
21
      size_t j = 0;
3802
3.27k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3803
3.25k
        unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3804
        /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
3805
3.25k
        lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
3806
3.25k
      }
3807
21
    }
3808
62
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3809
35
    if(mode->bitdepth == 8) {
3810
509
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3811
497
        buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
3812
497
      }
3813
23
    } else {
3814
39.8k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3815
39.7k
        buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
3816
39.7k
      }
3817
23
    }
3818
35
  } else if(mode->colortype == LCT_RGBA) {
3819
27
    if(mode->bitdepth == 8) {
3820
321
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3821
312
        lodepng_memcpy(buffer, &in[i * 4], 3);
3822
312
      }
3823
18
    } else {
3824
12.2k
      for(i = 0; i != numpixels; ++i, buffer += num_channels) {
3825
12.2k
        buffer[0] = in[i * 8 + 0];
3826
12.2k
        buffer[1] = in[i * 8 + 2];
3827
12.2k
        buffer[2] = in[i * 8 + 4];
3828
12.2k
      }
3829
18
    }
3830
27
  }
3831
207
}
3832
3833
/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3834
given color type, but the given color type must be 16-bit itself.*/
3835
static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3836
110k
                                const unsigned char* in, size_t i, const LodePNGColorMode* mode) {
3837
110k
  if(mode->colortype == LCT_GREY) {
3838
1.77k
    *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3839
1.77k
    if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3840
1.51k
    else *a = 65535;
3841
109k
  } else if(mode->colortype == LCT_RGB) {
3842
3.96k
    *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
3843
3.96k
    *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
3844
3.96k
    *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
3845
3.96k
    if(mode->key_defined
3846
2.60k
       && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3847
1.01k
       && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3848
632
       && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3849
3.75k
    else *a = 65535;
3850
105k
  } else if(mode->colortype == LCT_GREY_ALPHA) {
3851
104k
    *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
3852
104k
    *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
3853
104k
  } else if(mode->colortype == LCT_RGBA) {
3854
694
    *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
3855
694
    *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
3856
694
    *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
3857
694
    *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
3858
694
  }
3859
110k
}
3860
3861
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3862
                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
3863
1.47k
                         unsigned w, unsigned h) {
3864
1.47k
  size_t i;
3865
1.47k
  ColorTree tree;
3866
1.47k
  size_t numpixels = (size_t)w * (size_t)h;
3867
1.47k
  unsigned error = 0;
3868
3869
1.47k
  if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) {
3870
0
    return 107; /* error: must provide palette if input mode is palette */
3871
0
  }
3872
3873
1.47k
  if(lodepng_color_mode_equal(mode_out, mode_in)) {
3874
0
    size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3875
0
    lodepng_memcpy(out, in, numbytes);
3876
0
    return 0;
3877
0
  }
3878
3879
1.47k
  if(mode_out->colortype == LCT_PALETTE) {
3880
149
    size_t palettesize = mode_out->palettesize;
3881
149
    const unsigned char* palette = mode_out->palette;
3882
149
    size_t palsize = (size_t)1u << mode_out->bitdepth;
3883
    /*if the user specified output palette but did not give the values, assume
3884
    they want the values of the input color type (assuming that one is palette).
3885
    Note that we never create a new palette ourselves.*/
3886
149
    if(palettesize == 0) {
3887
78
      palettesize = mode_in->palettesize;
3888
78
      palette = mode_in->palette;
3889
      /*if the input was also palette with same bitdepth, then the color types are also
3890
      equal, so copy literally. This to preserve the exact indices that were in the PNG
3891
      even in case there are duplicate colors in the palette.*/
3892
78
      if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
3893
0
        size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3894
0
        lodepng_memcpy(out, in, numbytes);
3895
0
        return 0;
3896
0
      }
3897
78
    }
3898
149
    if(palettesize < palsize) palsize = palettesize;
3899
149
    color_tree_init(&tree);
3900
2.48k
    for(i = 0; i != palsize; ++i) {
3901
2.33k
      const unsigned char* p = &palette[i * 4];
3902
2.33k
      error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
3903
2.33k
      if(error) break;
3904
2.33k
    }
3905
149
  }
3906
3907
1.47k
  if(!error) {
3908
1.47k
    if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
3909
110k
      for(i = 0; i != numpixels; ++i) {
3910
110k
        unsigned short r = 0, g = 0, b = 0, a = 0;
3911
110k
        getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3912
110k
        rgba16ToPixel(out, i, mode_out, r, g, b, a);
3913
110k
      }
3914
1.28k
    } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
3915
428
      getPixelColorsRGBA8(out, numpixels, in, mode_in);
3916
858
    } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
3917
207
      getPixelColorsRGB8(out, numpixels, in, mode_in);
3918
651
    } else {
3919
651
      unsigned char r = 0, g = 0, b = 0, a = 0;
3920
43.0M
      for(i = 0; i != numpixels; ++i) {
3921
43.0M
        getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3922
43.0M
        error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
3923
43.0M
        if(error) break;
3924
43.0M
      }
3925
651
    }
3926
1.47k
  }
3927
3928
1.47k
  if(mode_out->colortype == LCT_PALETTE) {
3929
149
    color_tree_cleanup(&tree);
3930
149
  }
3931
3932
1.47k
  return error;
3933
1.47k
}
3934
3935
3936
/* Converts a single rgb color without alpha from one type to another, color bits truncated to
3937
their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow
3938
function, do not use to process all pixels of an image. Alpha channel not supported on purpose:
3939
this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the
3940
specification it looks like bKGD should ignore the alpha values of the palette since it can use
3941
any palette index but doesn't have an alpha channel. Idem with ignoring color key. */
3942
unsigned lodepng_convert_rgb(
3943
    unsigned* r_out, unsigned* g_out, unsigned* b_out,
3944
    unsigned r_in, unsigned g_in, unsigned b_in,
3945
0
    const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) {
3946
0
  unsigned r = 0, g = 0, b = 0;
3947
0
  unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/
3948
0
  unsigned shift = 16 - mode_out->bitdepth;
3949
3950
0
  if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {
3951
0
    r = g = b = r_in * mul;
3952
0
  } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {
3953
0
    r = r_in * mul;
3954
0
    g = g_in * mul;
3955
0
    b = b_in * mul;
3956
0
  } else if(mode_in->colortype == LCT_PALETTE) {
3957
0
    if(r_in >= mode_in->palettesize) return 82;
3958
0
    r = mode_in->palette[r_in * 4 + 0] * 257u;
3959
0
    g = mode_in->palette[r_in * 4 + 1] * 257u;
3960
0
    b = mode_in->palette[r_in * 4 + 2] * 257u;
3961
0
  } else {
3962
0
    return 31;
3963
0
  }
3964
3965
  /* now convert to output format */
3966
0
  if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {
3967
0
    *r_out = r >> shift ;
3968
0
  } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {
3969
0
    *r_out = r >> shift ;
3970
0
    *g_out = g >> shift ;
3971
0
    *b_out = b >> shift ;
3972
0
  } else if(mode_out->colortype == LCT_PALETTE) {
3973
0
    unsigned i;
3974
    /* a 16-bit color cannot be in the palette */
3975
0
    if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;
3976
0
    for(i = 0; i < mode_out->palettesize; i++) {
3977
0
      unsigned j = i * 4;
3978
0
      if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&
3979
0
          (b >> 8) == mode_out->palette[j + 2]) {
3980
0
        *r_out = i;
3981
0
        return 0;
3982
0
      }
3983
0
    }
3984
0
    return 82;
3985
0
  } else {
3986
0
    return 31;
3987
0
  }
3988
3989
0
  return 0;
3990
0
}
3991
3992
#ifdef LODEPNG_COMPILE_ENCODER
3993
3994
0
void lodepng_color_stats_init(LodePNGColorStats* stats) {
3995
  /*stats*/
3996
0
  stats->colored = 0;
3997
0
  stats->key = 0;
3998
0
  stats->key_r = stats->key_g = stats->key_b = 0;
3999
0
  stats->alpha = 0;
4000
0
  stats->numcolors = 0;
4001
0
  stats->bits = 1;
4002
0
  stats->numpixels = 0;
4003
  /*settings*/
4004
0
  stats->allow_palette = 1;
4005
0
  stats->allow_greyscale = 1;
4006
0
}
4007
4008
/*function used for debug purposes with C++*/
4009
/*void printColorStats(LodePNGColorStats* p) {
4010
  std::cout << "colored: " << (int)p->colored << ", ";
4011
  std::cout << "key: " << (int)p->key << ", ";
4012
  std::cout << "key_r: " << (int)p->key_r << ", ";
4013
  std::cout << "key_g: " << (int)p->key_g << ", ";
4014
  std::cout << "key_b: " << (int)p->key_b << ", ";
4015
  std::cout << "alpha: " << (int)p->alpha << ", ";
4016
  std::cout << "numcolors: " << (int)p->numcolors << ", ";
4017
  std::cout << "bits: " << (int)p->bits << std::endl;
4018
}*/
4019
4020
/*Returns how many bits needed to represent given value (max 8 bit)*/
4021
0
static unsigned getValueRequiredBits(unsigned char value) {
4022
0
  if(value == 0 || value == 255) return 1;
4023
  /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
4024
0
  if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
4025
0
  return 8;
4026
0
}
4027
4028
/*stats must already have been inited. */
4029
unsigned lodepng_compute_color_stats(LodePNGColorStats* stats,
4030
                                     const unsigned char* in, unsigned w, unsigned h,
4031
0
                                     const LodePNGColorMode* mode_in) {
4032
0
  size_t i;
4033
0
  ColorTree tree;
4034
0
  size_t numpixels = (size_t)w * (size_t)h;
4035
0
  unsigned error = 0;
4036
4037
  /* mark things as done already if it would be impossible to have a more expensive case */
4038
0
  unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;
4039
0
  unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;
4040
0
  unsigned numcolors_done = 0;
4041
0
  unsigned bpp = lodepng_get_bpp(mode_in);
4042
0
  unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0;
4043
0
  unsigned sixteen = 0; /* whether the input image is 16 bit */
4044
0
  unsigned maxnumcolors = 257;
4045
0
  if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp));
4046
4047
0
  stats->numpixels += numpixels;
4048
4049
  /*if palette not allowed, no need to compute numcolors*/
4050
0
  if(!stats->allow_palette) numcolors_done = 1;
4051
4052
0
  color_tree_init(&tree);
4053
4054
  /*If the stats was already filled in from previous data, fill its palette in tree
4055
  and mark things as done already if we know they are the most expensive case already*/
4056
0
  if(stats->alpha) alpha_done = 1;
4057
0
  if(stats->colored) colored_done = 1;
4058
0
  if(stats->bits == 16) numcolors_done = 1;
4059
0
  if(stats->bits >= bpp) bits_done = 1;
4060
0
  if(stats->numcolors >= maxnumcolors) numcolors_done = 1;
4061
4062
0
  if(!numcolors_done) {
4063
0
    for(i = 0; i < stats->numcolors; i++) {
4064
0
      const unsigned char* color = &stats->palette[i * 4];
4065
0
      error = color_tree_add(&tree, color[0], color[1], color[2], color[3], (unsigned)i);
4066
0
      if(error) goto cleanup;
4067
0
    }
4068
0
  }
4069
4070
  /*Check if the 16-bit input is truly 16-bit*/
4071
0
  if(mode_in->bitdepth == 16 && !sixteen) {
4072
0
    unsigned short r = 0, g = 0, b = 0, a = 0;
4073
0
    for(i = 0; i != numpixels; ++i) {
4074
0
      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
4075
0
      if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
4076
0
         (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ {
4077
0
        stats->bits = 16;
4078
0
        sixteen = 1;
4079
0
        bits_done = 1;
4080
0
        numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
4081
0
        break;
4082
0
      }
4083
0
    }
4084
0
  }
4085
4086
0
  if(sixteen) {
4087
0
    unsigned short r = 0, g = 0, b = 0, a = 0;
4088
4089
0
    for(i = 0; i != numpixels; ++i) {
4090
0
      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
4091
4092
0
      if(!colored_done && (r != g || r != b)) {
4093
0
        stats->colored = 1;
4094
0
        colored_done = 1;
4095
0
      }
4096
4097
0
      if(!alpha_done) {
4098
0
        unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
4099
0
        if(a != 65535 && (a != 0 || (stats->key && !matchkey))) {
4100
0
          stats->alpha = 1;
4101
0
          stats->key = 0;
4102
0
          alpha_done = 1;
4103
0
        } else if(a == 0 && !stats->alpha && !stats->key) {
4104
0
          stats->key = 1;
4105
0
          stats->key_r = r;
4106
0
          stats->key_g = g;
4107
0
          stats->key_b = b;
4108
0
        } else if(a == 65535 && stats->key && matchkey) {
4109
          /* Color key cannot be used if an opaque pixel also has that RGB color. */
4110
0
          stats->alpha = 1;
4111
0
          stats->key = 0;
4112
0
          alpha_done = 1;
4113
0
        }
4114
0
      }
4115
0
      if(alpha_done && numcolors_done && colored_done && bits_done) break;
4116
0
    }
4117
4118
0
    if(stats->key && !stats->alpha) {
4119
0
      for(i = 0; i != numpixels; ++i) {
4120
0
        getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
4121
0
        if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
4122
          /* Color key cannot be used if an opaque pixel also has that RGB color. */
4123
0
          stats->alpha = 1;
4124
0
          stats->key = 0;
4125
0
          alpha_done = 1;
4126
0
        }
4127
0
      }
4128
0
    }
4129
0
  } else /* < 16-bit */ {
4130
0
    unsigned char r = 0, g = 0, b = 0, a = 0;
4131
0
    unsigned char pr = 0, pg = 0, pb = 0, pa = 0;
4132
0
    for(i = 0; i != numpixels; ++i) {
4133
0
      getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
4134
4135
      /*skip if color same as before, this speeds up large non-photographic
4136
      images with many same colors by avoiding 'color_tree_has' below */
4137
0
      if(i != 0 && r == pr && g == pg && b == pb && a == pa) continue;
4138
0
      pr = r;
4139
0
      pg = g;
4140
0
      pb = b;
4141
0
      pa = a;
4142
4143
0
      if(!bits_done && stats->bits < 8) {
4144
        /*only r is checked, < 8 bits is only relevant for grayscale*/
4145
0
        unsigned bits = getValueRequiredBits(r);
4146
0
        if(bits > stats->bits) stats->bits = bits;
4147
0
      }
4148
0
      bits_done = (stats->bits >= bpp);
4149
4150
0
      if(!colored_done && (r != g || r != b)) {
4151
0
        stats->colored = 1;
4152
0
        colored_done = 1;
4153
0
        if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
4154
0
      }
4155
4156
0
      if(!alpha_done) {
4157
0
        unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
4158
0
        if(a != 255 && (a != 0 || (stats->key && !matchkey))) {
4159
0
          stats->alpha = 1;
4160
0
          stats->key = 0;
4161
0
          alpha_done = 1;
4162
0
          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
4163
0
        } else if(a == 0 && !stats->alpha && !stats->key) {
4164
0
          stats->key = 1;
4165
0
          stats->key_r = r;
4166
0
          stats->key_g = g;
4167
0
          stats->key_b = b;
4168
0
        } else if(a == 255 && stats->key && matchkey) {
4169
          /* Color key cannot be used if an opaque pixel also has that RGB color. */
4170
0
          stats->alpha = 1;
4171
0
          stats->key = 0;
4172
0
          alpha_done = 1;
4173
0
          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
4174
0
        }
4175
0
      }
4176
4177
0
      if(!numcolors_done) {
4178
0
        if(!color_tree_has(&tree, r, g, b, a)) {
4179
0
          error = color_tree_add(&tree, r, g, b, a, stats->numcolors);
4180
0
          if(error) goto cleanup;
4181
0
          if(stats->numcolors < 256) {
4182
0
            unsigned char* p = stats->palette;
4183
0
            unsigned n = stats->numcolors;
4184
0
            p[n * 4 + 0] = r;
4185
0
            p[n * 4 + 1] = g;
4186
0
            p[n * 4 + 2] = b;
4187
0
            p[n * 4 + 3] = a;
4188
0
          }
4189
0
          ++stats->numcolors;
4190
0
          numcolors_done = stats->numcolors >= maxnumcolors;
4191
0
        }
4192
0
      }
4193
4194
0
      if(alpha_done && numcolors_done && colored_done && bits_done) break;
4195
0
    }
4196
4197
0
    if(stats->key && !stats->alpha) {
4198
0
      for(i = 0; i != numpixels; ++i) {
4199
0
        getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
4200
0
        if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
4201
          /* Color key cannot be used if an opaque pixel also has that RGB color. */
4202
0
          stats->alpha = 1;
4203
0
          stats->key = 0;
4204
0
          alpha_done = 1;
4205
0
          if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
4206
0
        }
4207
0
      }
4208
0
    }
4209
4210
    /*make the stats's key always 16-bit for consistency - repeat each byte twice*/
4211
0
    stats->key_r += (stats->key_r << 8);
4212
0
    stats->key_g += (stats->key_g << 8);
4213
0
    stats->key_b += (stats->key_b << 8);
4214
0
  }
4215
4216
0
cleanup:
4217
0
  color_tree_cleanup(&tree);
4218
0
  return error;
4219
0
}
4220
4221
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4222
/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit
4223
(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for
4224
all pixels of an image but only for a few additional values. */
4225
static unsigned lodepng_color_stats_add(LodePNGColorStats* stats,
4226
0
                                        unsigned r, unsigned g, unsigned b, unsigned a) {
4227
0
  unsigned error = 0;
4228
0
  unsigned char image[8];
4229
0
  LodePNGColorMode mode;
4230
0
  lodepng_color_mode_init(&mode);
4231
0
  image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g;
4232
0
  image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a;
4233
0
  mode.bitdepth = 16;
4234
0
  mode.colortype = LCT_RGBA;
4235
0
  error = lodepng_compute_color_stats(stats, image, 1, 1, &mode);
4236
0
  lodepng_color_mode_cleanup(&mode);
4237
0
  return error;
4238
0
}
4239
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4240
4241
/*Computes a minimal PNG color model that can contain all colors as indicated by the stats.
4242
The stats should be computed with lodepng_compute_color_stats.
4243
mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant.
4244
Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image,
4245
e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ...
4246
This is used if auto_convert is enabled (it is by default).
4247
*/
4248
static unsigned auto_choose_color(LodePNGColorMode* mode_out,
4249
                                  const LodePNGColorMode* mode_in,
4250
0
                                  const LodePNGColorStats* stats) {
4251
0
  unsigned error = 0;
4252
0
  unsigned palettebits;
4253
0
  size_t i, n;
4254
0
  size_t numpixels = stats->numpixels;
4255
0
  unsigned palette_ok, gray_ok;
4256
4257
0
  unsigned alpha = stats->alpha;
4258
0
  unsigned key = stats->key;
4259
0
  unsigned bits = stats->bits;
4260
4261
0
  mode_out->key_defined = 0;
4262
4263
0
  if(key && numpixels <= 16) {
4264
0
    alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
4265
0
    key = 0;
4266
0
    if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
4267
0
  }
4268
4269
0
  gray_ok = !stats->colored;
4270
0
  if(!stats->allow_greyscale) gray_ok = 0;
4271
0
  if(!gray_ok && bits < 8) bits = 8;
4272
4273
0
  n = stats->numcolors;
4274
0
  palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
4275
0
  palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/
4276
0
  if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
4277
0
  if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/
4278
0
  if(!stats->allow_palette) palette_ok = 0;
4279
4280
0
  if(palette_ok) {
4281
0
    const unsigned char* p = stats->palette;
4282
0
    lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
4283
0
    for(i = 0; i != stats->numcolors; ++i) {
4284
0
      error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
4285
0
      if(error) break;
4286
0
    }
4287
4288
0
    mode_out->colortype = LCT_PALETTE;
4289
0
    mode_out->bitdepth = palettebits;
4290
4291
0
    if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
4292
0
        && mode_in->bitdepth == mode_out->bitdepth) {
4293
      /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
4294
0
      lodepng_color_mode_cleanup(mode_out); /*clears palette, keeps the above set colortype and bitdepth fields as-is*/
4295
0
      lodepng_color_mode_copy(mode_out, mode_in);
4296
0
    }
4297
0
  } else /*8-bit or 16-bit per channel*/ {
4298
0
    mode_out->bitdepth = bits;
4299
0
    mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA)
4300
0
                                : (gray_ok ? LCT_GREY : LCT_RGB);
4301
0
    if(key) {
4302
0
      unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/
4303
0
      mode_out->key_r = stats->key_r & mask;
4304
0
      mode_out->key_g = stats->key_g & mask;
4305
0
      mode_out->key_b = stats->key_b & mask;
4306
0
      mode_out->key_defined = 1;
4307
0
    }
4308
0
  }
4309
4310
0
  return error;
4311
0
}
4312
4313
#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
4314
4315
/*Paeth predictor, used by PNG filter type 4*/
4316
9.27M
static unsigned char paethPredictor(unsigned char a, unsigned char b, unsigned char c) {
4317
  /* the subtractions of unsigned char cast it to a signed type.
4318
  With gcc, short is faster than int, with clang int is as fast (as of april 2023)*/
4319
9.27M
  short pa = (b - c) < 0 ? -(b - c) : (b - c);
4320
9.27M
  short pb = (a - c) < 0 ? -(a - c) : (a - c);
4321
  /* writing it out like this compiles to something faster than introducing a temp variable*/
4322
9.27M
  short pc = (a + b - c - c) < 0 ? -(a + b - c - c) : (a + b - c - c);
4323
  /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */
4324
9.27M
  if(pb < pa) { a = b; pa = pb; }
4325
9.27M
  return (pc < pa) ? c : a;
4326
9.27M
}
4327
4328
/*shared values used by multiple Adam7 related functions*/
4329
4330
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
4331
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
4332
static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
4333
static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
4334
4335
/*
4336
Outputs various dimensions and positions in the image related to the Adam7 reduced images.
4337
passw: output containing the width of the 7 passes
4338
passh: output containing the height of the 7 passes
4339
filter_passstart: output containing the index of the start and end of each
4340
 reduced image with filter bytes
4341
padded_passstart output containing the index of the start and end of each
4342
 reduced image when without filter bytes but with padded scanlines
4343
passstart: output containing the index of the start and end of each reduced
4344
 image without padding between scanlines, but still padding between the images
4345
w, h: width and height of non-interlaced image
4346
bpp: bits per pixel
4347
"padded" is only relevant if bpp is less than 8 and a scanline or image does not
4348
 end at a full byte
4349
*/
4350
static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
4351
3.25k
                                size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) {
4352
  /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
4353
3.25k
  unsigned i;
4354
4355
  /*calculate width and height in pixels of each pass*/
4356
26.0k
  for(i = 0; i != 7; ++i) {
4357
22.7k
    passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
4358
22.7k
    passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
4359
22.7k
    if(passw[i] == 0) passh[i] = 0;
4360
22.7k
    if(passh[i] == 0) passw[i] = 0;
4361
22.7k
  }
4362
4363
3.25k
  filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
4364
26.0k
  for(i = 0; i != 7; ++i) {
4365
    /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
4366
22.7k
    filter_passstart[i + 1] = filter_passstart[i]
4367
22.7k
                            + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);
4368
    /*bits padded if needed to fill full byte at end of each scanline*/
4369
22.7k
    padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);
4370
    /*only padded at end of reduced image*/
4371
22.7k
    passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;
4372
22.7k
  }
4373
3.25k
}
4374
4375
#ifdef LODEPNG_COMPILE_DECODER
4376
4377
/* ////////////////////////////////////////////////////////////////////////// */
4378
/* / PNG Decoder                                                            / */
4379
/* ////////////////////////////////////////////////////////////////////////// */
4380
4381
/*read the information from the header and store it in the LodePNGInfo. return value is error*/
4382
unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
4383
8.32k
                         const unsigned char* in, size_t insize) {
4384
8.32k
  unsigned width, height;
4385
8.32k
  LodePNGInfo* info = &state->info_png;
4386
8.32k
  if(insize == 0 || in == 0) {
4387
0
    CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
4388
0
  }
4389
8.32k
  if(insize < 33) {
4390
12
    CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
4391
0
  }
4392
4393
  /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
4394
  /* TODO: remove this. One should use a new LodePNGState for new sessions */
4395
8.31k
  lodepng_info_cleanup(info);
4396
8.31k
  lodepng_info_init(info);
4397
4398
8.31k
  if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
4399
8.26k
     || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
4400
92
    CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
4401
0
  }
4402
8.22k
  if(lodepng_chunk_length(in + 8) != 13) {
4403
47
    CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
4404
0
  }
4405
8.17k
  if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {
4406
54
    CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
4407
0
  }
4408
4409
  /*read the values given in the header*/
4410
8.12k
  width = lodepng_read32bitInt(&in[16]);
4411
8.12k
  height = lodepng_read32bitInt(&in[20]);
4412
  /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/
4413
8.12k
  if(w) *w = width;
4414
8.12k
  if(h) *h = height;
4415
8.12k
  info->color.bitdepth = in[24];
4416
8.12k
  info->color.colortype = (LodePNGColorType)in[25];
4417
8.12k
  info->compression_method = in[26];
4418
8.12k
  info->filter_method = in[27];
4419
8.12k
  info->interlace_method = in[28];
4420
4421
  /*errors returned only after the parsing so other values are still output*/
4422
4423
  /*error: invalid image size*/
4424
8.12k
  if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);
4425
  /*error: invalid colortype or bitdepth combination*/
4426
8.12k
  state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
4427
8.12k
  if(state->error) return state->error;
4428
  /*error: only compression method 0 is allowed in the specification*/
4429
8.04k
  if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
4430
  /*error: only filter method 0 is allowed in the specification*/
4431
8.03k
  if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
4432
  /*error: only interlace methods 0 and 1 exist in the specification*/
4433
8.02k
  if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
4434
4435
8.01k
  if(!state->decoder.ignore_crc) {
4436
0
    unsigned crc = lodepng_read32bitInt(&in[29]);
4437
0
    unsigned checksum = lodepng_crc32(&in[12], 17);
4438
0
    if(crc != checksum) {
4439
0
      CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
4440
0
    }
4441
0
  }
4442
4443
8.01k
  return state->error;
4444
8.01k
}
4445
4446
static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
4447
147k
                                 size_t bytewidth, unsigned char filterType, size_t length) {
4448
  /*
4449
  For PNG filter method 0
4450
  unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
4451
  the filter works byte per byte (bytewidth = 1)
4452
  precon is the previous unfiltered scanline, recon the result, scanline the current one
4453
  the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
4454
  recon and scanline MAY be the same memory address! precon must be disjoint.
4455
  */
4456
4457
147k
  size_t i;
4458
147k
  switch(filterType) {
4459
84.6k
    case 0:
4460
33.0M
      for(i = 0; i != length; ++i) recon[i] = scanline[i];
4461
84.6k
      break;
4462
4.29k
    case 1: {
4463
4.29k
      size_t j = 0;
4464
17.1k
      for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
4465
40.2M
      for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + recon[j];
4466
4.29k
      break;
4467
0
    }
4468
9.92k
    case 2:
4469
9.92k
      if(precon) {
4470
16.1M
        for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
4471
8.76k
      } else {
4472
12.0k
        for(i = 0; i != length; ++i) recon[i] = scanline[i];
4473
1.16k
      }
4474
9.92k
      break;
4475
16.1k
    case 3:
4476
16.1k
      if(precon) {
4477
13.7k
        size_t j = 0;
4478
61.9k
        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);
4479
        /* Unroll independent paths of this predictor. A 6x and 8x version is also possible but that adds
4480
        too much code. Whether this speeds up anything depends on compiler and settings. */
4481
13.7k
        if(bytewidth >= 4) {
4482
47.3k
          for(; i + 3 < length; i += 4, j += 4) {
4483
41.0k
            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];
4484
41.0k
            unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];
4485
41.0k
            unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];
4486
41.0k
            recon[i + 0] = s0 + ((r0 + p0) >> 1u);
4487
41.0k
            recon[i + 1] = s1 + ((r1 + p1) >> 1u);
4488
41.0k
            recon[i + 2] = s2 + ((r2 + p2) >> 1u);
4489
41.0k
            recon[i + 3] = s3 + ((r3 + p3) >> 1u);
4490
41.0k
          }
4491
7.40k
        } else if(bytewidth >= 3) {
4492
218k
          for(; i + 2 < length; i += 3, j += 3) {
4493
217k
            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];
4494
217k
            unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];
4495
217k
            unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];
4496
217k
            recon[i + 0] = s0 + ((r0 + p0) >> 1u);
4497
217k
            recon[i + 1] = s1 + ((r1 + p1) >> 1u);
4498
217k
            recon[i + 2] = s2 + ((r2 + p2) >> 1u);
4499
217k
          }
4500
6.14k
        } else if(bytewidth >= 2) {
4501
2.63k
          for(; i + 1 < length; i += 2, j += 2) {
4502
1.55k
            unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];
4503
1.55k
            unsigned char r0 = recon[j + 0], r1 = recon[j + 1];
4504
1.55k
            unsigned char p0 = precon[i + 0], p1 = precon[i + 1];
4505
1.55k
            recon[i + 0] = s0 + ((r0 + p0) >> 1u);
4506
1.55k
            recon[i + 1] = s1 + ((r1 + p1) >> 1u);
4507
1.55k
          }
4508
1.08k
        }
4509
63.3k
        for(; i != length; ++i, ++j) recon[i] = scanline[i] + ((recon[j] + precon[i]) >> 1u);
4510
13.7k
      } else {
4511
2.48k
        size_t j = 0;
4512
10.7k
        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
4513
75.3k
        for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + (recon[j] >> 1u);
4514
2.48k
      }
4515
16.1k
      break;
4516
32.5k
    case 4:
4517
32.5k
      if(precon) {
4518
        /* Unroll independent paths of this predictor. Whether this speeds up
4519
        anything depends on compiler and settings. */
4520
29.4k
        if(bytewidth == 8) {
4521
2.89k
          unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;
4522
2.89k
          unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;
4523
2.89k
          unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0;
4524
2.89k
          unsigned char a6, b6 = 0, c6, d6 = 0, a7, b7 = 0, c7, d7 = 0;
4525
12.9k
          for(i = 0; i + 7 < length; i += 8) {
4526
10.0k
            c0 = b0; c1 = b1; c2 = b2; c3 = b3;
4527
10.0k
            c4 = b4; c5 = b5; c6 = b6; c7 = b7;
4528
10.0k
            b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3];
4529
10.0k
            b4 = precon[i + 4]; b5 = precon[i + 5]; b6 = precon[i + 6]; b7 = precon[i + 7];
4530
10.0k
            a0 = d0; a1 = d1; a2 = d2; a3 = d3;
4531
10.0k
            a4 = d4; a5 = d5; a6 = d6; a7 = d7;
4532
10.0k
            d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);
4533
10.0k
            d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);
4534
10.0k
            d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);
4535
10.0k
            d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);
4536
10.0k
            d4 = scanline[i + 4] + paethPredictor(a4, b4, c4);
4537
10.0k
            d5 = scanline[i + 5] + paethPredictor(a5, b5, c5);
4538
10.0k
            d6 = scanline[i + 6] + paethPredictor(a6, b6, c6);
4539
10.0k
            d7 = scanline[i + 7] + paethPredictor(a7, b7, c7);
4540
10.0k
            recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3;
4541
10.0k
            recon[i + 4] = d4; recon[i + 5] = d5; recon[i + 6] = d6; recon[i + 7] = d7;
4542
10.0k
          }
4543
26.5k
        } else if(bytewidth == 6) {
4544
9.40k
          unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;
4545
9.40k
          unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;
4546
9.40k
          unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0;
4547
28.3k
          for(i = 0; i + 5 < length; i += 6) {
4548
18.9k
            c0 = b0; c1 = b1; c2 = b2;
4549
18.9k
            c3 = b3; c4 = b4; c5 = b5;
4550
18.9k
            b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2];
4551
18.9k
            b3 = precon[i + 3]; b4 = precon[i + 4]; b5 = precon[i + 5];
4552
18.9k
            a0 = d0; a1 = d1; a2 = d2;
4553
18.9k
            a3 = d3; a4 = d4; a5 = d5;
4554
18.9k
            d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);
4555
18.9k
            d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);
4556
18.9k
            d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);
4557
18.9k
            d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);
4558
18.9k
            d4 = scanline[i + 4] + paethPredictor(a4, b4, c4);
4559
18.9k
            d5 = scanline[i + 5] + paethPredictor(a5, b5, c5);
4560
18.9k
            recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2;
4561
18.9k
            recon[i + 3] = d3; recon[i + 4] = d4; recon[i + 5] = d5;
4562
18.9k
          }
4563
17.1k
        } else if(bytewidth == 4) {
4564
4.03k
          unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0;
4565
4.03k
          unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0;
4566
186k
          for(i = 0; i + 3 < length; i += 4) {
4567
182k
            c0 = b0; c1 = b1; c2 = b2; c3 = b3;
4568
182k
            b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3];
4569
182k
            a0 = d0; a1 = d1; a2 = d2; a3 = d3;
4570
182k
            d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);
4571
182k
            d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);
4572
182k
            d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);
4573
182k
            d3 = scanline[i + 3] + paethPredictor(a3, b3, c3);
4574
182k
            recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3;
4575
182k
          }
4576
13.1k
        } else if(bytewidth == 3) {
4577
2.87k
          unsigned char a0, b0 = 0, c0, d0 = 0;
4578
2.87k
          unsigned char a1, b1 = 0, c1, d1 = 0;
4579
2.87k
          unsigned char a2, b2 = 0, c2, d2 = 0;
4580
2.77M
          for(i = 0; i + 2 < length; i += 3) {
4581
2.76M
            c0 = b0; c1 = b1; c2 = b2;
4582
2.76M
            b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2];
4583
2.76M
            a0 = d0; a1 = d1; a2 = d2;
4584
2.76M
            d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);
4585
2.76M
            d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);
4586
2.76M
            d2 = scanline[i + 2] + paethPredictor(a2, b2, c2);
4587
2.76M
            recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2;
4588
2.76M
          }
4589
10.2k
        } else if(bytewidth == 2) {
4590
4.16k
          unsigned char a0, b0 = 0, c0, d0 = 0;
4591
4.16k
          unsigned char a1, b1 = 0, c1, d1 = 0;
4592
17.6k
          for(i = 0; i + 1 < length; i += 2) {
4593
13.4k
            c0 = b0; c1 = b1;
4594
13.4k
            b0 = precon[i + 0];
4595
13.4k
            b1 = precon[i + 1];
4596
13.4k
            a0 = d0; a1 = d1;
4597
13.4k
            d0 = scanline[i + 0] + paethPredictor(a0, b0, c0);
4598
13.4k
            d1 = scanline[i + 1] + paethPredictor(a1, b1, c1);
4599
13.4k
            recon[i + 0] = d0;
4600
13.4k
            recon[i + 1] = d1;
4601
13.4k
          }
4602
6.05k
        } else if(bytewidth == 1) {
4603
6.05k
          unsigned char a, b = 0, c, d = 0;
4604
29.0k
          for(i = 0; i != length; ++i) {
4605
22.9k
            c = b;
4606
22.9k
            b = precon[i];
4607
22.9k
            a = d;
4608
22.9k
            d = scanline[i] + paethPredictor(a, b, c);
4609
22.9k
            recon[i] = d;
4610
22.9k
          }
4611
6.05k
        } else {
4612
          /* Normally not a possible case, but this would handle it correctly */
4613
0
          for(i = 0; i != bytewidth; ++i) {
4614
0
            recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
4615
0
          }
4616
0
        }
4617
        /* finish any remaining bytes */
4618
29.4k
        for(; i != length; ++i) {
4619
0
          recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
4620
0
        }
4621
29.4k
      } else {
4622
3.10k
        size_t j = 0;
4623
13.9k
        for(i = 0; i != bytewidth; ++i) {
4624
10.8k
          recon[i] = scanline[i];
4625
10.8k
        }
4626
48.6k
        for(i = bytewidth; i != length; ++i, ++j) {
4627
          /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
4628
45.5k
          recon[i] = (scanline[i] + recon[j]);
4629
45.5k
        }
4630
3.10k
      }
4631
32.5k
      break;
4632
222
    default: return 36; /*error: invalid filter type given*/
4633
147k
  }
4634
147k
  return 0;
4635
147k
}
4636
4637
15.1k
static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
4638
  /*
4639
  For PNG filter method 0
4640
  this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
4641
  out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
4642
  w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
4643
  in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
4644
  */
4645
4646
15.1k
  unsigned y;
4647
15.1k
  unsigned char* prevline = 0;
4648
4649
  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
4650
15.1k
  size_t bytewidth = (bpp + 7u) / 8u;
4651
  /*the width of a scanline in bytes, not including the filter type*/
4652
15.1k
  size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;
4653
4654
162k
  for(y = 0; y < h; ++y) {
4655
147k
    size_t outindex = linebytes * y;
4656
147k
    size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
4657
147k
    unsigned char filterType = in[inindex];
4658
4659
147k
    CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
4660
4661
147k
    prevline = &out[outindex];
4662
147k
  }
4663
4664
14.9k
  return 0;
4665
15.1k
}
4666
4667
/*
4668
in: Adam7 interlaced image, with no padding bits between scanlines, but between
4669
 reduced images so that each reduced image starts at a byte.
4670
out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
4671
bpp: bits per pixel
4672
out has the following size in bits: w * h * bpp.
4673
in is possibly bigger due to padding bits between reduced images.
4674
out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4675
(because that's likely a little bit faster)
4676
NOTE: comments about padding bits are only relevant if bpp < 8
4677
*/
4678
1.59k
static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
4679
1.59k
  unsigned passw[7], passh[7];
4680
1.59k
  size_t filter_passstart[8], padded_passstart[8], passstart[8];
4681
1.59k
  unsigned i;
4682
4683
1.59k
  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4684
4685
1.59k
  if(bpp >= 8) {
4686
10.7k
    for(i = 0; i != 7; ++i) {
4687
9.42k
      unsigned x, y, b;
4688
9.42k
      size_t bytewidth = bpp / 8u;
4689
77.9k
      for(y = 0; y < passh[i]; ++y)
4690
992k
      for(x = 0; x < passw[i]; ++x) {
4691
923k
        size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4692
923k
        size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w
4693
923k
                             + ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth;
4694
2.51M
        for(b = 0; b < bytewidth; ++b) {
4695
1.59M
          out[pixeloutstart + b] = in[pixelinstart + b];
4696
1.59M
        }
4697
923k
      }
4698
9.42k
    }
4699
1.34k
  } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
4700
2.01k
    for(i = 0; i != 7; ++i) {
4701
1.76k
      unsigned x, y, b;
4702
1.76k
      unsigned ilinebits = bpp * passw[i];
4703
1.76k
      unsigned olinebits = bpp * w;
4704
1.76k
      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4705
31.4k
      for(y = 0; y < passh[i]; ++y)
4706
212M
      for(x = 0; x < passw[i]; ++x) {
4707
212M
        ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4708
212M
        obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp;
4709
424M
        for(b = 0; b < bpp; ++b) {
4710
212M
          unsigned char bit = readBitFromReversedStream(&ibp, in);
4711
212M
          setBitOfReversedStream(&obp, out, bit);
4712
212M
        }
4713
212M
      }
4714
1.76k
    }
4715
252
  }
4716
1.59k
}
4717
4718
static void removePaddingBits(unsigned char* out, const unsigned char* in,
4719
2.49k
                              size_t olinebits, size_t ilinebits, unsigned h) {
4720
  /*
4721
  After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4722
  to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4723
  for the Adam7 code, the color convert code and the output to the user.
4724
  in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4725
  have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4726
  also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4727
  only useful if (ilinebits - olinebits) is a value in the range 1..7
4728
  */
4729
2.49k
  unsigned y;
4730
2.49k
  size_t diff = ilinebits - olinebits;
4731
2.49k
  size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4732
39.8k
  for(y = 0; y < h; ++y) {
4733
37.3k
    size_t x;
4734
216M
    for(x = 0; x < olinebits; ++x) {
4735
216M
      unsigned char bit = readBitFromReversedStream(&ibp, in);
4736
216M
      setBitOfReversedStream(&obp, out, bit);
4737
216M
    }
4738
37.3k
    ibp += diff;
4739
37.3k
  }
4740
2.49k
}
4741
4742
/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4743
the IDAT chunks (with filter index bytes and possible padding bits)
4744
return value is error*/
4745
static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4746
5.39k
                                     unsigned w, unsigned h, const LodePNGInfo* info_png) {
4747
  /*
4748
  This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4749
  Steps:
4750
  *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)
4751
  *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4752
  NOTE: the in buffer will be overwritten with intermediate data!
4753
  */
4754
5.39k
  unsigned bpp = lodepng_get_bpp(&info_png->color);
4755
5.39k
  if(bpp == 0) return 31; /*error: invalid colortype*/
4756
4757
5.39k
  if(info_png->interlace_method == 0) {
4758
3.73k
    if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
4759
674
      CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4760
663
      removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);
4761
663
    }
4762
    /*we can immediately filter into the out buffer, no other steps needed*/
4763
3.57k
    else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4764
3.57k
  } else /*interlace_method is 1 (Adam7)*/ {
4765
1.65k
    unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4766
1.65k
    unsigned i;
4767
4768
1.65k
    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4769
4770
13.0k
    for(i = 0; i != 7; ++i) {
4771
11.4k
      CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4772
      /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
4773
      move bytes instead of bits or move not at all*/
4774
11.3k
      if(bpp < 8) {
4775
        /*remove padding bits in scanlines; after this there still may be padding
4776
        bits between the different reduced images: each reduced image still starts nicely at a byte*/
4777
1.83k
        removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4778
1.83k
                          ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);
4779
1.83k
      }
4780
11.3k
    }
4781
4782
1.59k
    Adam7_deinterlace(out, in, w, h, bpp);
4783
1.59k
  }
4784
4785
5.16k
  return 0;
4786
5.39k
}
4787
4788
2.88k
static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
4789
2.88k
  unsigned pos = 0, i;
4790
2.88k
  color->palettesize = chunkLength / 3u;
4791
2.88k
  if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/
4792
2.87k
  lodepng_color_mode_alloc_palette(color);
4793
2.87k
  if(!color->palette && color->palettesize) {
4794
0
    color->palettesize = 0;
4795
0
    return 83; /*alloc fail*/
4796
0
  }
4797
4798
18.7k
  for(i = 0; i != color->palettesize; ++i) {
4799
15.8k
    color->palette[4 * i + 0] = data[pos++]; /*R*/
4800
15.8k
    color->palette[4 * i + 1] = data[pos++]; /*G*/
4801
15.8k
    color->palette[4 * i + 2] = data[pos++]; /*B*/
4802
15.8k
    color->palette[4 * i + 3] = 255; /*alpha*/
4803
15.8k
  }
4804
4805
2.87k
  return 0; /* OK */
4806
2.87k
}
4807
4808
2.56k
static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
4809
2.56k
  unsigned i;
4810
2.56k
  if(color->colortype == LCT_PALETTE) {
4811
    /*error: more alpha values given than there are palette entries*/
4812
603
    if(chunkLength > color->palettesize) return 39;
4813
4814
1.07k
    for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
4815
1.96k
  } else if(color->colortype == LCT_GREY) {
4816
    /*error: this chunk must be 2 bytes for grayscale image*/
4817
583
    if(chunkLength != 2) return 30;
4818
4819
573
    color->key_defined = 1;
4820
573
    color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
4821
1.38k
  } else if(color->colortype == LCT_RGB) {
4822
    /*error: this chunk must be 6 bytes for RGB image*/
4823
1.38k
    if(chunkLength != 6) return 41;
4824
4825
1.36k
    color->key_defined = 1;
4826
1.36k
    color->key_r = 256u * data[0] + data[1];
4827
1.36k
    color->key_g = 256u * data[2] + data[3];
4828
1.36k
    color->key_b = 256u * data[4] + data[5];
4829
1.36k
  }
4830
2
  else return 42; /*error: tRNS chunk not allowed for other color models*/
4831
4832
2.50k
  return 0; /* OK */
4833
2.56k
}
4834
4835
4836
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4837
/*background color chunk (bKGD)*/
4838
1.05k
static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
4839
1.05k
  if(info->color.colortype == LCT_PALETTE) {
4840
    /*error: this chunk must be 1 byte for indexed color image*/
4841
226
    if(chunkLength != 1) return 43;
4842
4843
    /*error: invalid palette index, or maybe this chunk appeared before PLTE*/
4844
219
    if(data[0] >= info->color.palettesize) return 103;
4845
4846
210
    info->background_defined = 1;
4847
210
    info->background_r = info->background_g = info->background_b = data[0];
4848
827
  } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
4849
    /*error: this chunk must be 2 bytes for grayscale image*/
4850
411
    if(chunkLength != 2) return 44;
4851
4852
    /*the values are truncated to bitdepth in the PNG file*/
4853
403
    info->background_defined = 1;
4854
403
    info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
4855
416
  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
4856
    /*error: this chunk must be 6 bytes for grayscale image*/
4857
416
    if(chunkLength != 6) return 45;
4858
4859
    /*the values are truncated to bitdepth in the PNG file*/
4860
407
    info->background_defined = 1;
4861
407
    info->background_r = 256u * data[0] + data[1];
4862
407
    info->background_g = 256u * data[2] + data[3];
4863
407
    info->background_b = 256u * data[4] + data[5];
4864
407
  }
4865
4866
1.02k
  return 0; /* OK */
4867
1.05k
}
4868
4869
/*text chunk (tEXt)*/
4870
95.5k
static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
4871
95.5k
  unsigned error = 0;
4872
95.5k
  char *key = 0, *str = 0;
4873
4874
95.5k
  while(!error) /*not really a while loop, only used to break on error*/ {
4875
95.5k
    unsigned length, string2_begin;
4876
4877
95.5k
    length = 0;
4878
1.11M
    while(length < chunkLength && data[length] != 0) ++length;
4879
    /*even though it's not allowed by the standard, no error is thrown if
4880
    there's no null termination char, if the text is empty*/
4881
95.5k
    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4882
4883
95.5k
    key = (char*)lodepng_malloc(length + 1);
4884
95.5k
    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4885
4886
95.5k
    lodepng_memcpy(key, data, length);
4887
95.5k
    key[length] = 0;
4888
4889
95.5k
    string2_begin = length + 1; /*skip keyword null terminator*/
4890
4891
95.5k
    length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);
4892
95.5k
    str = (char*)lodepng_malloc(length + 1);
4893
95.5k
    if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
4894
4895
95.5k
    lodepng_memcpy(str, data + string2_begin, length);
4896
95.5k
    str[length] = 0;
4897
4898
95.5k
    error = lodepng_add_text(info, key, str);
4899
4900
95.5k
    break;
4901
95.5k
  }
4902
4903
95.5k
  lodepng_free(key);
4904
95.5k
  lodepng_free(str);
4905
4906
95.5k
  return error;
4907
95.5k
}
4908
4909
/*compressed text chunk (zTXt)*/
4910
static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,
4911
1.00k
                               const unsigned char* data, size_t chunkLength) {
4912
1.00k
  unsigned error = 0;
4913
4914
  /*copy the object to change parameters in it*/
4915
1.00k
  LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
4916
4917
1.00k
  unsigned length, string2_begin;
4918
1.00k
  char *key = 0;
4919
1.00k
  unsigned char* str = 0;
4920
1.00k
  size_t size = 0;
4921
4922
1.00k
  while(!error) /*not really a while loop, only used to break on error*/ {
4923
2.23M
    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4924
1.00k
    if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4925
987
    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4926
4927
958
    key = (char*)lodepng_malloc(length + 1);
4928
958
    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4929
4930
958
    lodepng_memcpy(key, data, length);
4931
958
    key[length] = 0;
4932
4933
958
    if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4934
4935
954
    string2_begin = length + 2;
4936
954
    if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
4937
4938
954
    length = (unsigned)chunkLength - string2_begin;
4939
954
    zlibsettings.max_output_size = decoder->max_text_size;
4940
    /*will fail if zlib error, e.g. if length is too small*/
4941
954
    error = zlib_decompress(&str, &size, 0, &data[string2_begin],
4942
954
                            length, &zlibsettings);
4943
    /*error: compressed text larger than  decoder->max_text_size*/
4944
954
    if(error && size > zlibsettings.max_output_size) error = 112;
4945
954
    if(error) break;
4946
834
    error = lodepng_add_text_sized(info, key, (char*)str, size);
4947
834
    break;
4948
954
  }
4949
4950
1.00k
  lodepng_free(key);
4951
1.00k
  lodepng_free(str);
4952
4953
1.00k
  return error;
4954
1.00k
}
4955
4956
/*international text chunk (iTXt)*/
4957
static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,
4958
95.2k
                               const unsigned char* data, size_t chunkLength) {
4959
95.2k
  unsigned error = 0;
4960
95.2k
  unsigned i;
4961
4962
  /*copy the object to change parameters in it*/
4963
95.2k
  LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
4964
4965
95.2k
  unsigned length, begin, compressed;
4966
95.2k
  char *key = 0, *langtag = 0, *transkey = 0;
4967
4968
95.2k
  while(!error) /*not really a while loop, only used to break on error*/ {
4969
    /*Quick check if the chunk length isn't too small. Even without check
4970
    it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4971
95.2k
    if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
4972
4973
    /*read the key*/
4974
5.30M
    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
4975
95.2k
    if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
4976
95.2k
    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
4977
4978
95.1k
    key = (char*)lodepng_malloc(length + 1);
4979
95.1k
    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
4980
4981
95.1k
    lodepng_memcpy(key, data, length);
4982
95.1k
    key[length] = 0;
4983
4984
    /*read the compression method*/
4985
95.1k
    compressed = data[length + 1];
4986
95.1k
    if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
4987
4988
    /*even though it's not allowed by the standard, no error is thrown if
4989
    there's no null termination char, if the text is empty for the next 3 texts*/
4990
4991
    /*read the langtag*/
4992
95.1k
    begin = length + 3;
4993
95.1k
    length = 0;
4994
3.73M
    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
4995
4996
95.1k
    langtag = (char*)lodepng_malloc(length + 1);
4997
95.1k
    if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
4998
4999
95.1k
    lodepng_memcpy(langtag, data + begin, length);
5000
95.1k
    langtag[length] = 0;
5001
5002
    /*read the transkey*/
5003
95.1k
    begin += length + 1;
5004
95.1k
    length = 0;
5005
2.94M
    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
5006
5007
95.1k
    transkey = (char*)lodepng_malloc(length + 1);
5008
95.1k
    if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
5009
5010
95.1k
    lodepng_memcpy(transkey, data + begin, length);
5011
95.1k
    transkey[length] = 0;
5012
5013
    /*read the actual text*/
5014
95.1k
    begin += length + 1;
5015
5016
95.1k
    length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;
5017
5018
95.1k
    if(compressed) {
5019
508
      unsigned char* str = 0;
5020
508
      size_t size = 0;
5021
508
      zlibsettings.max_output_size = decoder->max_text_size;
5022
      /*will fail if zlib error, e.g. if length is too small*/
5023
508
      error = zlib_decompress(&str, &size, 0, &data[begin],
5024
508
                              length, &zlibsettings);
5025
      /*error: compressed text larger than  decoder->max_text_size*/
5026
508
      if(error && size > zlibsettings.max_output_size) error = 112;
5027
508
      if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)str, size);
5028
508
      lodepng_free(str);
5029
94.6k
    } else {
5030
94.6k
      error = lodepng_add_itext_sized(info, key, langtag, transkey, (const char*)(data + begin), length);
5031
94.6k
    }
5032
5033
95.1k
    break;
5034
95.1k
  }
5035
5036
95.2k
  lodepng_free(key);
5037
95.2k
  lodepng_free(langtag);
5038
95.2k
  lodepng_free(transkey);
5039
5040
95.2k
  return error;
5041
95.2k
}
5042
5043
239
static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5044
239
  if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
5045
5046
221
  info->time_defined = 1;
5047
221
  info->time.year = 256u * data[0] + data[1];
5048
221
  info->time.month = data[2];
5049
221
  info->time.day = data[3];
5050
221
  info->time.hour = data[4];
5051
221
  info->time.minute = data[5];
5052
221
  info->time.second = data[6];
5053
5054
221
  return 0; /* OK */
5055
239
}
5056
5057
296
static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5058
296
  if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
5059
5060
281
  info->phys_defined = 1;
5061
281
  info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
5062
281
  info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
5063
281
  info->phys_unit = data[8];
5064
5065
281
  return 0; /* OK */
5066
296
}
5067
5068
286
static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5069
286
  if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/
5070
5071
277
  info->gama_defined = 1;
5072
277
  info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
5073
5074
277
  return 0; /* OK */
5075
286
}
5076
5077
214
static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5078
214
  if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/
5079
5080
204
  info->chrm_defined = 1;
5081
204
  info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];
5082
204
  info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];
5083
204
  info->chrm_red_x   = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];
5084
204
  info->chrm_red_y   = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];
5085
204
  info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
5086
204
  info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
5087
204
  info->chrm_blue_x  = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];
5088
204
  info->chrm_blue_y  = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];
5089
5090
204
  return 0; /* OK */
5091
214
}
5092
5093
333
static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5094
333
  if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/
5095
5096
325
  info->srgb_defined = 1;
5097
325
  info->srgb_intent = data[0];
5098
5099
325
  return 0; /* OK */
5100
333
}
5101
5102
static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecoderSettings* decoder,
5103
1.27k
                               const unsigned char* data, size_t chunkLength) {
5104
1.27k
  unsigned error = 0;
5105
1.27k
  unsigned i;
5106
1.27k
  size_t size = 0;
5107
  /*copy the object to change parameters in it*/
5108
1.27k
  LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
5109
5110
1.27k
  unsigned length, string2_begin;
5111
5112
1.27k
  if(info->iccp_defined) lodepng_clear_icc(info);
5113
5114
1.44M
  for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
5115
1.27k
  if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/
5116
1.25k
  if(length < 1 || length > 79) return 89; /*keyword too short or long*/
5117
5118
1.21k
  info->iccp_name = (char*)lodepng_malloc(length + 1);
5119
1.21k
  if(!info->iccp_name) return 83; /*alloc fail*/
5120
5121
1.21k
  info->iccp_name[length] = 0;
5122
3.67k
  for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];
5123
5124
1.21k
  if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/
5125
5126
1.19k
  string2_begin = length + 2;
5127
1.19k
  if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/
5128
5129
1.19k
  length = (unsigned)chunkLength - string2_begin;
5130
1.19k
  zlibsettings.max_output_size = decoder->max_icc_size;
5131
1.19k
  error = zlib_decompress(&info->iccp_profile, &size, 0,
5132
1.19k
                          &data[string2_begin],
5133
1.19k
                          length, &zlibsettings);
5134
  /*error: ICC profile larger than decoder->max_icc_size*/
5135
1.19k
  if(error && size > zlibsettings.max_output_size) error = 113;
5136
1.19k
  info->iccp_profile_size = (unsigned)size;
5137
1.19k
  if(!error && !info->iccp_profile_size) error = 123; /*invalid ICC profile size*/
5138
5139
1.19k
  if(!error) info->iccp_defined = 1;
5140
1.19k
  return error;
5141
1.19k
}
5142
5143
205
static unsigned readChunk_cICP(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5144
205
  if(chunkLength != 4) return 117; /*invalid cICP chunk size*/
5145
5146
201
  info->cicp_defined = 1;
5147
  /* No error checking for value ranges is done here, that is up to a CICP
5148
  handling library, not the PNG decoding. Just pass on the metadata. */
5149
201
  info->cicp_color_primaries = data[0];
5150
201
  info->cicp_transfer_function = data[1];
5151
201
  info->cicp_matrix_coefficients = data[2];
5152
201
  info->cicp_video_full_range_flag = data[3];
5153
5154
201
  return 0; /* OK */
5155
205
}
5156
5157
222
static unsigned readChunk_mDCV(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5158
222
  if(chunkLength != 24) return 119; /*invalid mDCV chunk size*/
5159
5160
204
  info->mdcv_defined = 1;
5161
204
  info->mdcv_red_x = 256u * data[0] + data[1];
5162
204
  info->mdcv_red_y = 256u * data[2] + data[3];
5163
204
  info->mdcv_green_x = 256u * data[4] + data[5];
5164
204
  info->mdcv_green_y = 256u * data[6] + data[7];
5165
204
  info->mdcv_blue_x = 256u * data[8] + data[9];
5166
204
  info->mdcv_blue_y = 256u * data[10] + data[11];
5167
204
  info->mdcv_white_x = 256u * data[12] + data[13];
5168
204
  info->mdcv_white_y = 256u * data[14] + data[15];
5169
204
  info->mdcv_max_luminance = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
5170
204
  info->mdcv_min_luminance = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
5171
5172
204
  return 0; /* OK */
5173
222
}
5174
5175
213
static unsigned readChunk_cLLI(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5176
213
  if(chunkLength != 8) return 120; /*invalid cLLI chunk size*/
5177
5178
202
  info->clli_defined = 1;
5179
202
  info->clli_max_cll = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
5180
202
  info->clli_max_fall = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
5181
5182
202
  return 0; /* OK */
5183
213
}
5184
5185
944
static unsigned readChunk_eXIf(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5186
944
  return lodepng_set_exif(info, data, (unsigned)chunkLength);
5187
944
}
5188
5189
/*significant bits chunk (sBIT)*/
5190
1.13k
static unsigned readChunk_sBIT(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
5191
1.13k
  unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth;
5192
1.13k
  if(info->color.colortype == LCT_GREY) {
5193
    /*error: this chunk must be 1 bytes for grayscale image*/
5194
227
    if(chunkLength != 1) return 114;
5195
211
    if(data[0] == 0 || data[0] > bitdepth) return 115;
5196
204
    info->sbit_defined = 1;
5197
204
    info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/
5198
911
  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) {
5199
    /*error: this chunk must be 3 bytes for RGB and palette image*/
5200
432
    if(chunkLength != 3) return 114;
5201
425
    if(data[0] == 0 || data[1] == 0 || data[2] == 0) return 115;
5202
422
    if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth) return 115;
5203
401
    info->sbit_defined = 1;
5204
401
    info->sbit_r = data[0];
5205
401
    info->sbit_g = data[1];
5206
401
    info->sbit_b = data[2];
5207
479
  } else if(info->color.colortype == LCT_GREY_ALPHA) {
5208
    /*error: this chunk must be 2 byte for grayscale with alpha image*/
5209
226
    if(chunkLength != 2) return 114;
5210
220
    if(data[0] == 0 || data[1] == 0) return 115;
5211
217
    if(data[0] > bitdepth || data[1] > bitdepth) return 115;
5212
205
    info->sbit_defined = 1;
5213
205
    info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/
5214
205
    info->sbit_a = data[1];
5215
253
  } else if(info->color.colortype == LCT_RGBA) {
5216
    /*error: this chunk must be 4 bytes for grayscale image*/
5217
253
    if(chunkLength != 4) return 114;
5218
249
    if(data[0] == 0 || data[1] == 0 || data[2] == 0 || data[3] == 0) return 115;
5219
241
    if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth || data[3] > bitdepth) return 115;
5220
216
    info->sbit_defined = 1;
5221
216
    info->sbit_r = data[0];
5222
216
    info->sbit_g = data[1];
5223
216
    info->sbit_b = data[2];
5224
216
    info->sbit_a = data[3];
5225
216
  }
5226
5227
1.02k
  return 0; /* OK */
5228
1.13k
}
5229
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5230
5231
unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
5232
0
                               const unsigned char* in, size_t insize) {
5233
0
  const unsigned char* chunk = in + pos;
5234
0
  unsigned chunkLength;
5235
0
  const unsigned char* data;
5236
0
  unsigned unhandled = 0;
5237
0
  unsigned error = 0;
5238
5239
0
  if(pos + 4 > insize) return 30;
5240
0
  chunkLength = lodepng_chunk_length(chunk);
5241
0
  if(chunkLength > 2147483647) return 63;
5242
0
  data = lodepng_chunk_data_const(chunk);
5243
0
  if(chunkLength + 12 > insize - pos) return 30;
5244
5245
0
  if(lodepng_chunk_type_equals(chunk, "PLTE")) {
5246
0
    error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
5247
0
  } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
5248
0
    error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
5249
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5250
0
  } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
5251
0
    error = readChunk_bKGD(&state->info_png, data, chunkLength);
5252
0
  } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
5253
0
    error = readChunk_tEXt(&state->info_png, data, chunkLength);
5254
0
  } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
5255
0
    error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);
5256
0
  } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
5257
0
    error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);
5258
0
  } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
5259
0
    error = readChunk_tIME(&state->info_png, data, chunkLength);
5260
0
  } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
5261
0
    error = readChunk_pHYs(&state->info_png, data, chunkLength);
5262
0
  } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
5263
0
    error = readChunk_gAMA(&state->info_png, data, chunkLength);
5264
0
  } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
5265
0
    error = readChunk_cHRM(&state->info_png, data, chunkLength);
5266
0
  } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
5267
0
    error = readChunk_sRGB(&state->info_png, data, chunkLength);
5268
0
  } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
5269
0
    error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);
5270
0
  } else if(lodepng_chunk_type_equals(chunk, "cICP")) {
5271
0
    error = readChunk_cICP(&state->info_png, data, chunkLength);
5272
0
  } else if(lodepng_chunk_type_equals(chunk, "mDCV")) {
5273
0
    error = readChunk_mDCV(&state->info_png, data, chunkLength);
5274
0
  } else if(lodepng_chunk_type_equals(chunk, "cLLI")) {
5275
0
    error = readChunk_cLLI(&state->info_png, data, chunkLength);
5276
0
  } else if(lodepng_chunk_type_equals(chunk, "eXIf")) {
5277
0
    error = readChunk_eXIf(&state->info_png, data, chunkLength);
5278
0
  } else if(lodepng_chunk_type_equals(chunk, "sBIT")) {
5279
0
    error = readChunk_sBIT(&state->info_png, data, chunkLength);
5280
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5281
0
  } else {
5282
    /* unhandled chunk is ok (is not an error) */
5283
0
    unhandled = 1;
5284
0
  }
5285
5286
0
  if(!error && !unhandled && !state->decoder.ignore_crc) {
5287
0
    if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/
5288
0
  }
5289
5290
0
  return error;
5291
0
}
5292
5293
/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
5294
static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
5295
                          LodePNGState* state,
5296
8.32k
                          const unsigned char* in, size_t insize) {
5297
8.32k
  unsigned char IEND = 0;
5298
8.32k
  const unsigned char* chunk; /*points to beginning of next chunk*/
5299
8.32k
  unsigned char* idat; /*the data from idat chunks, zlib compressed*/
5300
8.32k
  size_t idatsize = 0;
5301
8.32k
  unsigned char* scanlines = 0;
5302
8.32k
  size_t scanlines_size = 0, expected_size = 0;
5303
8.32k
  size_t outsize = 0;
5304
5305
  /*for unknown chunk order*/
5306
8.32k
  unsigned unknown = 0;
5307
8.32k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5308
8.32k
  unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
5309
8.32k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5310
5311
5312
  /* safe output values in case error happens */
5313
8.32k
  *out = 0;
5314
8.32k
  *w = *h = 0;
5315
5316
8.32k
  state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
5317
8.32k
  if(state->error) return;
5318
5319
8.01k
  if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
5320
66
    CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
5321
0
  }
5322
5323
  /*the input filesize is a safe upper bound for the sum of idat chunks size*/
5324
7.95k
  idat = (unsigned char*)lodepng_malloc(insize);
5325
7.95k
  if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/
5326
5327
7.95k
  chunk = &in[33]; /*first byte of the first chunk after the header*/
5328
5329
  /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
5330
  IDAT data is put at the start of the in buffer*/
5331
225k
  while(!IEND && !state->error) {
5332
224k
    unsigned chunkLength;
5333
224k
    const unsigned char* data; /*the data in the chunk*/
5334
224k
    size_t pos = (size_t)(chunk - in);
5335
5336
    /*error: next chunk out of bounds of the in buffer*/
5337
224k
    if(chunk < in || pos + 12 > insize) {
5338
6.82k
      if(state->decoder.ignore_end) break; /*other errors may still happen though*/
5339
6.82k
      CERROR_BREAK(state->error, 30);
5340
0
    }
5341
5342
    /*length of the data of the chunk, excluding the 12 bytes for length, chunk type and CRC*/
5343
218k
    chunkLength = lodepng_chunk_length(chunk);
5344
    /*error: chunk length larger than the max PNG chunk size*/
5345
218k
    if(chunkLength > 2147483647) {
5346
83
      if(state->decoder.ignore_end) break; /*other errors may still happen though*/
5347
83
      CERROR_BREAK(state->error, 63);
5348
0
    }
5349
5350
218k
    if(pos + (size_t)chunkLength + 12 > insize || pos + (size_t)chunkLength + 12 < pos) {
5351
83
      CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk (or int overflow)*/
5352
0
    }
5353
5354
218k
    data = lodepng_chunk_data_const(chunk);
5355
5356
218k
    unknown = 0;
5357
5358
    /*IDAT chunk, containing compressed image data*/
5359
218k
    if(lodepng_chunk_type_equals(chunk, "IDAT")) {
5360
10.1k
      size_t newsize;
5361
10.1k
      if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
5362
10.1k
      if(newsize > insize) CERROR_BREAK(state->error, 95);
5363
10.1k
      lodepng_memcpy(idat + idatsize, data, chunkLength);
5364
10.1k
      idatsize += chunkLength;
5365
10.1k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5366
10.1k
      critical_pos = 3;
5367
10.1k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5368
207k
    } else if(lodepng_chunk_type_equals(chunk, "IEND")) {
5369
      /*IEND chunk*/
5370
20
      IEND = 1;
5371
207k
    } else if(lodepng_chunk_type_equals(chunk, "PLTE")) {
5372
      /*palette chunk (PLTE)*/
5373
2.88k
      state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
5374
2.88k
      if(state->error) break;
5375
2.87k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5376
2.87k
      critical_pos = 2;
5377
2.87k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5378
204k
    } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
5379
      /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
5380
      in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
5381
      affects the alpha channel of pixels. */
5382
2.56k
      state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
5383
2.56k
      if(state->error) break;
5384
2.56k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5385
      /*background color chunk (bKGD)*/
5386
202k
    } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
5387
1.05k
      state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
5388
1.05k
      if(state->error) break;
5389
201k
    } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
5390
      /*text chunk (tEXt)*/
5391
95.5k
      if(state->decoder.read_text_chunks) {
5392
95.5k
        state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
5393
95.5k
        if(state->error) break;
5394
95.5k
      }
5395
105k
    } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
5396
      /*compressed text chunk (zTXt)*/
5397
1.00k
      if(state->decoder.read_text_chunks) {
5398
1.00k
        state->error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);
5399
1.00k
        if(state->error) break;
5400
1.00k
      }
5401
104k
    } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
5402
      /*international text chunk (iTXt)*/
5403
95.2k
      if(state->decoder.read_text_chunks) {
5404
95.2k
        state->error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);
5405
95.2k
        if(state->error) break;
5406
95.2k
      }
5407
95.2k
    } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
5408
239
      state->error = readChunk_tIME(&state->info_png, data, chunkLength);
5409
239
      if(state->error) break;
5410
9.35k
    } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
5411
296
      state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
5412
296
      if(state->error) break;
5413
9.05k
    } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
5414
286
      state->error = readChunk_gAMA(&state->info_png, data, chunkLength);
5415
286
      if(state->error) break;
5416
8.77k
    } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
5417
214
      state->error = readChunk_cHRM(&state->info_png, data, chunkLength);
5418
214
      if(state->error) break;
5419
8.55k
    } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
5420
333
      state->error = readChunk_sRGB(&state->info_png, data, chunkLength);
5421
333
      if(state->error) break;
5422
8.22k
    } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
5423
1.27k
      state->error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);
5424
1.27k
      if(state->error) break;
5425
6.94k
    } else if(lodepng_chunk_type_equals(chunk, "cICP")) {
5426
205
      state->error = readChunk_cICP(&state->info_png, data, chunkLength);
5427
205
      if(state->error) break;
5428
6.74k
    } else if(lodepng_chunk_type_equals(chunk, "mDCV")) {
5429
222
      state->error = readChunk_mDCV(&state->info_png, data, chunkLength);
5430
222
      if(state->error) break;
5431
6.52k
    } else if(lodepng_chunk_type_equals(chunk, "cLLI")) {
5432
213
      state->error = readChunk_cLLI(&state->info_png, data, chunkLength);
5433
213
      if(state->error) break;
5434
6.30k
    } else if(lodepng_chunk_type_equals(chunk, "eXIf")) {
5435
944
      state->error = readChunk_eXIf(&state->info_png, data, chunkLength);
5436
944
      if(state->error) break;
5437
5.36k
    } else if(lodepng_chunk_type_equals(chunk, "sBIT")) {
5438
1.13k
      state->error = readChunk_sBIT(&state->info_png, data, chunkLength);
5439
1.13k
      if(state->error) break;
5440
1.13k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5441
4.22k
    } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {
5442
4.22k
      if(!lodepng_chunk_type_name_valid(chunk)) {
5443
90
        CERROR_BREAK(state->error, 121); /* invalid chunk type name */
5444
0
      }
5445
4.13k
      if(lodepng_chunk_reserved(chunk)) {
5446
3
        CERROR_BREAK(state->error, 122); /* invalid third lowercase character */
5447
0
      }
5448
5449
      /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
5450
4.13k
      if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
5451
11
        CERROR_BREAK(state->error, 69);
5452
0
      }
5453
5454
4.12k
      unknown = 1;
5455
4.12k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5456
4.12k
      if(state->decoder.remember_unknown_chunks) {
5457
0
        state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
5458
0
                                            &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
5459
0
        if(state->error) break;
5460
0
      }
5461
4.12k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5462
4.12k
    }
5463
5464
217k
    if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {
5465
0
      if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
5466
0
    }
5467
5468
217k
    if(!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize);
5469
217k
  }
5470
5471
7.95k
  if(!state->error && state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) {
5472
34
    state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */
5473
34
  }
5474
5475
7.95k
  if(!state->error) {
5476
    /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
5477
    If the decompressed size does not match the prediction, the image must be corrupt.*/
5478
6.89k
    if(state->info_png.interlace_method == 0) {
5479
4.77k
      unsigned bpp = lodepng_get_bpp(&state->info_png.color);
5480
4.77k
      expected_size = lodepng_get_raw_size_idat(*w, *h, bpp);
5481
4.77k
    } else {
5482
2.11k
      unsigned bpp = lodepng_get_bpp(&state->info_png.color);
5483
      /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/
5484
2.11k
      expected_size = 0;
5485
2.11k
      expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp);
5486
2.11k
      if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp);
5487
2.11k
      expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp);
5488
2.11k
      if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp);
5489
2.11k
      expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp);
5490
2.11k
      if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp);
5491
2.11k
      expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp);
5492
2.11k
    }
5493
5494
6.89k
    state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings);
5495
6.89k
  }
5496
7.95k
  if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/
5497
7.95k
  lodepng_free(idat);
5498
5499
7.95k
  if(!state->error) {
5500
5.39k
    outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
5501
5.39k
    *out = (unsigned char*)lodepng_malloc(outsize);
5502
5.39k
    if(!*out) state->error = 83; /*alloc fail*/
5503
5.39k
  }
5504
7.95k
  if(!state->error) {
5505
5.39k
    lodepng_memset(*out, 0, outsize);
5506
5.39k
    state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);
5507
5.39k
  }
5508
7.95k
  lodepng_free(scanlines);
5509
7.95k
}
5510
5511
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
5512
                        LodePNGState* state,
5513
8.32k
                        const unsigned char* in, size_t insize) {
5514
8.32k
  *out = 0;
5515
8.32k
  decodeGeneric(out, w, h, state, in, insize);
5516
8.32k
  if(state->error) return state->error;
5517
5.16k
  if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
5518
    /*same color type, no copying or converting of data needed*/
5519
    /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
5520
    the raw image has to the end user*/
5521
3.48k
    if(!state->decoder.color_convert) {
5522
1.72k
      state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
5523
1.72k
      if(state->error) return state->error;
5524
1.72k
    }
5525
3.48k
  } else { /*color conversion needed*/
5526
1.68k
    unsigned char* data = *out;
5527
1.68k
    size_t outsize;
5528
5529
    /*TODO: check if this works according to the statement in the documentation: "The converter can convert
5530
    from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
5531
1.68k
    if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
5532
666
       && !(state->info_raw.bitdepth == 8)) {
5533
209
      return 56; /*unsupported color mode conversion*/
5534
209
    }
5535
5536
1.47k
    outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
5537
1.47k
    *out = (unsigned char*)lodepng_malloc(outsize);
5538
1.47k
    if(!(*out)) {
5539
1
      state->error = 83; /*alloc fail*/
5540
1
    }
5541
1.47k
    else state->error = lodepng_convert(*out, data, &state->info_raw,
5542
1.47k
                                        &state->info_png.color, *w, *h);
5543
1.47k
    lodepng_free(data);
5544
1.47k
  }
5545
4.96k
  return state->error;
5546
5.16k
}
5547
5548
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
5549
0
                               size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
5550
0
  unsigned error;
5551
0
  LodePNGState state;
5552
0
  lodepng_state_init(&state);
5553
0
  state.info_raw.colortype = colortype;
5554
0
  state.info_raw.bitdepth = bitdepth;
5555
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5556
  /*disable reading things that this function doesn't output*/
5557
0
  state.decoder.read_text_chunks = 0;
5558
0
  state.decoder.remember_unknown_chunks = 0;
5559
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5560
0
  error = lodepng_decode(out, w, h, &state, in, insize);
5561
0
  lodepng_state_cleanup(&state);
5562
0
  return error;
5563
0
}
5564
5565
0
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
5566
0
  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
5567
0
}
5568
5569
0
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
5570
0
  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
5571
0
}
5572
5573
#ifdef LODEPNG_COMPILE_DISK
5574
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
5575
0
                             LodePNGColorType colortype, unsigned bitdepth) {
5576
0
  unsigned char* buffer = 0;
5577
0
  size_t buffersize;
5578
0
  unsigned error;
5579
  /* safe output values in case error happens */
5580
0
  *out = 0;
5581
0
  *w = *h = 0;
5582
0
  error = lodepng_load_file(&buffer, &buffersize, filename);
5583
0
  if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
5584
0
  lodepng_free(buffer);
5585
0
  return error;
5586
0
}
5587
5588
0
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
5589
0
  return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
5590
0
}
5591
5592
0
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
5593
0
  return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
5594
0
}
5595
#endif /*LODEPNG_COMPILE_DISK*/
5596
5597
4.88k
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) {
5598
4.88k
  settings->color_convert = 1;
5599
4.88k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5600
4.88k
  settings->read_text_chunks = 1;
5601
4.88k
  settings->remember_unknown_chunks = 0;
5602
4.88k
  settings->max_text_size = 16777216;
5603
4.88k
  settings->max_icc_size = 16777216; /* 16MB is much more than enough for any reasonable ICC profile */
5604
4.88k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
5605
4.88k
  settings->ignore_crc = 0;
5606
4.88k
  settings->ignore_critical = 0;
5607
4.88k
  settings->ignore_end = 0;
5608
4.88k
  lodepng_decompress_settings_init(&settings->zlibsettings);
5609
4.88k
}
5610
5611
#endif /*LODEPNG_COMPILE_DECODER*/
5612
5613
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
5614
5615
4.88k
void lodepng_state_init(LodePNGState* state) {
5616
4.88k
#ifdef LODEPNG_COMPILE_DECODER
5617
4.88k
  lodepng_decoder_settings_init(&state->decoder);
5618
4.88k
#endif /*LODEPNG_COMPILE_DECODER*/
5619
4.88k
#ifdef LODEPNG_COMPILE_ENCODER
5620
4.88k
  lodepng_encoder_settings_init(&state->encoder);
5621
4.88k
#endif /*LODEPNG_COMPILE_ENCODER*/
5622
4.88k
  lodepng_color_mode_init(&state->info_raw);
5623
4.88k
  lodepng_info_init(&state->info_png);
5624
4.88k
  state->error = 1;
5625
4.88k
}
5626
5627
4.88k
void lodepng_state_cleanup(LodePNGState* state) {
5628
4.88k
  lodepng_color_mode_cleanup(&state->info_raw);
5629
4.88k
  lodepng_info_cleanup(&state->info_png);
5630
4.88k
}
5631
5632
0
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) {
5633
0
  lodepng_state_cleanup(dest);
5634
0
  *dest = *source;
5635
0
  lodepng_color_mode_init(&dest->info_raw);
5636
0
  lodepng_info_init(&dest->info_png);
5637
0
  dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
5638
0
  dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
5639
0
}
5640
5641
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
5642
5643
#ifdef LODEPNG_COMPILE_ENCODER
5644
5645
/* ////////////////////////////////////////////////////////////////////////// */
5646
/* / PNG Encoder                                                            / */
5647
/* ////////////////////////////////////////////////////////////////////////// */
5648
5649
5650
0
static unsigned writeSignature(ucvector* out) {
5651
0
  size_t pos = out->size;
5652
0
  const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10};
5653
  /*8 bytes PNG signature, aka the magic bytes*/
5654
0
  if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/
5655
0
  lodepng_memcpy(out->data + pos, signature, 8);
5656
0
  return 0;
5657
0
}
5658
5659
static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
5660
0
                              LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) {
5661
0
  unsigned char *chunk, *data;
5662
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR"));
5663
0
  data = chunk + 8;
5664
5665
0
  lodepng_set32bitInt(data + 0, w); /*width*/
5666
0
  lodepng_set32bitInt(data + 4, h); /*height*/
5667
0
  data[8] = (unsigned char)bitdepth; /*bit depth*/
5668
0
  data[9] = (unsigned char)colortype; /*color type*/
5669
0
  data[10] = 0; /*compression method*/
5670
0
  data[11] = 0; /*filter method*/
5671
0
  data[12] = interlace_method; /*interlace method*/
5672
5673
0
  lodepng_chunk_generate_crc(chunk);
5674
0
  return 0;
5675
0
}
5676
5677
/* only adds the chunk if needed (there is a key or palette with alpha) */
5678
0
static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) {
5679
0
  unsigned char* chunk;
5680
0
  size_t i, j = 8;
5681
5682
0
  if(info->palettesize == 0 || info->palettesize > 256) {
5683
0
    return 68; /*invalid palette size, it is only allowed to be 1-256*/
5684
0
  }
5685
5686
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE"));
5687
5688
0
  for(i = 0; i != info->palettesize; ++i) {
5689
    /*add all channels except alpha channel*/
5690
0
    chunk[j++] = info->palette[i * 4 + 0];
5691
0
    chunk[j++] = info->palette[i * 4 + 1];
5692
0
    chunk[j++] = info->palette[i * 4 + 2];
5693
0
  }
5694
5695
0
  lodepng_chunk_generate_crc(chunk);
5696
0
  return 0;
5697
0
}
5698
5699
0
static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) {
5700
0
  unsigned char* chunk = 0;
5701
5702
0
  if(info->colortype == LCT_PALETTE) {
5703
0
    size_t i, amount = info->palettesize;
5704
    /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
5705
0
    for(i = info->palettesize; i != 0; --i) {
5706
0
      if(info->palette[4 * (i - 1) + 3] != 255) break;
5707
0
      --amount;
5708
0
    }
5709
0
    if(amount) {
5710
0
      CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS"));
5711
      /*add the alpha channel values from the palette*/
5712
0
      for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3];
5713
0
    }
5714
0
  } else if(info->colortype == LCT_GREY) {
5715
0
    if(info->key_defined) {
5716
0
      CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS"));
5717
0
      chunk[8] = (unsigned char)(info->key_r >> 8);
5718
0
      chunk[9] = (unsigned char)(info->key_r & 255);
5719
0
    }
5720
0
  } else if(info->colortype == LCT_RGB) {
5721
0
    if(info->key_defined) {
5722
0
      CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS"));
5723
0
      chunk[8] = (unsigned char)(info->key_r >> 8);
5724
0
      chunk[9] = (unsigned char)(info->key_r & 255);
5725
0
      chunk[10] = (unsigned char)(info->key_g >> 8);
5726
0
      chunk[11] = (unsigned char)(info->key_g & 255);
5727
0
      chunk[12] = (unsigned char)(info->key_b >> 8);
5728
0
      chunk[13] = (unsigned char)(info->key_b & 255);
5729
0
    }
5730
0
  }
5731
5732
0
  if(chunk) lodepng_chunk_generate_crc(chunk);
5733
0
  return 0;
5734
0
}
5735
5736
static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
5737
0
                              LodePNGCompressSettings* zlibsettings) {
5738
0
  unsigned error = 0;
5739
0
  unsigned char* zlib = 0;
5740
0
  size_t pos = 0;
5741
0
  size_t zlibsize = 0;
5742
  /* max chunk length allowed by the specification is 2147483647 bytes */
5743
0
  const size_t max_chunk_length = 2147483647u;
5744
5745
0
  error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings);
5746
0
  while(!error) {
5747
0
    if(zlibsize - pos > max_chunk_length) {
5748
0
      error = lodepng_chunk_createv(out, max_chunk_length, "IDAT", zlib + pos);
5749
0
      pos += max_chunk_length;
5750
0
    } else {
5751
0
      error = lodepng_chunk_createv(out, zlibsize - pos, "IDAT", zlib + pos);
5752
0
      break;
5753
0
    }
5754
0
  }
5755
0
  lodepng_free(zlib);
5756
0
  return error;
5757
0
}
5758
5759
0
static unsigned addChunk_IEND(ucvector* out) {
5760
0
  return lodepng_chunk_createv(out, 0, "IEND", 0);
5761
0
}
5762
5763
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
5764
5765
0
static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) {
5766
0
  unsigned char* chunk = 0;
5767
0
  size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring);
5768
0
  size_t size = keysize + 1 + textsize;
5769
0
  if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
5770
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt"));
5771
0
  lodepng_memcpy(chunk + 8, keyword, keysize);
5772
0
  chunk[8 + keysize] = 0; /*null termination char*/
5773
0
  lodepng_memcpy(chunk + 9 + keysize, textstring, textsize);
5774
0
  lodepng_chunk_generate_crc(chunk);
5775
0
  return 0;
5776
0
}
5777
5778
static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
5779
0
                              LodePNGCompressSettings* zlibsettings) {
5780
0
  unsigned error = 0;
5781
0
  unsigned char* chunk = 0;
5782
0
  unsigned char* compressed = 0;
5783
0
  size_t compressedsize = 0;
5784
0
  size_t textsize = lodepng_strlen(textstring);
5785
0
  size_t keysize = lodepng_strlen(keyword);
5786
0
  if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
5787
5788
0
  error = zlib_compress(&compressed, &compressedsize,
5789
0
                        (const unsigned char*)textstring, textsize, zlibsettings);
5790
0
  if(!error) {
5791
0
    size_t size = keysize + 2 + compressedsize;
5792
0
    error = lodepng_chunk_init(&chunk, out, size, "zTXt");
5793
0
  }
5794
0
  if(!error) {
5795
0
    lodepng_memcpy(chunk + 8, keyword, keysize);
5796
0
    chunk[8 + keysize] = 0; /*null termination char*/
5797
0
    chunk[9 + keysize] = 0; /*compression method: 0*/
5798
0
    lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);
5799
0
    lodepng_chunk_generate_crc(chunk);
5800
0
  }
5801
5802
0
  lodepng_free(compressed);
5803
0
  return error;
5804
0
}
5805
5806
static unsigned addChunk_iTXt(ucvector* out, unsigned compress, const char* keyword, const char* langtag,
5807
0
                              const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) {
5808
0
  unsigned error = 0;
5809
0
  unsigned char* chunk = 0;
5810
0
  unsigned char* compressed = 0;
5811
0
  size_t compressedsize = 0;
5812
0
  size_t textsize = lodepng_strlen(textstring);
5813
0
  size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey);
5814
5815
0
  if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
5816
5817
0
  if(compress) {
5818
0
    error = zlib_compress(&compressed, &compressedsize,
5819
0
                          (const unsigned char*)textstring, textsize, zlibsettings);
5820
0
  }
5821
0
  if(!error) {
5822
0
    size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize);
5823
0
    error = lodepng_chunk_init(&chunk, out, size, "iTXt");
5824
0
  }
5825
0
  if(!error) {
5826
0
    size_t pos = 8;
5827
0
    lodepng_memcpy(chunk + pos, keyword, keysize);
5828
0
    pos += keysize;
5829
0
    chunk[pos++] = 0; /*null termination char*/
5830
0
    chunk[pos++] = (compress ? 1 : 0); /*compression flag*/
5831
0
    chunk[pos++] = 0; /*compression method: 0*/
5832
0
    lodepng_memcpy(chunk + pos, langtag, langsize);
5833
0
    pos += langsize;
5834
0
    chunk[pos++] = 0; /*null termination char*/
5835
0
    lodepng_memcpy(chunk + pos, transkey, transsize);
5836
0
    pos += transsize;
5837
0
    chunk[pos++] = 0; /*null termination char*/
5838
0
    if(compress) {
5839
0
      lodepng_memcpy(chunk + pos, compressed, compressedsize);
5840
0
    } else {
5841
0
      lodepng_memcpy(chunk + pos, textstring, textsize);
5842
0
    }
5843
0
    lodepng_chunk_generate_crc(chunk);
5844
0
  }
5845
5846
0
  lodepng_free(compressed);
5847
0
  return error;
5848
0
}
5849
5850
0
static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) {
5851
0
  unsigned char* chunk = 0;
5852
0
  if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
5853
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD"));
5854
0
    chunk[8] = (unsigned char)(info->background_r >> 8);
5855
0
    chunk[9] = (unsigned char)(info->background_r & 255);
5856
0
  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
5857
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD"));
5858
0
    chunk[8] = (unsigned char)(info->background_r >> 8);
5859
0
    chunk[9] = (unsigned char)(info->background_r & 255);
5860
0
    chunk[10] = (unsigned char)(info->background_g >> 8);
5861
0
    chunk[11] = (unsigned char)(info->background_g & 255);
5862
0
    chunk[12] = (unsigned char)(info->background_b >> 8);
5863
0
    chunk[13] = (unsigned char)(info->background_b & 255);
5864
0
  } else if(info->color.colortype == LCT_PALETTE) {
5865
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD"));
5866
0
    chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/
5867
0
  }
5868
0
  if(chunk) lodepng_chunk_generate_crc(chunk);
5869
0
  return 0;
5870
0
}
5871
5872
0
static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) {
5873
0
  unsigned char* chunk;
5874
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME"));
5875
0
  chunk[8] = (unsigned char)(time->year >> 8);
5876
0
  chunk[9] = (unsigned char)(time->year & 255);
5877
0
  chunk[10] = (unsigned char)time->month;
5878
0
  chunk[11] = (unsigned char)time->day;
5879
0
  chunk[12] = (unsigned char)time->hour;
5880
0
  chunk[13] = (unsigned char)time->minute;
5881
0
  chunk[14] = (unsigned char)time->second;
5882
0
  lodepng_chunk_generate_crc(chunk);
5883
0
  return 0;
5884
0
}
5885
5886
0
static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) {
5887
0
  unsigned char* chunk;
5888
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs"));
5889
0
  lodepng_set32bitInt(chunk + 8, info->phys_x);
5890
0
  lodepng_set32bitInt(chunk + 12, info->phys_y);
5891
0
  chunk[16] = info->phys_unit;
5892
0
  lodepng_chunk_generate_crc(chunk);
5893
0
  return 0;
5894
0
}
5895
5896
0
static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) {
5897
0
  unsigned char* chunk;
5898
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA"));
5899
0
  lodepng_set32bitInt(chunk + 8, info->gama_gamma);
5900
0
  lodepng_chunk_generate_crc(chunk);
5901
0
  return 0;
5902
0
}
5903
5904
0
static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) {
5905
0
  unsigned char* chunk;
5906
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM"));
5907
0
  lodepng_set32bitInt(chunk + 8, info->chrm_white_x);
5908
0
  lodepng_set32bitInt(chunk + 12, info->chrm_white_y);
5909
0
  lodepng_set32bitInt(chunk + 16, info->chrm_red_x);
5910
0
  lodepng_set32bitInt(chunk + 20, info->chrm_red_y);
5911
0
  lodepng_set32bitInt(chunk + 24, info->chrm_green_x);
5912
0
  lodepng_set32bitInt(chunk + 28, info->chrm_green_y);
5913
0
  lodepng_set32bitInt(chunk + 32, info->chrm_blue_x);
5914
0
  lodepng_set32bitInt(chunk + 36, info->chrm_blue_y);
5915
0
  lodepng_chunk_generate_crc(chunk);
5916
0
  return 0;
5917
0
}
5918
5919
0
static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) {
5920
0
  unsigned char data = info->srgb_intent;
5921
0
  return lodepng_chunk_createv(out, 1, "sRGB", &data);
5922
0
}
5923
5924
0
static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) {
5925
0
  unsigned error = 0;
5926
0
  unsigned char* chunk = 0;
5927
0
  unsigned char* compressed = 0;
5928
0
  size_t compressedsize = 0;
5929
0
  size_t keysize = lodepng_strlen(info->iccp_name);
5930
5931
0
  if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
5932
0
  error = zlib_compress(&compressed, &compressedsize,
5933
0
                        info->iccp_profile, info->iccp_profile_size, zlibsettings);
5934
0
  if(!error) {
5935
0
    size_t size = keysize + 2 + compressedsize;
5936
0
    error = lodepng_chunk_init(&chunk, out, size, "iCCP");
5937
0
  }
5938
0
  if(!error) {
5939
0
    lodepng_memcpy(chunk + 8, info->iccp_name, keysize);
5940
0
    chunk[8 + keysize] = 0; /*null termination char*/
5941
0
    chunk[9 + keysize] = 0; /*compression method: 0*/
5942
0
    lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);
5943
0
    lodepng_chunk_generate_crc(chunk);
5944
0
  }
5945
5946
0
  lodepng_free(compressed);
5947
0
  return error;
5948
0
}
5949
5950
0
static unsigned addChunk_cICP(ucvector* out, const LodePNGInfo* info) {
5951
0
  unsigned char* chunk;
5952
  /* Allow up to 255 since they are bytes. The ITU-R-BT.709 spec has a more
5953
  restricted set of valid values for each field, but that's up to the error
5954
  handling of a CICP library, not the PNG encoding/decoding, to manage. */
5955
0
  if(info->cicp_color_primaries > 255) return 116;
5956
0
  if(info->cicp_transfer_function > 255) return 116;
5957
0
  if(info->cicp_matrix_coefficients > 255) return 116;
5958
0
  if(info->cicp_video_full_range_flag > 255) return 116;
5959
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "cICP"));
5960
0
  chunk[8 + 0] = (unsigned char)info->cicp_color_primaries;
5961
0
  chunk[8 + 1] = (unsigned char)info->cicp_transfer_function;
5962
0
  chunk[8 + 2] = (unsigned char)info->cicp_matrix_coefficients;
5963
0
  chunk[8 + 3] = (unsigned char)info->cicp_video_full_range_flag;
5964
0
  lodepng_chunk_generate_crc(chunk);
5965
0
  return 0;
5966
0
}
5967
5968
0
static unsigned addChunk_mDCV(ucvector* out, const LodePNGInfo* info) {
5969
0
  unsigned char* chunk;
5970
  /* Allow up to 65535 since they are 16-bit ints. */
5971
0
  if(info->mdcv_red_x > 65535) return 118;
5972
0
  if(info->mdcv_red_y > 65535) return 118;
5973
0
  if(info->mdcv_green_x > 65535) return 118;
5974
0
  if(info->mdcv_green_y > 65535) return 118;
5975
0
  if(info->mdcv_blue_x > 65535) return 118;
5976
0
  if(info->mdcv_blue_y > 65535) return 118;
5977
0
  if(info->mdcv_white_x > 65535) return 118;
5978
0
  if(info->mdcv_white_y > 65535) return 118;
5979
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 24, "mDCV"));
5980
0
  chunk[8 + 0] = (unsigned char)((info->mdcv_red_x) >> 8u);
5981
0
  chunk[8 + 1] = (unsigned char)(info->mdcv_red_x);
5982
0
  chunk[8 + 2] = (unsigned char)((info->mdcv_red_y) >> 8u);
5983
0
  chunk[8 + 3] = (unsigned char)(info->mdcv_red_y);
5984
0
  chunk[8 + 4] = (unsigned char)((info->mdcv_green_x) >> 8u);
5985
0
  chunk[8 + 5] = (unsigned char)(info->mdcv_green_x);
5986
0
  chunk[8 + 6] = (unsigned char)((info->mdcv_green_y) >> 8u);
5987
0
  chunk[8 + 7] = (unsigned char)(info->mdcv_green_y);
5988
0
  chunk[8 + 8] = (unsigned char)((info->mdcv_blue_x) >> 8u);
5989
0
  chunk[8 + 9] = (unsigned char)(info->mdcv_blue_x);
5990
0
  chunk[8 + 10] = (unsigned char)((info->mdcv_blue_y) >> 8u);
5991
0
  chunk[8 + 11] = (unsigned char)(info->mdcv_blue_y);
5992
0
  chunk[8 + 12] = (unsigned char)((info->mdcv_white_x) >> 8u);
5993
0
  chunk[8 + 13] = (unsigned char)(info->mdcv_white_x);
5994
0
  chunk[8 + 14] = (unsigned char)((info->mdcv_white_y) >> 8u);
5995
0
  chunk[8 + 15] = (unsigned char)(info->mdcv_white_y);
5996
0
  lodepng_set32bitInt(chunk + 8 + 16, info->mdcv_max_luminance);
5997
0
  lodepng_set32bitInt(chunk + 8 + 20, info->mdcv_min_luminance);
5998
0
  lodepng_chunk_generate_crc(chunk);
5999
0
  return 0;
6000
0
}
6001
6002
0
static unsigned addChunk_cLLI(ucvector* out, const LodePNGInfo* info) {
6003
0
  unsigned char* chunk;
6004
0
  CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 8, "cLLI"));
6005
0
  lodepng_set32bitInt(chunk + 8 + 0, info->clli_max_cll);
6006
0
  lodepng_set32bitInt(chunk + 8 + 4, info->clli_max_fall);
6007
0
  lodepng_chunk_generate_crc(chunk);
6008
0
  return 0;
6009
0
}
6010
6011
0
static unsigned addChunk_eXIf(ucvector* out, const LodePNGInfo* info) {
6012
0
  return lodepng_chunk_createv(out, info->exif_size, "eXIf", info->exif);
6013
0
}
6014
6015
0
static unsigned addChunk_sBIT(ucvector* out, const LodePNGInfo* info) {
6016
0
  unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth;
6017
0
  unsigned char* chunk = 0;
6018
0
  if(info->color.colortype == LCT_GREY) {
6019
0
    if(info->sbit_r == 0 || info->sbit_r > bitdepth) return 115;
6020
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "sBIT"));
6021
0
    chunk[8] = info->sbit_r;
6022
0
  } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) {
6023
0
    if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0) return 115;
6024
0
    if(info->sbit_r > bitdepth || info->sbit_g > bitdepth || info->sbit_b > bitdepth) return 115;
6025
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 3, "sBIT"));
6026
0
    chunk[8] = info->sbit_r;
6027
0
    chunk[9] = info->sbit_g;
6028
0
    chunk[10] = info->sbit_b;
6029
0
  } else if(info->color.colortype == LCT_GREY_ALPHA) {
6030
0
    if(info->sbit_r == 0 || info->sbit_a == 0) return 115;
6031
0
    if(info->sbit_r > bitdepth || info->sbit_a > bitdepth) return 115;
6032
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "sBIT"));
6033
0
    chunk[8] = info->sbit_r;
6034
0
    chunk[9] = info->sbit_a;
6035
0
  } else if(info->color.colortype == LCT_RGBA) {
6036
0
    if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0 || info->sbit_a == 0 ||
6037
0
       info->sbit_r > bitdepth || info->sbit_g > bitdepth ||
6038
0
       info->sbit_b > bitdepth || info->sbit_a > bitdepth) {
6039
0
      return 115;
6040
0
    }
6041
0
    CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "sBIT"));
6042
0
    chunk[8] = info->sbit_r;
6043
0
    chunk[9] = info->sbit_g;
6044
0
    chunk[10] = info->sbit_b;
6045
0
    chunk[11] = info->sbit_a;
6046
0
  }
6047
0
  if(chunk) lodepng_chunk_generate_crc(chunk);
6048
0
  return 0;
6049
0
}
6050
6051
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6052
6053
static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
6054
0
                           size_t length, size_t bytewidth, unsigned char filterType) {
6055
0
  size_t i;
6056
0
  switch(filterType) {
6057
0
    case 0: /*None*/
6058
0
      for(i = 0; i != length; ++i) out[i] = scanline[i];
6059
0
      break;
6060
0
    case 1: /*Sub*/
6061
0
      for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
6062
0
      for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
6063
0
      break;
6064
0
    case 2: /*Up*/
6065
0
      if(prevline) {
6066
0
        for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
6067
0
      } else {
6068
0
        for(i = 0; i != length; ++i) out[i] = scanline[i];
6069
0
      }
6070
0
      break;
6071
0
    case 3: /*Average*/
6072
0
      if(prevline) {
6073
0
        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
6074
0
        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
6075
0
      } else {
6076
0
        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
6077
0
        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
6078
0
      }
6079
0
      break;
6080
0
    case 4: /*Paeth*/
6081
0
      if(prevline) {
6082
        /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
6083
0
        for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
6084
0
        for(i = bytewidth; i < length; ++i) {
6085
0
          out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
6086
0
        }
6087
0
      } else {
6088
0
        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
6089
        /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
6090
0
        for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
6091
0
      }
6092
0
      break;
6093
0
    default: return; /*invalid filter type given*/
6094
0
  }
6095
0
}
6096
6097
/* integer binary logarithm, max return value is 31 */
6098
0
static size_t ilog2(size_t i) {
6099
0
  size_t result = 0;
6100
0
  if(i >= 65536) { result += 16; i >>= 16; }
6101
0
  if(i >= 256) { result += 8; i >>= 8; }
6102
0
  if(i >= 16) { result += 4; i >>= 4; }
6103
0
  if(i >= 4) { result += 2; i >>= 2; }
6104
0
  if(i >= 2) { result += 1; /*i >>= 1;*/ }
6105
0
  return result;
6106
0
}
6107
6108
/* integer approximation for i * log2(i), helper function for LFS_ENTROPY */
6109
0
static size_t ilog2i(size_t i) {
6110
0
  size_t l;
6111
0
  if(i == 0) return 0;
6112
0
  l = ilog2(i);
6113
  /* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u)
6114
  linearly approximates the missing fractional part multiplied by i */
6115
0
  return i * l + ((i - (((size_t)1) << l)) << 1u);
6116
0
}
6117
6118
static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
6119
0
                       const LodePNGColorMode* color, const LodePNGEncoderSettings* settings) {
6120
  /*
6121
  For PNG filter method 0
6122
  out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are
6123
  the scanlines with 1 extra byte per scanline
6124
  */
6125
6126
0
  unsigned bpp = lodepng_get_bpp(color);
6127
  /*the width of a scanline in bytes, not including the filter type*/
6128
0
  size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;
6129
6130
  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
6131
0
  size_t bytewidth = (bpp + 7u) / 8u;
6132
0
  const unsigned char* prevline = 0;
6133
0
  unsigned x, y;
6134
0
  unsigned error = 0;
6135
0
  LodePNGFilterStrategy strategy = settings->filter_strategy;
6136
6137
0
  if(settings->filter_palette_zero && (color->colortype == LCT_PALETTE || color->bitdepth < 8)) {
6138
    /*if the filter_palette_zero setting is enabled, override the filter strategy with
6139
    zero for all scanlines for palette and less-than-8-bitdepth images*/
6140
0
    strategy = LFS_ZERO;
6141
0
  }
6142
6143
0
  if(bpp == 0) return 31; /*error: invalid color type*/
6144
6145
0
  if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) {
6146
0
    unsigned char type = (unsigned char)strategy;
6147
0
    for(y = 0; y != h; ++y) {
6148
0
      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
6149
0
      size_t inindex = linebytes * y;
6150
0
      out[outindex] = type; /*filter type byte*/
6151
0
      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
6152
0
      prevline = &in[inindex];
6153
0
    }
6154
0
  } else if(strategy == LFS_MINSUM) {
6155
    /*adaptive filtering: independently for each row, try all five filter types and select the one that produces the
6156
    smallest sum of absolute values per row.*/
6157
0
    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
6158
0
    size_t smallest = 0;
6159
0
    unsigned char type, bestType = 0;
6160
6161
0
    for(type = 0; type != 5; ++type) {
6162
0
      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
6163
0
      if(!attempt[type]) error = 83; /*alloc fail*/
6164
0
    }
6165
6166
0
    if(!error) {
6167
0
      for(y = 0; y != h; ++y) {
6168
        /*try the 5 filter types*/
6169
0
        for(type = 0; type != 5; ++type) {
6170
0
          size_t sum = 0;
6171
0
          filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
6172
6173
          /*calculate the sum of the result*/
6174
0
          if(type == 0) {
6175
0
            for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]);
6176
0
          } else {
6177
0
            for(x = 0; x != linebytes; ++x) {
6178
              /*For differences, each byte should be treated as signed, values above 127 are negative
6179
              (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
6180
              This means filtertype 0 is almost never chosen, but that is justified.*/
6181
0
              unsigned char s = attempt[type][x];
6182
0
              sum += s < 128 ? s : (255U - s);
6183
0
            }
6184
0
          }
6185
6186
          /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
6187
0
          if(type == 0 || sum < smallest) {
6188
0
            bestType = type;
6189
0
            smallest = sum;
6190
0
          }
6191
0
        }
6192
6193
0
        prevline = &in[y * linebytes];
6194
6195
        /*now fill the out values*/
6196
0
        out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
6197
0
        for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
6198
0
      }
6199
0
    }
6200
6201
0
    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
6202
0
  } else if(strategy == LFS_ENTROPY) {
6203
0
    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
6204
0
    size_t bestSum = 0;
6205
0
    unsigned type, bestType = 0;
6206
0
    unsigned count[256];
6207
6208
0
    for(type = 0; type != 5; ++type) {
6209
0
      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
6210
0
      if(!attempt[type]) error = 83; /*alloc fail*/
6211
0
    }
6212
6213
0
    if(!error) {
6214
0
      for(y = 0; y != h; ++y) {
6215
        /*try the 5 filter types*/
6216
0
        for(type = 0; type != 5; ++type) {
6217
0
          size_t sum = 0;
6218
0
          filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
6219
0
          lodepng_memset(count, 0, 256 * sizeof(*count));
6220
0
          for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
6221
0
          ++count[type]; /*the filter type itself is part of the scanline*/
6222
0
          for(x = 0; x != 256; ++x) {
6223
0
            sum += ilog2i(count[x]);
6224
0
          }
6225
          /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
6226
0
          if(type == 0 || sum > bestSum) {
6227
0
            bestType = type;
6228
0
            bestSum = sum;
6229
0
          }
6230
0
        }
6231
6232
0
        prevline = &in[y * linebytes];
6233
6234
        /*now fill the out values*/
6235
0
        out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
6236
0
        for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
6237
0
      }
6238
0
    }
6239
6240
0
    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
6241
0
  } else if(strategy == LFS_PREDEFINED) {
6242
0
    for(y = 0; y != h; ++y) {
6243
0
      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
6244
0
      size_t inindex = linebytes * y;
6245
0
      unsigned char type = settings->predefined_filters[y];
6246
0
      out[outindex] = type; /*filter type byte*/
6247
0
      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
6248
0
      prevline = &in[inindex];
6249
0
    }
6250
0
  } else if(strategy == LFS_BRUTE_FORCE) {
6251
    /*brute force filter chooser.
6252
    deflate the scanline after every filter attempt to see which one deflates best.
6253
    This is very slow and gives only slightly smaller, sometimes even larger, result*/
6254
0
    size_t size[5];
6255
0
    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
6256
0
    size_t smallest = 0;
6257
0
    unsigned type = 0, bestType = 0;
6258
0
    unsigned char* dummy;
6259
0
    LodePNGCompressSettings zlibsettings;
6260
0
    lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings));
6261
    /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
6262
    to simulate the true case where the tree is the same for the whole image. Sometimes it gives
6263
    better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
6264
    cases better compression. It does make this a bit less slow, so it's worth doing this.*/
6265
0
    zlibsettings.btype = 1;
6266
    /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
6267
    images only, so disable it*/
6268
0
    zlibsettings.custom_zlib = 0;
6269
0
    zlibsettings.custom_deflate = 0;
6270
0
    for(type = 0; type != 5; ++type) {
6271
0
      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
6272
0
      if(!attempt[type]) error = 83; /*alloc fail*/
6273
0
    }
6274
0
    if(!error) {
6275
0
      for(y = 0; y != h; ++y) /*try the 5 filter types*/ {
6276
0
        for(type = 0; type != 5; ++type) {
6277
0
          unsigned testsize = (unsigned)linebytes;
6278
          /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
6279
6280
0
          filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
6281
0
          size[type] = 0;
6282
0
          dummy = 0;
6283
0
          zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
6284
0
          lodepng_free(dummy);
6285
          /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
6286
0
          if(type == 0 || size[type] < smallest) {
6287
0
            bestType = type;
6288
0
            smallest = size[type];
6289
0
          }
6290
0
        }
6291
0
        prevline = &in[y * linebytes];
6292
0
        out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
6293
0
        for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
6294
0
      }
6295
0
    }
6296
0
    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
6297
0
  }
6298
0
  else return 88; /* unknown filter strategy */
6299
6300
0
  return error;
6301
0
}
6302
6303
static void addPaddingBits(unsigned char* out, const unsigned char* in,
6304
0
                           size_t olinebits, size_t ilinebits, unsigned h) {
6305
  /*The opposite of the removePaddingBits function
6306
  olinebits must be >= ilinebits*/
6307
0
  unsigned y;
6308
0
  size_t diff = olinebits - ilinebits;
6309
0
  size_t obp = 0, ibp = 0; /*bit pointers*/
6310
0
  for(y = 0; y != h; ++y) {
6311
0
    size_t x;
6312
0
    for(x = 0; x < ilinebits; ++x) {
6313
0
      unsigned char bit = readBitFromReversedStream(&ibp, in);
6314
0
      setBitOfReversedStream(&obp, out, bit);
6315
0
    }
6316
    /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
6317
    "Use of uninitialised value of size ###" warning from valgrind*/
6318
0
    for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
6319
0
  }
6320
0
}
6321
6322
/*
6323
in: non-interlaced image with size w*h
6324
out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
6325
 no padding bits between scanlines, but between reduced images so that each
6326
 reduced image starts at a byte.
6327
bpp: bits per pixel
6328
there are no padding bits, not between scanlines, not between reduced images
6329
in has the following size in bits: w * h * bpp.
6330
out is possibly bigger due to padding bits between reduced images
6331
NOTE: comments about padding bits are only relevant if bpp < 8
6332
*/
6333
0
static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
6334
0
  unsigned passw[7], passh[7];
6335
0
  size_t filter_passstart[8], padded_passstart[8], passstart[8];
6336
0
  unsigned i;
6337
6338
0
  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
6339
6340
0
  if(bpp >= 8) {
6341
0
    for(i = 0; i != 7; ++i) {
6342
0
      unsigned x, y, b;
6343
0
      size_t bytewidth = bpp / 8u;
6344
0
      for(y = 0; y < passh[i]; ++y)
6345
0
      for(x = 0; x < passw[i]; ++x) {
6346
0
        size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
6347
0
        size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
6348
0
        for(b = 0; b < bytewidth; ++b) {
6349
0
          out[pixeloutstart + b] = in[pixelinstart + b];
6350
0
        }
6351
0
      }
6352
0
    }
6353
0
  } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
6354
0
    for(i = 0; i != 7; ++i) {
6355
0
      unsigned x, y, b;
6356
0
      unsigned ilinebits = bpp * passw[i];
6357
0
      unsigned olinebits = bpp * w;
6358
0
      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
6359
0
      for(y = 0; y < passh[i]; ++y)
6360
0
      for(x = 0; x < passw[i]; ++x) {
6361
0
        ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
6362
0
        obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
6363
0
        for(b = 0; b < bpp; ++b) {
6364
0
          unsigned char bit = readBitFromReversedStream(&ibp, in);
6365
0
          setBitOfReversedStream(&obp, out, bit);
6366
0
        }
6367
0
      }
6368
0
    }
6369
0
  }
6370
0
}
6371
6372
/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
6373
return value is error**/
6374
static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
6375
                                    unsigned w, unsigned h,
6376
0
                                    const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) {
6377
  /*
6378
  This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
6379
  *) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter
6380
  *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
6381
  */
6382
0
  size_t bpp = lodepng_get_bpp(&info_png->color);
6383
0
  unsigned error = 0;
6384
0
  if(info_png->interlace_method == 0) {
6385
    /*image size plus an extra byte per scanline + possible padding bits*/
6386
0
    *outsize = (size_t)h + ((size_t)h * (((size_t)w * bpp + 7u) / 8u));
6387
0
    *out = (unsigned char*)lodepng_malloc(*outsize);
6388
0
    if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
6389
6390
0
    if(!error) {
6391
      /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
6392
0
      if(bpp < 8 && (size_t)w * bpp != (((size_t)w * bpp + 7u) / 8u) * 8u) {
6393
0
        unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u));
6394
0
        if(!padded) error = 83; /*alloc fail*/
6395
0
        if(!error) {
6396
0
          addPaddingBits(padded, in, (((size_t)w * bpp + 7u) / 8u) * 8u, (size_t)w * bpp, h);
6397
0
          error = filter(*out, padded, w, h, &info_png->color, settings);
6398
0
        }
6399
0
        lodepng_free(padded);
6400
0
      } else {
6401
        /*we can immediately filter into the out buffer, no other steps needed*/
6402
0
        error = filter(*out, in, w, h, &info_png->color, settings);
6403
0
      }
6404
0
    }
6405
0
  } else /*interlace_method is 1 (Adam7)*/ {
6406
0
    unsigned passw[7], passh[7];
6407
0
    size_t filter_passstart[8], padded_passstart[8], passstart[8];
6408
0
    unsigned char* adam7;
6409
6410
0
    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, (unsigned)bpp);
6411
6412
0
    *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
6413
0
    *out = (unsigned char*)lodepng_malloc(*outsize);
6414
0
    if(!(*out)) error = 83; /*alloc fail*/
6415
6416
0
    adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
6417
0
    if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
6418
6419
0
    if(!error) {
6420
0
      unsigned i;
6421
6422
0
      Adam7_interlace(adam7, in, w, h, (unsigned)bpp);
6423
0
      for(i = 0; i != 7; ++i) {
6424
0
        if(bpp < 8) {
6425
0
          unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
6426
0
          if(!padded) ERROR_BREAK(83); /*alloc fail*/
6427
0
          addPaddingBits(padded, &adam7[passstart[i]],
6428
0
                         (((size_t)passw[i] * bpp + 7u) / 8u) * 8u, (size_t)passw[i] * bpp, passh[i]);
6429
0
          error = filter(&(*out)[filter_passstart[i]], padded,
6430
0
                         passw[i], passh[i], &info_png->color, settings);
6431
0
          lodepng_free(padded);
6432
0
        } else {
6433
0
          error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
6434
0
                         passw[i], passh[i], &info_png->color, settings);
6435
0
        }
6436
6437
0
        if(error) break;
6438
0
      }
6439
0
    }
6440
6441
0
    lodepng_free(adam7);
6442
0
  }
6443
6444
0
  return error;
6445
0
}
6446
6447
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6448
0
static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) {
6449
0
  unsigned char* inchunk = data;
6450
0
  while((size_t)(inchunk - data) < datasize) {
6451
0
    CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
6452
0
    out->allocsize = out->size; /*fix the allocsize again*/
6453
0
    inchunk = lodepng_chunk_next(inchunk, data + datasize);
6454
0
  }
6455
0
  return 0;
6456
0
}
6457
6458
0
static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) {
6459
  /*
6460
  It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19
6461
  are "RGB ". We do not perform any full parsing of the ICC profile here, other
6462
  than check those 4 bytes to grayscale profile. Other than that, validity of
6463
  the profile is not checked. This is needed only because the PNG specification
6464
  requires using a non-gray color model if there is an ICC profile with "RGB "
6465
  (sadly limiting compression opportunities if the input data is grayscale RGB
6466
  data), and requires using a gray color model if it is "GRAY".
6467
  */
6468
0
  if(size < 20) return 0;
6469
0
  return profile[16] == 'G' &&  profile[17] == 'R' &&  profile[18] == 'A' &&  profile[19] == 'Y';
6470
0
}
6471
6472
0
static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) {
6473
  /* See comment in isGrayICCProfile*/
6474
0
  if(size < 20) return 0;
6475
0
  return profile[16] == 'R' &&  profile[17] == 'G' &&  profile[18] == 'B' &&  profile[19] == ' ';
6476
0
}
6477
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6478
6479
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
6480
                        const unsigned char* image, unsigned w, unsigned h,
6481
0
                        LodePNGState* state) {
6482
0
  unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
6483
0
  size_t datasize = 0;
6484
0
  ucvector outv = ucvector_init(NULL, 0);
6485
0
  LodePNGInfo info;
6486
0
  const LodePNGInfo* info_png = &state->info_png;
6487
0
  LodePNGColorMode auto_color;
6488
6489
0
  lodepng_info_init(&info);
6490
0
  lodepng_color_mode_init(&auto_color);
6491
6492
  /*provide some proper output values if error will happen*/
6493
0
  *out = 0;
6494
0
  *outsize = 0;
6495
0
  state->error = 0;
6496
6497
  /*check input values validity*/
6498
0
  if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette)
6499
0
      && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) {
6500
    /*this error is returned even if auto_convert is enabled and thus encoder could
6501
    generate the palette by itself: while allowing this could be possible in theory,
6502
    it may complicate the code or edge cases, and always requiring to give a palette
6503
    when setting this color type is a simpler contract*/
6504
0
    state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
6505
0
    goto cleanup;
6506
0
  }
6507
0
  if(state->encoder.zlibsettings.btype > 2) {
6508
0
    state->error = 61; /*error: invalid btype*/
6509
0
    goto cleanup;
6510
0
  }
6511
0
  if(info_png->interlace_method > 1) {
6512
0
    state->error = 71; /*error: invalid interlace mode*/
6513
0
    goto cleanup;
6514
0
  }
6515
0
  state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth);
6516
0
  if(state->error) goto cleanup; /*error: invalid color type given*/
6517
0
  state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
6518
0
  if(state->error) goto cleanup; /*error: invalid color type given*/
6519
6520
  /* color convert and compute scanline filter types */
6521
0
  CERROR_TRY_RETURN(lodepng_info_copy(&info, &state->info_png));
6522
0
  if(state->encoder.auto_convert) {
6523
0
    LodePNGColorStats stats;
6524
0
    unsigned allow_convert = 1;
6525
0
    lodepng_color_stats_init(&stats);
6526
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6527
0
    if(info_png->iccp_defined &&
6528
0
        isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
6529
      /*the PNG specification does not allow to use palette with a GRAY ICC profile, even
6530
      if the palette has only gray colors, so disallow it.*/
6531
0
      stats.allow_palette = 0;
6532
0
    }
6533
0
    if(info_png->iccp_defined &&
6534
0
        isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
6535
      /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/
6536
0
      stats.allow_greyscale = 0;
6537
0
    }
6538
0
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
6539
0
    state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw);
6540
0
    if(state->error) goto cleanup;
6541
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6542
0
    if(info_png->background_defined) {
6543
      /*the background chunk's color must be taken into account as well*/
6544
0
      unsigned r = 0, g = 0, b = 0;
6545
0
      LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);
6546
0
      lodepng_convert_rgb(&r, &g, &b,
6547
0
          info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color);
6548
0
      state->error = lodepng_color_stats_add(&stats, r, g, b, 65535);
6549
0
      if(state->error) goto cleanup;
6550
0
    }
6551
0
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
6552
0
    state->error = auto_choose_color(&auto_color, &state->info_raw, &stats);
6553
0
    if(state->error) goto cleanup;
6554
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6555
0
    if(info_png->sbit_defined) {
6556
      /*if sbit is defined, due to strict requirements of which sbit values can be present for which color modes,
6557
      auto_convert can't be done in many cases. However, do support a few cases here.
6558
      TODO: more conversions may be possible, and it may also be possible to get a more appropriate color type out of
6559
            auto_choose_color if knowledge about sbit is used beforehand
6560
      */
6561
0
      unsigned sbit_max = LODEPNG_MAX(LODEPNG_MAX(LODEPNG_MAX(info_png->sbit_r, info_png->sbit_g),
6562
0
                           info_png->sbit_b), info_png->sbit_a);
6563
0
      unsigned equal = (!info_png->sbit_g || info_png->sbit_g == info_png->sbit_r)
6564
0
                    && (!info_png->sbit_b || info_png->sbit_b == info_png->sbit_r)
6565
0
                    && (!info_png->sbit_a || info_png->sbit_a == info_png->sbit_r);
6566
0
      allow_convert = 0;
6567
0
      if(info.color.colortype == LCT_PALETTE &&
6568
0
         auto_color.colortype == LCT_PALETTE) {
6569
        /* input and output are palette, and in this case it may happen that palette data is
6570
        expected to be copied from info_raw into the info_png */
6571
0
        allow_convert = 1;
6572
0
      }
6573
      /*going from 8-bit RGB to palette (or 16-bit as long as sbit_max <= 8) is possible
6574
      since both are 8-bit RGB for sBIT's purposes*/
6575
0
      if(info.color.colortype == LCT_RGB &&
6576
0
         auto_color.colortype == LCT_PALETTE && sbit_max <= 8) {
6577
0
        allow_convert = 1;
6578
0
      }
6579
      /*going from 8-bit RGBA to palette is also ok but only if sbit_a is exactly 8*/
6580
0
      if(info.color.colortype == LCT_RGBA && auto_color.colortype == LCT_PALETTE &&
6581
0
         info_png->sbit_a == 8 && sbit_max <= 8) {
6582
0
        allow_convert = 1;
6583
0
      }
6584
      /*going from 16-bit RGB(A) to 8-bit RGB(A) is ok if all sbit values are <= 8*/
6585
0
      if((info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA) && info.color.bitdepth == 16 &&
6586
0
         auto_color.colortype == info.color.colortype && auto_color.bitdepth == 8 &&
6587
0
         sbit_max <= 8) {
6588
0
        allow_convert = 1;
6589
0
      }
6590
      /*going to less channels is ok if all bit values are equal (all possible values in sbit,
6591
        as well as the chosen bitdepth of the result). Due to how auto_convert works,
6592
        we already know that auto_color.colortype has less than or equal amount of channels than
6593
        info.colortype. Palette is not used here. This conversion is not allowed if
6594
        info_png->sbit_r < auto_color.bitdepth, because specifically for alpha, non-presence of
6595
        an sbit value heavily implies that alpha's bit depth is equal to the PNG bit depth (rather
6596
        than the bit depths set in the r, g and b sbit values, by how the PNG specification describes
6597
        handling tRNS chunk case with sBIT), so be conservative here about ignoring user input.*/
6598
0
      if(info.color.colortype != LCT_PALETTE && auto_color.colortype != LCT_PALETTE &&
6599
0
         equal && info_png->sbit_r == auto_color.bitdepth) {
6600
0
        allow_convert = 1;
6601
0
      }
6602
0
    }
6603
0
#endif
6604
0
    if(state->encoder.force_palette) {
6605
0
      if(info.color.colortype != LCT_GREY && info.color.colortype != LCT_GREY_ALPHA &&
6606
0
         (auto_color.colortype == LCT_GREY || auto_color.colortype == LCT_GREY_ALPHA)) {
6607
        /*user speficially forced a PLTE palette, so cannot convert to grayscale types because
6608
        the PNG specification only allows writing a suggested palette in PLTE for truecolor types*/
6609
0
        allow_convert = 0;
6610
0
      }
6611
0
    }
6612
0
    if(allow_convert) {
6613
0
      lodepng_color_mode_copy(&info.color, &auto_color);
6614
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6615
      /*also convert the background chunk*/
6616
0
      if(info_png->background_defined) {
6617
0
        if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,
6618
0
            info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) {
6619
0
          state->error = 104;
6620
0
          goto cleanup;
6621
0
        }
6622
0
      }
6623
0
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
6624
0
    }
6625
0
  }
6626
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6627
0
  if(info_png->iccp_defined) {
6628
0
    unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
6629
0
    unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
6630
0
    unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;
6631
0
    if(!gray_icc && !rgb_icc) {
6632
0
      state->error = 100; /* Disallowed profile color type for PNG */
6633
0
      goto cleanup;
6634
0
    }
6635
0
    if(gray_icc != gray_png) {
6636
      /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa,
6637
      or in case of auto_convert, it wasn't possible to find appropriate model*/
6638
0
      state->error = state->encoder.auto_convert ? 102 : 101;
6639
0
      goto cleanup;
6640
0
    }
6641
0
  }
6642
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6643
0
  if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {
6644
0
    unsigned char* converted;
6645
0
    size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u;
6646
6647
0
    converted = (unsigned char*)lodepng_malloc(size);
6648
0
    if(!converted && size) state->error = 83; /*alloc fail*/
6649
0
    if(!state->error) {
6650
0
      state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
6651
0
    }
6652
0
    if(!state->error) {
6653
0
      state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
6654
0
    }
6655
0
    lodepng_free(converted);
6656
0
    if(state->error) goto cleanup;
6657
0
  } else {
6658
0
    state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
6659
0
    if(state->error) goto cleanup;
6660
0
  }
6661
6662
0
  /* output all PNG chunks */ {
6663
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6664
0
    size_t i;
6665
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6666
    /*write signature and chunks*/
6667
0
    state->error = writeSignature(&outv);
6668
0
    if(state->error) goto cleanup;
6669
    /*IHDR*/
6670
0
    state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
6671
0
    if(state->error) goto cleanup;
6672
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6673
    /*unknown chunks between IHDR and PLTE*/
6674
0
    if(info.unknown_chunks_data[0]) {
6675
0
      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
6676
0
      if(state->error) goto cleanup;
6677
0
    }
6678
    /*color profile chunks must come before PLTE */
6679
0
    if(info.cicp_defined) {
6680
0
      state->error = addChunk_cICP(&outv, &info);
6681
0
      if(state->error) goto cleanup;
6682
0
    }
6683
0
    if(info.mdcv_defined) {
6684
0
      state->error = addChunk_mDCV(&outv, &info);
6685
0
      if(state->error) goto cleanup;
6686
0
    }
6687
0
    if(info.clli_defined) {
6688
0
      state->error = addChunk_cLLI(&outv, &info);
6689
0
      if(state->error) goto cleanup;
6690
0
    }
6691
0
    if(info.iccp_defined) {
6692
0
      state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);
6693
0
      if(state->error) goto cleanup;
6694
0
    }
6695
0
    if(info.srgb_defined) {
6696
0
      state->error = addChunk_sRGB(&outv, &info);
6697
0
      if(state->error) goto cleanup;
6698
0
    }
6699
0
    if(info.gama_defined) {
6700
0
      state->error = addChunk_gAMA(&outv, &info);
6701
0
      if(state->error) goto cleanup;
6702
0
    }
6703
0
    if(info.chrm_defined) {
6704
0
      state->error = addChunk_cHRM(&outv, &info);
6705
0
      if(state->error) goto cleanup;
6706
0
    }
6707
0
    if(info_png->sbit_defined) {
6708
0
      state->error = addChunk_sBIT(&outv, &info);
6709
0
      if(state->error) goto cleanup;
6710
0
    }
6711
0
    if(info.exif_defined) {
6712
0
      state->error = addChunk_eXIf(&outv, &info);
6713
0
      if(state->error) goto cleanup;
6714
0
    }
6715
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6716
    /*PLTE*/
6717
0
    if(info.color.colortype == LCT_PALETTE) {
6718
0
      state->error = addChunk_PLTE(&outv, &info.color);
6719
0
      if(state->error) goto cleanup;
6720
0
    }
6721
0
    if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {
6722
      /*force_palette means: write suggested palette for truecolor in PLTE chunk*/
6723
0
      state->error = addChunk_PLTE(&outv, &info.color);
6724
0
      if(state->error) goto cleanup;
6725
0
    }
6726
    /*tRNS (this will only add if when necessary) */
6727
0
    state->error = addChunk_tRNS(&outv, &info.color);
6728
0
    if(state->error) goto cleanup;
6729
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6730
    /*bKGD (must come between PLTE and the IDAt chunks*/
6731
0
    if(info.background_defined) {
6732
0
      state->error = addChunk_bKGD(&outv, &info);
6733
0
      if(state->error) goto cleanup;
6734
0
    }
6735
    /*pHYs (must come before the IDAT chunks)*/
6736
0
    if(info.phys_defined) {
6737
0
      state->error = addChunk_pHYs(&outv, &info);
6738
0
      if(state->error) goto cleanup;
6739
0
    }
6740
6741
    /*unknown chunks between PLTE and IDAT*/
6742
0
    if(info.unknown_chunks_data[1]) {
6743
0
      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
6744
0
      if(state->error) goto cleanup;
6745
0
    }
6746
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6747
    /*IDAT (multiple IDAT chunks must be consecutive)*/
6748
0
    state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
6749
0
    if(state->error) goto cleanup;
6750
0
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6751
    /*tIME*/
6752
0
    if(info.time_defined) {
6753
0
      state->error = addChunk_tIME(&outv, &info.time);
6754
0
      if(state->error) goto cleanup;
6755
0
    }
6756
    /*tEXt and/or zTXt*/
6757
0
    for(i = 0; i != info.text_num; ++i) {
6758
0
      if(lodepng_strlen(info.text_keys[i]) > 79) {
6759
0
        state->error = 66; /*text chunk too large*/
6760
0
        goto cleanup;
6761
0
      }
6762
0
      if(lodepng_strlen(info.text_keys[i]) < 1) {
6763
0
        state->error = 67; /*text chunk too small*/
6764
0
        goto cleanup;
6765
0
      }
6766
0
      if(state->encoder.text_compression) {
6767
0
        state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
6768
0
        if(state->error) goto cleanup;
6769
0
      } else {
6770
0
        state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
6771
0
        if(state->error) goto cleanup;
6772
0
      }
6773
0
    }
6774
    /*LodePNG version id in text chunk*/
6775
0
    if(state->encoder.add_id) {
6776
0
      unsigned already_added_id_text = 0;
6777
0
      for(i = 0; i != info.text_num; ++i) {
6778
0
        const char* k = info.text_keys[i];
6779
        /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */
6780
0
        if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' &&
6781
0
           k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') {
6782
0
          already_added_id_text = 1;
6783
0
          break;
6784
0
        }
6785
0
      }
6786
0
      if(already_added_id_text == 0) {
6787
0
        state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
6788
0
        if(state->error) goto cleanup;
6789
0
      }
6790
0
    }
6791
    /*iTXt*/
6792
0
    for(i = 0; i != info.itext_num; ++i) {
6793
0
      if(lodepng_strlen(info.itext_keys[i]) > 79) {
6794
0
        state->error = 66; /*text chunk too large*/
6795
0
        goto cleanup;
6796
0
      }
6797
0
      if(lodepng_strlen(info.itext_keys[i]) < 1) {
6798
0
        state->error = 67; /*text chunk too small*/
6799
0
        goto cleanup;
6800
0
      }
6801
0
      state->error = addChunk_iTXt(
6802
0
          &outv, state->encoder.text_compression,
6803
0
          info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
6804
0
          &state->encoder.zlibsettings);
6805
0
      if(state->error) goto cleanup;
6806
0
    }
6807
6808
    /*unknown chunks between IDAT and IEND*/
6809
0
    if(info.unknown_chunks_data[2]) {
6810
0
      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
6811
0
      if(state->error) goto cleanup;
6812
0
    }
6813
0
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6814
0
    state->error = addChunk_IEND(&outv);
6815
0
    if(state->error) goto cleanup;
6816
0
  }
6817
6818
0
cleanup:
6819
0
  lodepng_info_cleanup(&info);
6820
0
  lodepng_free(data);
6821
0
  lodepng_color_mode_cleanup(&auto_color);
6822
6823
  /*instead of cleaning the vector up, give it to the output*/
6824
0
  *out = outv.data;
6825
0
  *outsize = outv.size;
6826
6827
0
  return state->error;
6828
0
}
6829
6830
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
6831
0
                               unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
6832
0
  unsigned error;
6833
0
  LodePNGState state;
6834
0
  lodepng_state_init(&state);
6835
0
  state.info_raw.colortype = colortype;
6836
0
  state.info_raw.bitdepth = bitdepth;
6837
0
  state.info_png.color.colortype = colortype;
6838
0
  state.info_png.color.bitdepth = bitdepth;
6839
0
  lodepng_encode(out, outsize, image, w, h, &state);
6840
0
  error = state.error;
6841
0
  lodepng_state_cleanup(&state);
6842
0
  return error;
6843
0
}
6844
6845
0
unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
6846
0
  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
6847
0
}
6848
6849
0
unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
6850
0
  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
6851
0
}
6852
6853
#ifdef LODEPNG_COMPILE_DISK
6854
unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
6855
0
                             LodePNGColorType colortype, unsigned bitdepth) {
6856
0
  unsigned char* buffer;
6857
0
  size_t buffersize;
6858
0
  unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
6859
0
  if(!error) error = lodepng_save_file(buffer, buffersize, filename);
6860
0
  lodepng_free(buffer);
6861
0
  return error;
6862
0
}
6863
6864
0
unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
6865
0
  return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
6866
0
}
6867
6868
0
unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
6869
0
  return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
6870
0
}
6871
#endif /*LODEPNG_COMPILE_DISK*/
6872
6873
4.88k
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) {
6874
4.88k
  lodepng_compress_settings_init(&settings->zlibsettings);
6875
4.88k
  settings->filter_palette_zero = 1;
6876
4.88k
  settings->filter_strategy = LFS_MINSUM;
6877
4.88k
  settings->auto_convert = 1;
6878
4.88k
  settings->force_palette = 0;
6879
4.88k
  settings->predefined_filters = 0;
6880
4.88k
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
6881
4.88k
  settings->add_id = 0;
6882
4.88k
  settings->text_compression = 1;
6883
4.88k
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
6884
4.88k
}
6885
6886
#endif /*LODEPNG_COMPILE_ENCODER*/
6887
#endif /*LODEPNG_COMPILE_PNG*/
6888
6889
#ifdef LODEPNG_COMPILE_ERROR_TEXT
6890
/*
6891
This returns the description of a numerical error code in English. This is also
6892
the documentation of all the error codes.
6893
*/
6894
0
const char* lodepng_error_text(unsigned code) {
6895
0
  switch(code) {
6896
0
    case 0: return "no error, everything went ok";
6897
0
    case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
6898
0
    case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
6899
0
    case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
6900
0
    case 13: return "problem while processing dynamic deflate block";
6901
0
    case 14: return "problem while processing dynamic deflate block";
6902
0
    case 15: return "problem while processing dynamic deflate block";
6903
    /*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/
6904
0
    case 16: return "invalid code while processing dynamic deflate block";
6905
0
    case 17: return "end of out buffer memory reached while inflating";
6906
0
    case 18: return "invalid distance code while inflating";
6907
0
    case 19: return "end of out buffer memory reached while inflating";
6908
0
    case 20: return "invalid deflate block BTYPE encountered while decoding";
6909
0
    case 21: return "NLEN is not ones complement of LEN in a deflate block";
6910
6911
    /*end of out buffer memory reached while inflating:
6912
    This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
6913
    all the pixels of the image, given the color depth and image dimensions. Something that doesn't
6914
    happen in a normal, well encoded, PNG image.*/
6915
0
    case 22: return "end of out buffer memory reached while inflating";
6916
0
    case 23: return "end of in buffer memory reached while inflating";
6917
0
    case 24: return "invalid FCHECK in zlib header";
6918
0
    case 25: return "invalid compression method in zlib header";
6919
0
    case 26: return "FDICT encountered in zlib header while it's not used for PNG";
6920
0
    case 27: return "PNG file is smaller than a PNG header";
6921
    /*Checks the magic file header, the first 8 bytes of the PNG file*/
6922
0
    case 28: return "incorrect PNG signature, it's no PNG or corrupted";
6923
0
    case 29: return "first chunk is not the header chunk";
6924
0
    case 30: return "chunk length too large, chunk broken off at end of file";
6925
0
    case 31: return "illegal PNG color type or bpp";
6926
0
    case 32: return "illegal PNG compression method";
6927
0
    case 33: return "illegal PNG filter method";
6928
0
    case 34: return "illegal PNG interlace method";
6929
0
    case 35: return "chunk length of a chunk is too large or the chunk too small";
6930
0
    case 36: return "illegal PNG filter type encountered";
6931
0
    case 37: return "illegal bit depth for this color type given";
6932
0
    case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/
6933
0
    case 39: return "tRNS chunk before PLTE or has more entries than palette size";
6934
0
    case 40: return "tRNS chunk has wrong size for grayscale image";
6935
0
    case 41: return "tRNS chunk has wrong size for RGB image";
6936
0
    case 42: return "tRNS chunk appeared while it was not allowed for this color type";
6937
0
    case 43: return "bKGD chunk has wrong size for palette image";
6938
0
    case 44: return "bKGD chunk has wrong size for grayscale image";
6939
0
    case 45: return "bKGD chunk has wrong size for RGB image";
6940
0
    case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
6941
0
    case 49: return "jumped past memory while generating dynamic huffman tree";
6942
0
    case 50: return "jumped past memory while generating dynamic huffman tree";
6943
0
    case 51: return "jumped past memory while inflating huffman block";
6944
0
    case 52: return "jumped past memory while inflating";
6945
0
    case 53: return "size of zlib data too small";
6946
0
    case 54: return "repeat symbol in tree while there was no value symbol yet";
6947
    /*jumped past tree while generating huffman tree, this could be when the
6948
    tree will have more leaves than symbols after generating it out of the
6949
    given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
6950
0
    case 55: return "jumped past tree while generating huffman tree";
6951
0
    case 56: return "given output image colortype or bitdepth not supported for color conversion";
6952
0
    case 57: return "invalid CRC encountered (checking CRC can be disabled)";
6953
0
    case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
6954
0
    case 59: return "requested color conversion not supported";
6955
0
    case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
6956
0
    case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
6957
    /*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/
6958
0
    case 62: return "conversion from color to grayscale not supported";
6959
    /*(2^31-1)*/
6960
0
    case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";
6961
    /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
6962
0
    case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
6963
0
    case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
6964
0
    case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
6965
0
    case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
6966
0
    case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
6967
0
    case 71: return "invalid interlace mode given to encoder (must be 0 or 1)";
6968
0
    case 72: return "while decoding, invalid compression method encountered in zTXt, iTXt or iCCP chunk (it must be 0)";
6969
0
    case 73: return "invalid tIME chunk size";
6970
0
    case 74: return "invalid pHYs chunk size";
6971
    /*length could be wrong, or data chopped off*/
6972
0
    case 75: return "no null termination char found while decoding text chunk";
6973
0
    case 76: return "iTXt chunk too short to contain required bytes";
6974
0
    case 77: return "integer overflow in buffer size";
6975
0
    case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
6976
0
    case 79: return "failed to open file for writing";
6977
0
    case 80: return "tried creating a tree of 0 symbols";
6978
0
    case 81: return "lazy matching at pos 0 is impossible";
6979
0
    case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds";
6980
0
    case 83: return "memory allocation failed";
6981
0
    case 84: return "given image too small to contain all pixels to be encoded";
6982
0
    case 86: return "impossible offset in lz77 encoding (internal bug)";
6983
0
    case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
6984
0
    case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
6985
0
    case 89: return "text chunk keyword too short or long: must have size 1-79";
6986
    /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
6987
0
    case 90: return "windowsize must be a power of two";
6988
0
    case 91: return "invalid decompressed idat size";
6989
0
    case 92: return "integer overflow due to too many pixels";
6990
0
    case 93: return "zero width or height is invalid";
6991
0
    case 94: return "header chunk must have a size of 13 bytes";
6992
0
    case 95: return "integer overflow with combined idat chunk size";
6993
0
    case 96: return "invalid gAMA chunk size";
6994
0
    case 97: return "invalid cHRM chunk size";
6995
0
    case 98: return "invalid sRGB chunk size";
6996
0
    case 99: return "invalid sRGB rendering intent";
6997
0
    case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";
6998
0
    case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";
6999
0
    case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";
7000
0
    case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";
7001
0
    case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)";
7002
0
    case 105: return "integer overflow of bitsize";
7003
0
    case 106: return "PNG file must have PLTE chunk if color type is palette";
7004
0
    case 107: return "color convert from palette mode requested without setting the palette data in it";
7005
0
    case 108: return "tried to add more than 256 values to a palette";
7006
    /*this limit can be configured in LodePNGDecompressSettings*/
7007
0
    case 109: return "tried to decompress zlib or deflate data larger than desired max_output_size";
7008
0
    case 110: return "custom zlib or inflate decompression failed";
7009
0
    case 111: return "custom zlib or deflate compression failed";
7010
    /*max text size limit can be configured in LodePNGDecoderSettings. This error prevents
7011
    unreasonable memory consumption when decoding due to impossibly large text sizes.*/
7012
0
    case 112: return "compressed text unreasonably large";
7013
    /*max ICC size limit can be configured in LodePNGDecoderSettings. This error prevents
7014
    unreasonable memory consumption when decoding due to impossibly large ICC profile*/
7015
0
    case 113: return "ICC profile unreasonably large";
7016
0
    case 114: return "sBIT chunk has wrong size for the color type of the image";
7017
0
    case 115: return "sBIT value out of range";
7018
0
    case 116: return "cICP value out of range";
7019
0
    case 117: return "invalid cICP chunk size";
7020
0
    case 118: return "mDCV value out of range";
7021
0
    case 119: return "invalid mDCV chunk size";
7022
0
    case 120: return "invalid cLLI chunk size";
7023
0
    case 121: return "invalid chunk type name: may only contain [a-zA-Z]";
7024
0
    case 122: return "invalid chunk type name: third character must be uppercase";
7025
0
    case 123: return "invalid ICC profile size";
7026
0
  }
7027
0
  return "unknown error code";
7028
0
}
7029
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
7030
7031
/* ////////////////////////////////////////////////////////////////////////// */
7032
/* ////////////////////////////////////////////////////////////////////////// */
7033
/* // C++ Wrapper                                                          // */
7034
/* ////////////////////////////////////////////////////////////////////////// */
7035
/* ////////////////////////////////////////////////////////////////////////// */
7036
7037
#ifdef LODEPNG_COMPILE_CPP
7038
namespace lodepng {
7039
7040
#ifdef LODEPNG_COMPILE_DISK
7041
/* Resizes the vector to the file size and reads the file into it. Returns error code.*/
7042
0
static unsigned load_file_(std::vector<unsigned char>& buffer, FILE* file) {
7043
0
  long size = lodepng_filesize(file);
7044
0
  if(size < 0) return 78;
7045
0
  buffer.resize((size_t)size);
7046
0
  if(size == 0) return 0; /*ok*/
7047
0
  if(fread(&buffer[0], 1, buffer.size(), file) != buffer.size()) return 78;
7048
0
  return 0; /*ok*/
7049
0
}
7050
7051
0
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename) {
7052
0
  unsigned error;
7053
0
  FILE* file = fopen(filename.c_str(), "rb");
7054
0
  if(!file) return 78;
7055
0
  error = load_file_(buffer, file);
7056
0
  fclose(file);
7057
0
  return error;
7058
0
}
7059
7060
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
7061
0
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename) {
7062
0
  return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
7063
0
}
7064
#endif /* LODEPNG_COMPILE_DISK */
7065
7066
#ifdef LODEPNG_COMPILE_ZLIB
7067
#ifdef LODEPNG_COMPILE_DECODER
7068
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
7069
0
                    const LodePNGDecompressSettings& settings) {
7070
0
  unsigned char* buffer = 0;
7071
0
  size_t buffersize = 0;
7072
0
  unsigned error = zlib_decompress(&buffer, &buffersize, 0, in, insize, &settings);
7073
0
  if(buffer) {
7074
0
    out.insert(out.end(), buffer, &buffer[buffersize]);
7075
0
    lodepng_free(buffer);
7076
0
  }
7077
0
  return error;
7078
0
}
7079
7080
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
7081
0
                    const LodePNGDecompressSettings& settings) {
7082
0
  return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
7083
0
}
7084
#endif /* LODEPNG_COMPILE_DECODER */
7085
7086
#ifdef LODEPNG_COMPILE_ENCODER
7087
unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
7088
0
                  const LodePNGCompressSettings& settings) {
7089
0
  unsigned char* buffer = 0;
7090
0
  size_t buffersize = 0;
7091
0
  unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
7092
0
  if(buffer) {
7093
0
    out.insert(out.end(), buffer, &buffer[buffersize]);
7094
0
    lodepng_free(buffer);
7095
0
  }
7096
0
  return error;
7097
0
}
7098
7099
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
7100
0
                  const LodePNGCompressSettings& settings) {
7101
0
  return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
7102
0
}
7103
#endif /* LODEPNG_COMPILE_ENCODER */
7104
#endif /* LODEPNG_COMPILE_ZLIB */
7105
7106
7107
#ifdef LODEPNG_COMPILE_PNG
7108
7109
4.88k
State::State() {
7110
4.88k
  lodepng_state_init(this);
7111
4.88k
}
7112
7113
0
State::State(const State& other) {
7114
0
  lodepng_state_init(this);
7115
0
  lodepng_state_copy(this, &other);
7116
0
}
7117
7118
4.88k
State::~State() {
7119
4.88k
  lodepng_state_cleanup(this);
7120
4.88k
}
7121
7122
0
State& State::operator=(const State& other) {
7123
0
  lodepng_state_copy(this, &other);
7124
0
  return *this;
7125
0
}
7126
7127
#ifdef LODEPNG_COMPILE_DECODER
7128
7129
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
7130
0
                size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
7131
0
  unsigned char* buffer = 0;
7132
0
  unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
7133
0
  if(buffer && !error) {
7134
0
    State state;
7135
0
    state.info_raw.colortype = colortype;
7136
0
    state.info_raw.bitdepth = bitdepth;
7137
0
    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
7138
0
    out.insert(out.end(), buffer, &buffer[buffersize]);
7139
0
  }
7140
0
  lodepng_free(buffer);
7141
0
  return error;
7142
0
}
7143
7144
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
7145
0
                const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth) {
7146
0
  return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
7147
0
}
7148
7149
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
7150
                State& state,
7151
8.32k
                const unsigned char* in, size_t insize) {
7152
8.32k
  unsigned char* buffer = NULL;
7153
8.32k
  unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
7154
8.32k
  if(buffer && !error) {
7155
4.83k
    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
7156
4.83k
    out.insert(out.end(), buffer, &buffer[buffersize]);
7157
4.83k
  }
7158
8.32k
  lodepng_free(buffer);
7159
8.32k
  return error;
7160
8.32k
}
7161
7162
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
7163
                State& state,
7164
0
                const std::vector<unsigned char>& in) {
7165
0
  return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
7166
0
}
7167
7168
#ifdef LODEPNG_COMPILE_DISK
7169
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
7170
0
                LodePNGColorType colortype, unsigned bitdepth) {
7171
0
  std::vector<unsigned char> buffer;
7172
  /* safe output values in case error happens */
7173
0
  w = h = 0;
7174
0
  unsigned error = load_file(buffer, filename);
7175
0
  if(error) return error;
7176
0
  return decode(out, w, h, buffer, colortype, bitdepth);
7177
0
}
7178
#endif /* LODEPNG_COMPILE_DECODER */
7179
#endif /* LODEPNG_COMPILE_DISK */
7180
7181
#ifdef LODEPNG_COMPILE_ENCODER
7182
unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
7183
0
                LodePNGColorType colortype, unsigned bitdepth) {
7184
0
  unsigned char* buffer;
7185
0
  size_t buffersize;
7186
0
  unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
7187
0
  if(buffer) {
7188
0
    out.insert(out.end(), buffer, &buffer[buffersize]);
7189
0
    lodepng_free(buffer);
7190
0
  }
7191
0
  return error;
7192
0
}
7193
7194
unsigned encode(std::vector<unsigned char>& out,
7195
                const std::vector<unsigned char>& in, unsigned w, unsigned h,
7196
0
                LodePNGColorType colortype, unsigned bitdepth) {
7197
0
  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
7198
0
  return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
7199
0
}
7200
7201
unsigned encode(std::vector<unsigned char>& out,
7202
                const unsigned char* in, unsigned w, unsigned h,
7203
0
                State& state) {
7204
0
  unsigned char* buffer;
7205
0
  size_t buffersize;
7206
0
  unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
7207
0
  if(buffer) {
7208
0
    out.insert(out.end(), buffer, &buffer[buffersize]);
7209
0
    lodepng_free(buffer);
7210
0
  }
7211
0
  return error;
7212
0
}
7213
7214
unsigned encode(std::vector<unsigned char>& out,
7215
                const std::vector<unsigned char>& in, unsigned w, unsigned h,
7216
0
                State& state) {
7217
0
  if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
7218
0
  return encode(out, in.empty() ? 0 : &in[0], w, h, state);
7219
0
}
7220
7221
#ifdef LODEPNG_COMPILE_DISK
7222
unsigned encode(const std::string& filename,
7223
                const unsigned char* in, unsigned w, unsigned h,
7224
0
                LodePNGColorType colortype, unsigned bitdepth) {
7225
0
  std::vector<unsigned char> buffer;
7226
0
  unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
7227
0
  if(!error) error = save_file(buffer, filename);
7228
0
  return error;
7229
0
}
7230
7231
unsigned encode(const std::string& filename,
7232
                const std::vector<unsigned char>& in, unsigned w, unsigned h,
7233
0
                LodePNGColorType colortype, unsigned bitdepth) {
7234
0
  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
7235
0
  return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
7236
0
}
7237
#endif /* LODEPNG_COMPILE_DISK */
7238
#endif /* LODEPNG_COMPILE_ENCODER */
7239
#endif /* LODEPNG_COMPILE_PNG */
7240
} /* namespace lodepng */
7241
#endif /*LODEPNG_COMPILE_CPP*/