~lgb/x-emulators/dev

« back to all changes in this revision

Viewing changes to xemu/lodepng.c

  • Committer: GitHub
  • Author(s): LGB
  • Date: 2020-06-09 11:33:47 UTC
  • mfrom: (265.1.101)
  • Revision ID: git-v1:527c2b021966f6f9f2444c23d6402c141d1c19d2
Merge pull request #116 from lgblgblgb/dev

Merge dev stage into master

Show diffs side-by-side

added added

removed removed

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