picopng.h 33 KB

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