BARE2D
PicoPNG.cpp
Go to the documentation of this file.
1 #include <vector>
2 
3 using namespace std;
4 
5 namespace BARE2D {
6 
7  /*
8  decodePNG: The picoPNG function, decodes a PNG file buffer in memory, into a raw pixel buffer.
9  out_image: output parameter, this will contain the raw pixels after decoding.
10  By default the output is 32-bit RGBA color.
11  The std::vector is automatically resized to the correct size.
12  image_width: output_parameter, this will contain the width of the image in pixels.
13  image_height: output_parameter, this will contain the height of the image in pixels.
14  in_png: pointer to the buffer of the PNG file in memory. To get it from a file on
15  disk, load it and store it in a memory buffer yourself first.
16  in_size: size of the input PNG file in bytes.
17  convert_to_rgba32: optional parameter, true by default.
18  Set to true to get the output in RGBA 32-bit (8 bit per channel) color format
19  no matter what color type the original PNG image had. This gives predictable,
20  useable data from any random input PNG.
21  Set to false to do no color conversion at all. The result then has the same data
22  type as the PNG image, which can range from 1 bit to 64 bits per pixel.
23  Information about the color type or palette colors are not provided. You need
24  to know this information yourself to be able to use the data so this only
25  works for trusted PNG files. Use LodePNG instead of picoPNG if you need this information.
26  return: 0 if success, not 0 if some error occured.
27  */
28  int decodePNG(std::vector<unsigned char>& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, std::size_t in_size, bool convert_to_rgba32) {
29  // picoPNG version 20101224
30  // Copyright (c) 2005-2010 Lode Vandevenne
31  //
32  // This software is provided 'as-is', without any express or implied
33  // warranty. In no event will the authors be held liable for any damages
34  // arising from the use of this software.
35  //
36  // Permission is granted to anyone to use this software for any purpose,
37  // including commercial applications, and to alter it and redistribute it
38  // freely, subject to the following restrictions:
39  //
40  // 1. The origin of this software must not be misrepresented; you must not
41  // claim that you wrote the original software. If you use this software
42  // in a product, an acknowledgment in the product documentation would be
43  // appreciated but is not required.
44  // 2. Altered source versions must be plainly marked as such, and must not be
45  // misrepresented as being the original software.
46  // 3. This notice may not be removed or altered from any source distribution.
47 
48  // picoPNG is a PNG decoder in one C++ function of around 500 lines. Use picoPNG for
49  // programs that need only 1 .cpp file. Since it's a single function, it's very limited,
50  // it can convert a PNG to raw pixel data either converted to 32-bit RGBA color or
51  // with no color conversion at all. For anything more complex, another tiny library
52  // is available: LodePNG (lodepng.c(pp)), which is a single source and header file.
53  // Apologies for the compact code style, it's to make this tiny.
54 
55  static const unsigned long LENBASE[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 };
56  static const unsigned long LENEXTRA[29] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
57  static const unsigned long DISTBASE[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
58  static const unsigned long DISTEXTRA[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
59  static const unsigned long CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; //code length code lengths
60  struct Zlib { //nested functions for zlib decompression
61  static unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) {
62  unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1;
63  bitp++;
64  return result;
65  }
66  static unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits) {
67  unsigned long result = 0;
68  for (size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i;
69  return result;
70  }
71  struct HuffmanTree {
72  int makeFromLengths(const std::vector<unsigned long>& bitlen, unsigned long maxbitlen) {
73  //make tree given the lengths
74  unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0;
75  std::vector<unsigned long> tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0);
76  for (unsigned long bits = 0; bits < numcodes; bits++) blcount[bitlen[bits]]++; //count number of instances of each code length
77  for (unsigned long bits = 1; bits <= maxbitlen; bits++) nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1;
78  for (unsigned long n = 0; n < numcodes; n++) if (bitlen[n] != 0) tree1d[n] = nextcode[bitlen[n]]++; //generate all the codes
79  tree2d.clear();
80  tree2d.resize(numcodes * 2, 32767); //32767 here means the tree2d isn't filled there yet
81  for (unsigned long n = 0; n < numcodes; n++) //the codes
82  for (unsigned long i = 0; i < bitlen[n]; i++) { //the bits for this code
83  unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1;
84  if (treepos > numcodes - 2) return 55;
85  if (tree2d[2 * treepos + bit] == 32767) { //not yet filled in
86  if (i + 1 == bitlen[n]) {
87  tree2d[2 * treepos + bit] = n; //last bit
88  treepos = 0;
89  } else {
90  tree2d[2 * treepos + bit] = ++nodefilled + numcodes; //addresses are encoded as values > numcodes
91  treepos = nodefilled;
92  }
93  } else treepos = tree2d[2 * treepos + bit] - numcodes; //subtract numcodes from address to get address value
94  }
95  return 0;
96  }
97  int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const {
98  //Decodes a symbol from the tree
99  unsigned long numcodes = (unsigned long)tree2d.size() / 2;
100  if (treepos >= numcodes) return 11; //error: you appeared outside the codetree
101  result = tree2d[2 * treepos + bit];
102  decoded = (result < numcodes);
103  treepos = decoded ? 0 : result - numcodes;
104  return 0;
105  }
106  std::vector<unsigned long> tree2d; //2D representation of a huffman tree: The one dimension is "0" or "1", the other contains all nodes and leaves of the tree.
107  };
108  struct Inflator {
109  int error;
110  void inflate(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, size_t inpos = 0) {
111  size_t bp = 0, pos = 0; //bit pointer and byte pointer
112  error = 0;
113  unsigned long BFINAL = 0;
114  while (!BFINAL && !error) {
115  if (bp >> 3 >= in.size()) {
116  error = 52; //error, bit pointer will jump past memory
117  return;
118  }
119  BFINAL = readBitFromStream(bp, &in[inpos]);
120  unsigned long BTYPE = readBitFromStream(bp, &in[inpos]);
121  BTYPE += 2 * readBitFromStream(bp, &in[inpos]);
122  if (BTYPE == 3) {
123  error = 20; //error: invalid BTYPE
124  return;
125  } else if (BTYPE == 0) inflateNoCompression(out, &in[inpos], bp, pos, in.size());
126  else inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE);
127  }
128  if (!error) out.resize(pos); //Only now we know the true size of out, resize it to that
129  }
130  void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) { //get the tree of a deflated block with fixed tree
131  std::vector<unsigned long> bitlen(288, 8), bitlenD(32, 5);;
132  for (size_t i = 144; i <= 255; i++) bitlen[i] = 9;
133  for (size_t i = 256; i <= 279; i++) bitlen[i] = 7;
134  tree.makeFromLengths(bitlen, 15);
135  treeD.makeFromLengths(bitlenD, 15);
136  }
137  HuffmanTree codetree, codetreeD, codelengthcodetree; //the code tree for Huffman codes, dist codes, and code length codes
138  unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& codetree, size_t inlength) {
139  //decode a single symbol from given list of bits with given code tree. return value is the symbol
140  bool decoded;
141  unsigned long ct;
142  for (size_t treepos = 0;;) {
143  if ((bp & 0x07) == 0 && (bp >> 3) > inlength) {
144  error = 10; //error: end reached without endcode
145  return 0;
146  }
147  error = codetree.decode(decoded, ct, treepos, readBitFromStream(bp, in));
148  if (error) return 0; //stop, an error happened
149  if (decoded) return ct;
150  }
151  }
152  void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD, const unsigned char* in, size_t& bp, size_t inlength) {
153  //get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree
154  std::vector<unsigned long> bitlen(288, 0), bitlenD(32, 0);
155  if (bp >> 3 >= inlength - 2) {
156  error = 49; //the bit pointer is or will go past the memory
157  return;
158  }
159  size_t HLIT = readBitsFromStream(bp, in, 5) + 257; //number of literal/length codes + 257
160  size_t HDIST = readBitsFromStream(bp, in, 5) + 1; //number of dist codes + 1
161  size_t HCLEN = readBitsFromStream(bp, in, 4) + 4; //number of code length codes + 4
162  std::vector<unsigned long> codelengthcode(19); //lengths of tree to decode the lengths of the dynamic tree
163  for (size_t i = 0; i < 19; i++) codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0;
164  error = codelengthcodetree.makeFromLengths(codelengthcode, 7);
165  if (error) return;
166  size_t i = 0, replength;
167  while (i < HLIT + HDIST) {
168  unsigned long code = huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength);
169  if (error) return;
170  if (code <= 15) {
171  if (i < HLIT) bitlen[i++] = code; //a length code
172  else bitlenD[i++ - HLIT] = code;
173  } else if (code == 16) { //repeat previous
174  if (bp >> 3 >= inlength) {
175  error = 50; //error, bit pointer jumps past memory
176  return;
177  }
178  replength = 3 + readBitsFromStream(bp, in, 2);
179  unsigned long value; //set value to the previous code
180  if ((i - 1) < HLIT) value = bitlen[i - 1];
181  else value = bitlenD[i - HLIT - 1];
182  for (size_t n = 0; n < replength; n++) { //repeat this value in the next lengths
183  if (i >= HLIT + HDIST) {
184  error = 13; //error: i is larger than the amount of codes
185  return;
186  }
187  if (i < HLIT) bitlen[i++] = value;
188  else bitlenD[i++ - HLIT] = value;
189  }
190  } else if (code == 17) { //repeat "0" 3-10 times
191  if (bp >> 3 >= inlength) {
192  error = 50; //error, bit pointer jumps past memory
193  return;
194  }
195  replength = 3 + readBitsFromStream(bp, in, 3);
196  for (size_t n = 0; n < replength; n++) { //repeat this value in the next lengths
197  if (i >= HLIT + HDIST) {
198  error = 14; //error: i is larger than the amount of codes
199  return;
200  }
201  if (i < HLIT) bitlen[i++] = 0;
202  else bitlenD[i++ - HLIT] = 0;
203  }
204  } else if (code == 18) { //repeat "0" 11-138 times
205  if (bp >> 3 >= inlength) {
206  error = 50; //error, bit pointer jumps past memory
207  return;
208  }
209  replength = 11 + readBitsFromStream(bp, in, 7);
210  for (size_t n = 0; n < replength; n++) { //repeat this value in the next lengths
211  if (i >= HLIT + HDIST) {
212  error = 15; //error: i is larger than the amount of codes
213  return;
214  }
215  if (i < HLIT) bitlen[i++] = 0;
216  else bitlenD[i++ - HLIT] = 0;
217  }
218  } else {
219  error = 16; //error: somehow an unexisting code appeared. This can never happen.
220  return;
221  }
222  }
223  if (bitlen[256] == 0) {
224  error = 64; //the length of the end code 256 must be larger than 0
225  return;
226  }
227  error = tree.makeFromLengths(bitlen, 15);
228  if (error) return; //now we've finally got HLIT and HDIST, so generate the code trees, and the function is done
229  error = treeD.makeFromLengths(bitlenD, 15);
230  if (error) return;
231  }
232  void inflateHuffmanBlock(std::vector<unsigned char>& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype) {
233  if (btype == 1) {
234  generateFixedTrees(codetree, codetreeD);
235  } else if (btype == 2) {
236  getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength);
237  if (error) return;
238  }
239  for (;;) {
240  unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength);
241  if (error) return;
242  if (code == 256) return; //end code
243  else if (code <= 255) { //literal symbol
244  if (pos >= out.size()) out.resize((pos + 1) * 2); //reserve more room
245  out[pos++] = (unsigned char)(code);
246  } else if (code >= 257 && code <= 285) { //length code
247  size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257];
248  if ((bp >> 3) >= inlength) {
249  error = 51; //error, bit pointer will jump past memory
250  return;
251  }
252  length += readBitsFromStream(bp, in, numextrabits);
253  unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength);
254  if (error) return;
255  if (codeD > 29) {
256  error = 18; //error: invalid dist code (30-31 are never used)
257  return;
258  }
259  unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD];
260  if ((bp >> 3) >= inlength) {
261  error = 51; //error, bit pointer will jump past memory
262  return;
263  }
264  dist += readBitsFromStream(bp, in, numextrabitsD);
265  size_t start = pos, back = start - dist; //backwards
266  if (pos + length >= out.size()) out.resize((pos + length) * 2); //reserve more room
267  for (size_t i = 0; i < length; i++) {
268  out[pos++] = out[back++];
269  if (back >= start) back = start - dist;
270  }
271  }
272  }
273  }
274  void inflateNoCompression(std::vector<unsigned char>& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength) {
275  while ((bp & 0x7) != 0) bp++; //go to first boundary of byte
276  size_t p = bp / 8;
277  if (p >= inlength - 4) {
278  error = 52; //error, bit pointer will jump past memory
279  return;
280  }
281  unsigned long LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3];
282  p += 4;
283  if (LEN + NLEN != 65535) {
284  error = 21; //error: NLEN is not one's complement of LEN
285  return;
286  }
287  if (pos + LEN >= out.size()) out.resize(pos + LEN);
288  if (p + LEN > inlength) {
289  error = 23; //error: reading outside of in buffer
290  return;
291  }
292  for (unsigned long n = 0; n < LEN; n++) out[pos++] = in[p++]; //read LEN bytes of literal data
293  bp = p * 8;
294  }
295  };
296  int decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in) { //returns error value
297  Inflator inflator;
298  if (in.size() < 2) {
299  return 53; //error, size of zlib data too small
300  }
301  if ((in[0] * 256 + in[1]) % 31 != 0) {
302  return 24; //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way
303  }
304  unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1;
305  if (CM != 8 || CINFO > 7) {
306  return 25; //error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec
307  }
308  if (FDICT != 0) {
309  return 26; //error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary."
310  }
311  inflator.inflate(out, in, 2);
312  return inflator.error; //note: adler32 checksum was skipped and ignored
313  }
314  };
315  struct PNG { //nested functions for PNG decoding
316  struct Info {
317  unsigned long width, height, colorType, bitDepth, compressionMethod, filterMethod, interlaceMethod, key_r, key_g, key_b;
318  bool key_defined; //is a transparent color key given?
319  std::vector<unsigned char> palette;
320  } info;
321  int error;
322  void decode(std::vector<unsigned char>& out, const unsigned char* in, size_t size, bool convert_to_rgba32) {
323  error = 0;
324  if (size == 0 || in == 0) {
325  error = 48; //the given data is empty
326  return;
327  }
328  readPngHeader(&in[0], size);
329  if (error) return;
330  size_t pos = 33; //first byte of the first chunk after the header
331  std::vector<unsigned char> idat; //the data from idat chunks
332  bool IEND = false;
333  info.key_defined = false;
334  while (!IEND) { //loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer
335  if (pos + 8 >= size) {
336  error = 30; //error: size of the in buffer too small to contain next chunk
337  return;
338  }
339  size_t chunkLength = read32bitInt(&in[pos]);
340  pos += 4;
341  if (chunkLength > 2147483647) {
342  error = 63;
343  return;
344  }
345  if (pos + chunkLength >= size) {
346  error = 35; //error: size of the in buffer too small to contain next chunk
347  return;
348  }
349  if (in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') { //IDAT chunk, containing compressed image data
350  idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]);
351  pos += (4 + chunkLength);
352  } else if (in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') {
353  pos += 4;
354  IEND = true;
355  } else if (in[pos + 0] == 'P' && in[pos + 1] == 'L' && in[pos + 2] == 'T' && in[pos + 3] == 'E') { //palette chunk (PLTE)
356  pos += 4; //go after the 4 letters
357  info.palette.resize(4 * (chunkLength / 3));
358  if (info.palette.size() > (4 * 256)) {
359  error = 38; //error: palette too big
360  return;
361  }
362  for (size_t i = 0; i < info.palette.size(); i += 4) {
363  for (size_t j = 0; j < 3; j++) info.palette[i + j] = in[pos++]; //RGB
364  info.palette[i + 3] = 255; //alpha
365  }
366  } else if (in[pos + 0] == 't' && in[pos + 1] == 'R' && in[pos + 2] == 'N' && in[pos + 3] == 'S') { //palette transparency chunk (tRNS)
367  pos += 4; //go after the 4 letters
368  if (info.colorType == 3) {
369  if (4 * chunkLength > info.palette.size()) {
370  error = 39; //error: more alpha values given than there are palette entries
371  return;
372  }
373  for (size_t i = 0; i < chunkLength; i++) info.palette[4 * i + 3] = in[pos++];
374  } else if (info.colorType == 0) {
375  if (chunkLength != 2) {
376  error = 40; //error: this chunk must be 2 bytes for greyscale image
377  return;
378  }
379  info.key_defined = 1;
380  info.key_r = info.key_g = info.key_b = 256 * in[pos] + in[pos + 1];
381  pos += 2;
382  } else if (info.colorType == 2) {
383  if (chunkLength != 6) {
384  error = 41; //error: this chunk must be 6 bytes for RGB image
385  return;
386  }
387  info.key_defined = 1;
388  info.key_r = 256 * in[pos] + in[pos + 1];
389  pos += 2;
390  info.key_g = 256 * in[pos] + in[pos + 1];
391  pos += 2;
392  info.key_b = 256 * in[pos] + in[pos + 1];
393  pos += 2;
394  } else {
395  error = 42; //error: tRNS chunk not allowed for other color models
396  return;
397  }
398  } else { //it's not an implemented chunk type, so ignore it: skip over the data
399  if (!(in[pos + 0] & 32)) {
400  error = 69; //error: unknown critical chunk (5th bit of first byte of chunk type is 0)
401  return;
402  }
403  pos += (chunkLength + 4); //skip 4 letters and uninterpreted data of unimplemented chunk
404  }
405  pos += 4; //step over CRC (which is ignored)
406  }
407  unsigned long bpp = getBpp(info);
408  std::vector<unsigned char> scanlines(((info.width * (info.height * bpp + 7)) / 8) + info.height); //now the out buffer will be filled
409  Zlib zlib; //decompress with the Zlib decompressor
410  error = zlib.decompress(scanlines, idat);
411  if (error) return; //stop if the zlib decompressor returned an error
412  size_t bytewidth = (bpp + 7) / 8, outlength = (info.height * info.width * bpp + 7) / 8;
413  out.resize(outlength); //time to fill the out buffer
414  unsigned char* out_ = outlength ? &out[0] : 0; //use a regular pointer to the std::vector for faster code if compiled without optimization
415  if (info.interlaceMethod == 0) { //no interlace, just filter
416  size_t linestart = 0, linelength = (info.width * bpp + 7) / 8; //length in bytes of a scanline, excluding the filtertype byte
417  if (bpp >= 8) //byte per byte
418  for (unsigned long y = 0; y < info.height; y++) {
419  unsigned long filterType = scanlines[linestart];
420  const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth];
421  unFilterScanline(&out_[linestart - y], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength);
422  if (error) return;
423  linestart += (1 + linelength); //go to start of next scanline
424  } else { //less than 8 bits per pixel, so fill it up bit per bit
425  std::vector<unsigned char> templine((info.width * bpp + 7) >> 3); //only used if bpp < 8
426  for (size_t y = 0, obp = 0; y < info.height; y++) {
427  unsigned long filterType = scanlines[linestart];
428  const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth];
429  unFilterScanline(&templine[0], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength);
430  if (error) return;
431  for (size_t bp = 0; bp < info.width * bpp;) setBitOfReversedStream(obp, out_, readBitFromReversedStream(bp, &templine[0]));
432  linestart += (1 + linelength); //go to start of next scanline
433  }
434  }
435  } else { //interlaceMethod is 1 (Adam7)
436  size_t passw[7] = { (info.width + 7) / 8, (info.width + 3) / 8, (info.width + 3) / 4, (info.width + 1) / 4, (info.width + 1) / 2, (info.width + 0) / 2, (info.width + 0) / 1 };
437  size_t passh[7] = { (info.height + 7) / 8, (info.height + 7) / 8, (info.height + 3) / 8, (info.height + 3) / 4, (info.height + 1) / 4, (info.height + 1) / 2, (info.height + 0) / 2 };
438  size_t passstart[7] = { 0 };
439  size_t pattern[28] = { 0, 4, 0, 2, 0, 1, 0, 0, 0, 4, 0, 2, 0, 1, 8, 8, 4, 4, 2, 2, 1, 8, 8, 8, 4, 4, 2, 2 }; //values for the adam7 passes
440  for (int i = 0; i < 6; i++) passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8);
441  std::vector<unsigned char> scanlineo((info.width * bpp + 7) / 8), scanlinen((info.width * bpp + 7) / 8); //"old" and "new" scanline
442  for (int i = 0; i < 7; i++)
443  adam7Pass(&out_[0], &scanlinen[0], &scanlineo[0], &scanlines[passstart[i]], info.width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21], passw[i], passh[i], bpp);
444  }
445  if (convert_to_rgba32 && (info.colorType != 6 || info.bitDepth != 8)) { //conversion needed
446  std::vector<unsigned char> data = out;
447  error = convert(out, &data[0], info, info.width, info.height);
448  }
449  }
450  void readPngHeader(const unsigned char* in, size_t inlength) { //read the information from the header and store it in the Info
451  if (inlength < 29) {
452  error = 27; //error: the data length is smaller than the length of the header
453  return;
454  }
455  if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
456  error = 28; //no PNG signature
457  return;
458  }
459  if (in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') {
460  error = 29; //error: it doesn't start with a IHDR chunk!
461  return;
462  }
463  info.width = read32bitInt(&in[16]);
464  info.height = read32bitInt(&in[20]);
465  info.bitDepth = in[24];
466  info.colorType = in[25];
467  info.compressionMethod = in[26];
468  if (in[26] != 0) {
469  error = 32; //error: only compression method 0 is allowed in the specification
470  return;
471  }
472  info.filterMethod = in[27];
473  if (in[27] != 0) {
474  error = 33; //error: only filter method 0 is allowed in the specification
475  return;
476  }
477  info.interlaceMethod = in[28];
478  if (in[28] > 1) {
479  error = 34; //error: only interlace methods 0 and 1 exist in the specification
480  return;
481  }
482  error = checkColorValidity(info.colorType, info.bitDepth);
483  }
484  void unFilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned long filterType, size_t length) {
485  switch (filterType) {
486  case 0:
487  for (size_t i = 0; i < length; i++) recon[i] = scanline[i];
488  break;
489  case 1:
490  for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];
491  for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth];
492  break;
493  case 2:
494  if (precon) for (size_t i = 0; i < length; i++) recon[i] = scanline[i] + precon[i];
495  else for (size_t i = 0; i < length; i++) recon[i] = scanline[i];
496  break;
497  case 3:
498  if (precon) {
499  for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2;
500  for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
501  } else {
502  for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];
503  for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2;
504  }
505  break;
506  case 4:
507  if (precon) {
508  for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + paethPredictor(0, precon[i], 0);
509  for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]);
510  } else {
511  for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];
512  for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], 0, 0);
513  }
514  break;
515  default:
516  error = 36;
517  return; //error: unexisting filter type given
518  }
519  }
520  void adam7Pass(unsigned char* out, unsigned char* linen, unsigned char* lineo, const unsigned char* in, unsigned long w, size_t passleft, size_t passtop, size_t spacex, size_t spacey, size_t passw, size_t passh, unsigned long bpp) {
521  //filter and reposition the pixels into the output when the image is Adam7 interlaced. This function can only do it after the full image is already decoded. The out buffer must have the correct allocated memory size already.
522  if (passw == 0) return;
523  size_t bytewidth = (bpp + 7) / 8, linelength = 1 + ((bpp * passw + 7) / 8);
524  for (unsigned long y = 0; y < passh; y++) {
525  unsigned char filterType = in[y * linelength], *prevline = (y == 0) ? 0 : lineo;
526  unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType, (w * bpp + 7) / 8);
527  if (error) return;
528  if (bpp >= 8) for (size_t i = 0; i < passw; i++) for (size_t b = 0; b < bytewidth; b++) //b = current byte of this pixel
529  out[bytewidth * w * (passtop + spacey * y) + bytewidth * (passleft + spacex * i) + b] = linen[bytewidth * i + b];
530  else for (size_t i = 0; i < passw; i++) {
531  size_t obp = bpp * w * (passtop + spacey * y) + bpp * (passleft + spacex * i), bp = i * bpp;
532  for (size_t b = 0; b < bpp; b++) setBitOfReversedStream(obp, out, readBitFromReversedStream(bp, &linen[0]));
533  }
534  unsigned char* temp = linen;
535  linen = lineo;
536  lineo = temp; //swap the two buffer pointers "line old" and "line new"
537  }
538  }
539  static unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) {
540  unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1;
541  bitp++;
542  return result;
543  }
544  static unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits) {
545  unsigned long result = 0;
546  for (size_t i = nbits - 1; i < nbits; i--) result += ((readBitFromReversedStream(bitp, bits)) << i);
547  return result;
548  }
549  void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) {
550  bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7)));
551  bitp++;
552  }
553  unsigned long read32bitInt(const unsigned char* buffer) {
554  return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
555  }
556  int checkColorValidity(unsigned long colorType, unsigned long bd) { //return type is a LodePNG error code
557  if ((colorType == 2 || colorType == 4 || colorType == 6)) {
558  if (!(bd == 8 || bd == 16)) return 37;
559  else return 0;
560  } else if (colorType == 0) {
561  if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37;
562  else return 0;
563  } else if (colorType == 3) {
564  if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37;
565  else return 0;
566  } else return 31; //unexisting color type
567  }
568  unsigned long getBpp(const Info& info) {
569  if (info.colorType == 2) return (3 * info.bitDepth);
570  else if (info.colorType >= 4) return (info.colorType - 2) * info.bitDepth;
571  else return info.bitDepth;
572  }
573  int convert(std::vector<unsigned char>& out, const unsigned char* in, Info& infoIn, unsigned long w, unsigned long h) {
574  //converts from any color type to 32-bit. return value = LodePNG error code
575  size_t numpixels = w * h, bp = 0;
576  out.resize(numpixels * 4);
577  unsigned char* out_ = out.empty() ? 0 : &out[0]; //faster if compiled without optimization
578  if (infoIn.bitDepth == 8 && infoIn.colorType == 0) //greyscale
579  for (size_t i = 0; i < numpixels; i++) {
580  out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[i];
581  out_[4 * i + 3] = (infoIn.key_defined && in[i] == infoIn.key_r) ? 0 : 255;
582  } else if (infoIn.bitDepth == 8 && infoIn.colorType == 2) //RGB color
583  for (size_t i = 0; i < numpixels; i++) {
584  for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[3 * i + c];
585  out_[4 * i + 3] = (infoIn.key_defined == 1 && in[3 * i + 0] == infoIn.key_r && in[3 * i + 1] == infoIn.key_g && in[3 * i + 2] == infoIn.key_b) ? 0 : 255;
586  } else if (infoIn.bitDepth == 8 && infoIn.colorType == 3) //indexed color (palette)
587  for (size_t i = 0; i < numpixels; i++) {
588  if (4U * in[i] >= infoIn.palette.size()) return 46;
589  for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * in[i] + c]; //get rgb colors from the palette
590  } else if (infoIn.bitDepth == 8 && infoIn.colorType == 4) //greyscale with alpha
591  for (size_t i = 0; i < numpixels; i++) {
592  out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i + 0];
593  out_[4 * i + 3] = in[2 * i + 1];
594  } else if (infoIn.bitDepth == 8 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[4 * i + c]; //RGB with alpha
595  else if (infoIn.bitDepth == 16 && infoIn.colorType == 0) //greyscale
596  for (size_t i = 0; i < numpixels; i++) {
597  out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i];
598  out_[4 * i + 3] = (infoIn.key_defined && 256U * in[i] + in[i + 1] == infoIn.key_r) ? 0 : 255;
599  } else if (infoIn.bitDepth == 16 && infoIn.colorType == 2) //RGB color
600  for (size_t i = 0; i < numpixels; i++) {
601  for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[6 * i + 2 * c];
602  out_[4 * i + 3] = (infoIn.key_defined && 256U * in[6 * i + 0] + in[6 * i + 1] == infoIn.key_r && 256U * in[6 * i + 2] + in[6 * i + 3] == infoIn.key_g && 256U * in[6 * i + 4] + in[6 * i + 5] == infoIn.key_b) ? 0 : 255;
603  } else if (infoIn.bitDepth == 16 && infoIn.colorType == 4) //greyscale with alpha
604  for (size_t i = 0; i < numpixels; i++) {
605  out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[4 * i]; //most significant byte
606  out_[4 * i + 3] = in[4 * i + 2];
607  } else if (infoIn.bitDepth == 16 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[8 * i + 2 * c]; //RGB with alpha
608  else if (infoIn.bitDepth < 8 && infoIn.colorType == 0) //greyscale
609  for (size_t i = 0; i < numpixels; i++) {
610  unsigned long value = (readBitsFromReversedStream(bp, in, infoIn.bitDepth) * 255) / ((1 << infoIn.bitDepth) - 1); //scale value from 0 to 255
611  out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = (unsigned char)(value);
612  out_[4 * i + 3] = (infoIn.key_defined && value && ((1U << infoIn.bitDepth) - 1U) == infoIn.key_r && ((1U << infoIn.bitDepth) - 1U)) ? 0 : 255;
613  } else if (infoIn.bitDepth < 8 && infoIn.colorType == 3) //palette
614  for (size_t i = 0; i < numpixels; i++) {
615  unsigned long value = readBitsFromReversedStream(bp, in, infoIn.bitDepth);
616  if (4 * value >= infoIn.palette.size()) return 47;
617  for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * value + c]; //get rgb colors from the palette
618  }
619  return 0;
620  }
621  unsigned char paethPredictor(short a, short b, short c) { //Paeth predicter, used by PNG filter type 4
622  short p = a + b - c, pa = p > a ? (p - a) : (a - p), pb = p > b ? (p - b) : (b - p), pc = p > c ? (p - c) : (c - p);
623  return (unsigned char)((pa <= pb && pa <= pc) ? a : pb <= pc ? b : c);
624  }
625  };
626  PNG decoder;
627  decoder.decode(out_image, in_png, in_size, convert_to_rgba32);
628  image_width = decoder.info.width;
629  image_height = decoder.info.height;
630  return decoder.error;
631  }
632 
633 }
BARE2D
Definition: App.cpp:13
BARE2D::decodePNG
int decodePNG(std::vector< unsigned char > &out_image, unsigned long &image_width, unsigned long &image_height, const unsigned char *in_png, std::size_t in_size, bool convert_to_rgba32)
Definition: PicoPNG.cpp:28