upng.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /*
  2. uPNG -- derived from LodePNG version 20100808
  3. Copyright (c) 2005-2010 Lode Vandevenne
  4. Copyright (c) 2010 Sean Middleditch
  5. This software is provided 'as-is', without any express or implied
  6. warranty. In no event will the authors be held liable for any damages
  7. arising from the use of this software.
  8. Permission is granted to anyone to use this software for any purpose,
  9. including commercial applications, and to alter it and redistribute it
  10. freely, subject to the following restrictions:
  11. 1. The origin of this software must not be misrepresented; you must not
  12. claim that you wrote the original software. If you use this software
  13. in a product, an acknowledgment in the product documentation would be
  14. appreciated but is not required.
  15. 2. Altered source versions must be plainly marked as such, and must not be
  16. misrepresented as being the original software.
  17. 3. This notice may not be removed or altered from any source
  18. distribution.
  19. */
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <limits.h>
  24. #include "upng.h"
  25. #define MAKE_BYTE(b) ((b) & 0xFF)
  26. #define MAKE_DWORD(a,b,c,d) ((MAKE_BYTE(a) << 24) | (MAKE_BYTE(b) << 16) | (MAKE_BYTE(c) << 8) | MAKE_BYTE(d))
  27. #define MAKE_DWORD_PTR(p) MAKE_DWORD((p)[0], (p)[1], (p)[2], (p)[3])
  28. #define CHUNK_IHDR MAKE_DWORD('I','H','D','R')
  29. #define CHUNK_IDAT MAKE_DWORD('I','D','A','T')
  30. #define CHUNK_IEND MAKE_DWORD('I','E','N','D')
  31. #define FIRST_LENGTH_CODE_INDEX 257
  32. #define LAST_LENGTH_CODE_INDEX 285
  33. #define NUM_DEFLATE_CODE_SYMBOLS 288 /*256 literals, the end code, some length codes, and 2 unused codes */
  34. #define NUM_DISTANCE_SYMBOLS 32 /*the distance codes have their own symbols, 30 used, 2 unused */
  35. #define NUM_CODE_LENGTH_CODES 19 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros */
  36. #define MAX_SYMBOLS 288 /* largest number of symbols used by any tree type */
  37. #define DEFLATE_CODE_BITLEN 15
  38. #define DISTANCE_BITLEN 15
  39. #define CODE_LENGTH_BITLEN 7
  40. #define MAX_BIT_LENGTH 15 /* largest bitlen used by any tree type */
  41. #define DEFLATE_CODE_BUFFER_SIZE (NUM_DEFLATE_CODE_SYMBOLS * 2)
  42. #define DISTANCE_BUFFER_SIZE (NUM_DISTANCE_SYMBOLS * 2)
  43. #define CODE_LENGTH_BUFFER_SIZE (NUM_DISTANCE_SYMBOLS * 2)
  44. #define SET_ERROR(upng,code) do { (upng)->error = (code); (upng)->error_line = __LINE__; } while (0)
  45. #define upng_chunk_length(chunk) MAKE_DWORD_PTR(chunk)
  46. #define upng_chunk_type(chunk) MAKE_DWORD_PTR((chunk) + 4)
  47. #define upng_chunk_critical(chunk) (((chunk)[4] & 32) == 0)
  48. typedef enum upng_state {
  49. UPNG_ERROR = -1,
  50. UPNG_DECODED = 0,
  51. UPNG_HEADER = 1,
  52. UPNG_NEW = 2
  53. } upng_state;
  54. typedef enum upng_color {
  55. UPNG_LUM = 0,
  56. UPNG_RGB = 2,
  57. UPNG_LUMA = 4,
  58. UPNG_RGBA = 6
  59. } upng_color;
  60. typedef struct upng_source {
  61. const unsigned char* buffer;
  62. unsigned long size;
  63. char owning;
  64. } upng_source;
  65. struct upng_t {
  66. unsigned width;
  67. unsigned height;
  68. upng_color color_type;
  69. unsigned color_depth;
  70. upng_format format;
  71. unsigned char* buffer;
  72. unsigned long size;
  73. upng_error error;
  74. unsigned error_line;
  75. upng_state state;
  76. upng_source source;
  77. };
  78. typedef struct huffman_tree {
  79. unsigned* tree2d;
  80. unsigned maxbitlen; /*maximum number of bits a single code can get */
  81. unsigned numcodes; /*number of symbols in the alphabet = number of codes */
  82. } huffman_tree;
  83. static const unsigned LENGTH_BASE[29] = { /*the base lengths represented by codes 257-285 */
  84. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
  85. 67, 83, 99, 115, 131, 163, 195, 227, 258
  86. };
  87. static const unsigned LENGTH_EXTRA[29] = { /*the extra bits used by codes 257-285 (added to base length) */
  88. 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,
  89. 5, 5, 5, 0
  90. };
  91. static const unsigned DISTANCE_BASE[30] = { /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree) */
  92. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
  93. 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
  94. };
  95. static const unsigned DISTANCE_EXTRA[30] = { /*the extra bits of backwards distances (added to base) */
  96. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
  97. 11, 11, 12, 12, 13, 13
  98. };
  99. static const unsigned CLCL[NUM_CODE_LENGTH_CODES] /*the order in which "code length alphabet code lengths" are stored, out of this the huffman tree of the dynamic huffman tree lengths is generated */
  100. = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  101. static const unsigned FIXED_DEFLATE_CODE_TREE[NUM_DEFLATE_CODE_SYMBOLS * 2] = {
  102. 289, 370, 290, 307, 546, 291, 561, 292, 293, 300, 294, 297, 295, 296, 0, 1,
  103. 2, 3, 298, 299, 4, 5, 6, 7, 301, 304, 302, 303, 8, 9, 10, 11, 305, 306, 12,
  104. 13, 14, 15, 308, 339, 309, 324, 310, 317, 311, 314, 312, 313, 16, 17, 18,
  105. 19, 315, 316, 20, 21, 22, 23, 318, 321, 319, 320, 24, 25, 26, 27, 322, 323,
  106. 28, 29, 30, 31, 325, 332, 326, 329, 327, 328, 32, 33, 34, 35, 330, 331, 36,
  107. 37, 38, 39, 333, 336, 334, 335, 40, 41, 42, 43, 337, 338, 44, 45, 46, 47,
  108. 340, 355, 341, 348, 342, 345, 343, 344, 48, 49, 50, 51, 346, 347, 52, 53,
  109. 54, 55, 349, 352, 350, 351, 56, 57, 58, 59, 353, 354, 60, 61, 62, 63, 356,
  110. 363, 357, 360, 358, 359, 64, 65, 66, 67, 361, 362, 68, 69, 70, 71, 364,
  111. 367, 365, 366, 72, 73, 74, 75, 368, 369, 76, 77, 78, 79, 371, 434, 372,
  112. 403, 373, 388, 374, 381, 375, 378, 376, 377, 80, 81, 82, 83, 379, 380, 84,
  113. 85, 86, 87, 382, 385, 383, 384, 88, 89, 90, 91, 386, 387, 92, 93, 94, 95,
  114. 389, 396, 390, 393, 391, 392, 96, 97, 98, 99, 394, 395, 100, 101, 102, 103,
  115. 397, 400, 398, 399, 104, 105, 106, 107, 401, 402, 108, 109, 110, 111, 404,
  116. 419, 405, 412, 406, 409, 407, 408, 112, 113, 114, 115, 410, 411, 116, 117,
  117. 118, 119, 413, 416, 414, 415, 120, 121, 122, 123, 417, 418, 124, 125, 126,
  118. 127, 420, 427, 421, 424, 422, 423, 128, 129, 130, 131, 425, 426, 132, 133,
  119. 134, 135, 428, 431, 429, 430, 136, 137, 138, 139, 432, 433, 140, 141, 142,
  120. 143, 435, 483, 436, 452, 568, 437, 438, 445, 439, 442, 440, 441, 144, 145,
  121. 146, 147, 443, 444, 148, 149, 150, 151, 446, 449, 447, 448, 152, 153, 154,
  122. 155, 450, 451, 156, 157, 158, 159, 453, 468, 454, 461, 455, 458, 456, 457,
  123. 160, 161, 162, 163, 459, 460, 164, 165, 166, 167, 462, 465, 463, 464, 168,
  124. 169, 170, 171, 466, 467, 172, 173, 174, 175, 469, 476, 470, 473, 471, 472,
  125. 176, 177, 178, 179, 474, 475, 180, 181, 182, 183, 477, 480, 478, 479, 184,
  126. 185, 186, 187, 481, 482, 188, 189, 190, 191, 484, 515, 485, 500, 486, 493,
  127. 487, 490, 488, 489, 192, 193, 194, 195, 491, 492, 196, 197, 198, 199, 494,
  128. 497, 495, 496, 200, 201, 202, 203, 498, 499, 204, 205, 206, 207, 501, 508,
  129. 502, 505, 503, 504, 208, 209, 210, 211, 506, 507, 212, 213, 214, 215, 509,
  130. 512, 510, 511, 216, 217, 218, 219, 513, 514, 220, 221, 222, 223, 516, 531,
  131. 517, 524, 518, 521, 519, 520, 224, 225, 226, 227, 522, 523, 228, 229, 230,
  132. 231, 525, 528, 526, 527, 232, 233, 234, 235, 529, 530, 236, 237, 238, 239,
  133. 532, 539, 533, 536, 534, 535, 240, 241, 242, 243, 537, 538, 244, 245, 246,
  134. 247, 540, 543, 541, 542, 248, 249, 250, 251, 544, 545, 252, 253, 254, 255,
  135. 547, 554, 548, 551, 549, 550, 256, 257, 258, 259, 552, 553, 260, 261, 262,
  136. 263, 555, 558, 556, 557, 264, 265, 266, 267, 559, 560, 268, 269, 270, 271,
  137. 562, 565, 563, 564, 272, 273, 274, 275, 566, 567, 276, 277, 278, 279, 569,
  138. 572, 570, 571, 280, 281, 282, 283, 573, 574, 284, 285, 286, 287, 0, 0
  139. };
  140. static const unsigned FIXED_DISTANCE_TREE[NUM_DISTANCE_SYMBOLS * 2] = {
  141. 33, 48, 34, 41, 35, 38, 36, 37, 0, 1, 2, 3, 39, 40, 4, 5, 6, 7, 42, 45, 43,
  142. 44, 8, 9, 10, 11, 46, 47, 12, 13, 14, 15, 49, 56, 50, 53, 51, 52, 16, 17,
  143. 18, 19, 54, 55, 20, 21, 22, 23, 57, 60, 58, 59, 24, 25, 26, 27, 61, 62, 28,
  144. 29, 30, 31, 0, 0
  145. };
  146. static unsigned char read_bit(unsigned long *bitpointer, const unsigned char *bitstream)
  147. {
  148. unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> ((*bitpointer) & 0x7)) & 1);
  149. (*bitpointer)++;
  150. return result;
  151. }
  152. static unsigned read_bits(unsigned long *bitpointer, const unsigned char *bitstream, unsigned long nbits)
  153. {
  154. unsigned result = 0, i;
  155. for (i = 0; i < nbits; i++)
  156. result |= ((unsigned)read_bit(bitpointer, bitstream)) << i;
  157. return result;
  158. }
  159. /* the buffer must be numcodes*2 in size! */
  160. static void huffman_tree_init(huffman_tree* tree, unsigned* buffer, unsigned numcodes, unsigned maxbitlen)
  161. {
  162. tree->tree2d = buffer;
  163. tree->numcodes = numcodes;
  164. tree->maxbitlen = maxbitlen;
  165. }
  166. /*given the code lengths (as stored in the PNG file), generate the tree as defined by Deflate. maxbitlen is the maximum bits that a code in the tree can have. return value is error.*/
  167. static void huffman_tree_create_lengths(upng_t* upng, huffman_tree* tree, const unsigned *bitlen)
  168. {
  169. unsigned tree1d[MAX_SYMBOLS];
  170. unsigned blcount[MAX_BIT_LENGTH];
  171. unsigned nextcode[MAX_BIT_LENGTH];
  172. unsigned bits, n, i;
  173. unsigned nodefilled = 0; /*up to which node it is filled */
  174. unsigned treepos = 0; /*position in the tree (1 of the numcodes columns) */
  175. /* initialize local vectors */
  176. memset(blcount, 0, sizeof(blcount));
  177. memset(nextcode, 0, sizeof(nextcode));
  178. /*step 1: count number of instances of each code length */
  179. for (bits = 0; bits < tree->numcodes; bits++) {
  180. blcount[bitlen[bits]]++;
  181. }
  182. /*step 2: generate the nextcode values */
  183. for (bits = 1; bits <= tree->maxbitlen; bits++) {
  184. nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1;
  185. }
  186. /*step 3: generate all the codes */
  187. for (n = 0; n < tree->numcodes; n++) {
  188. if (bitlen[n] != 0) {
  189. tree1d[n] = nextcode[bitlen[n]]++;
  190. }
  191. }
  192. /*convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means uninited, a value >= numcodes is an address to another bit, a value < numcodes is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as many columns as codes - 1
  193. a good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. Here, the internal nodes are stored (what their 0 and 1 option point to). There is only memory for such good tree currently, if there are more nodes (due to too long length codes), error 55 will happen */
  194. for (n = 0; n < tree->numcodes * 2; n++) {
  195. tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet */
  196. }
  197. for (n = 0; n < tree->numcodes; n++) { /*the codes */
  198. for (i = 0; i < bitlen[n]; i++) { /*the bits for this code */
  199. unsigned char bit = (unsigned char)((tree1d[n] >> (bitlen[n] - i - 1)) & 1);
  200. /* check if oversubscribed */
  201. if (treepos > tree->numcodes - 2) {
  202. SET_ERROR(upng, UPNG_EMALFORMED);
  203. return;
  204. }
  205. if (tree->tree2d[2 * treepos + bit] == 32767) { /*not yet filled in */
  206. if (i + 1 == bitlen[n]) { /*last bit */
  207. tree->tree2d[2 * treepos + bit] = n; /*put the current code in it */
  208. treepos = 0;
  209. } else { /*put address of the next step in here, first that address has to be found of course (it's just nodefilled + 1)... */
  210. nodefilled++;
  211. tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; /*addresses encoded with numcodes added to it */
  212. treepos = nodefilled;
  213. }
  214. } else {
  215. treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
  216. }
  217. }
  218. }
  219. for (n = 0; n < tree->numcodes * 2; n++) {
  220. if (tree->tree2d[n] == 32767) {
  221. tree->tree2d[n] = 0; /*remove possible remaining 32767's */
  222. }
  223. }
  224. }
  225. static unsigned huffman_decode_symbol(upng_t *upng, const unsigned char *in, unsigned long *bp, const huffman_tree* codetree, unsigned long inlength)
  226. {
  227. unsigned treepos = 0, ct;
  228. unsigned char bit;
  229. for (;;) {
  230. /* error: end of input memory reached without endcode */
  231. if (((*bp) & 0x07) == 0 && ((*bp) >> 3) > inlength) {
  232. SET_ERROR(upng, UPNG_EMALFORMED);
  233. return 0;
  234. }
  235. bit = read_bit(bp, in);
  236. ct = codetree->tree2d[(treepos << 1) | bit];
  237. if (ct < codetree->numcodes) {
  238. return ct;
  239. }
  240. treepos = ct - codetree->numcodes;
  241. if (treepos >= codetree->numcodes) {
  242. SET_ERROR(upng, UPNG_EMALFORMED);
  243. return 0;
  244. }
  245. }
  246. }
  247. /* get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
  248. static void get_tree_inflate_dynamic(upng_t* upng, huffman_tree* codetree, huffman_tree* codetreeD, huffman_tree* codelengthcodetree, const unsigned char *in, unsigned long *bp, unsigned long inlength)
  249. {
  250. unsigned codelengthcode[NUM_CODE_LENGTH_CODES];
  251. unsigned bitlen[NUM_DEFLATE_CODE_SYMBOLS];
  252. unsigned bitlenD[NUM_DISTANCE_SYMBOLS];
  253. unsigned n, hlit, hdist, hclen, i;
  254. /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated */
  255. /*C-code note: use no "return" between ctor and dtor of an uivector! */
  256. if ((*bp) >> 3 >= inlength - 2) {
  257. SET_ERROR(upng, UPNG_EMALFORMED);
  258. return;
  259. }
  260. /* clear bitlen arrays */
  261. memset(bitlen, 0, sizeof(bitlen));
  262. memset(bitlenD, 0, sizeof(bitlenD));
  263. /*the bit pointer is or will go past the memory */
  264. hlit = read_bits(bp, in, 5) + 257; /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already */
  265. hdist = read_bits(bp, in, 5) + 1; /*number of distance codes. Unlike the spec, the value 1 is added to it here already */
  266. hclen = read_bits(bp, in, 4) + 4; /*number of code length codes. Unlike the spec, the value 4 is added to it here already */
  267. for (i = 0; i < NUM_CODE_LENGTH_CODES; i++) {
  268. if (i < hclen) {
  269. codelengthcode[CLCL[i]] = read_bits(bp, in, 3);
  270. } else {
  271. codelengthcode[CLCL[i]] = 0; /*if not, it must stay 0 */
  272. }
  273. }
  274. huffman_tree_create_lengths(upng, codelengthcodetree, codelengthcode);
  275. /* bail now if we encountered an error earlier */
  276. if (upng->error != UPNG_EOK) {
  277. return;
  278. }
  279. /*now we can use this tree to read the lengths for the tree that this function will return */
  280. i = 0;
  281. while (i < hlit + hdist) { /*i is the current symbol we're reading in the part that contains the code lengths of lit/len codes and dist codes */
  282. unsigned code = huffman_decode_symbol(upng, in, bp, codelengthcodetree, inlength);
  283. if (upng->error != UPNG_EOK) {
  284. break;
  285. }
  286. if (code <= 15) { /*a length code */
  287. if (i < hlit) {
  288. bitlen[i] = code;
  289. } else {
  290. bitlenD[i - hlit] = code;
  291. }
  292. i++;
  293. } else if (code == 16) { /*repeat previous */
  294. unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6) */
  295. unsigned value; /*set value to the previous code */
  296. if ((*bp) >> 3 >= inlength) {
  297. SET_ERROR(upng, UPNG_EMALFORMED);
  298. break;
  299. }
  300. /*error, bit pointer jumps past memory */
  301. replength += read_bits(bp, in, 2);
  302. if ((i - 1) < hlit) {
  303. value = bitlen[i - 1];
  304. } else {
  305. value = bitlenD[i - hlit - 1];
  306. }
  307. /*repeat this value in the next lengths */
  308. for (n = 0; n < replength; n++) {
  309. /* i is larger than the amount of codes */
  310. if (i >= hlit + hdist) {
  311. SET_ERROR(upng, UPNG_EMALFORMED);
  312. break;
  313. }
  314. if (i < hlit) {
  315. bitlen[i] = value;
  316. } else {
  317. bitlenD[i - hlit] = value;
  318. }
  319. i++;
  320. }
  321. } else if (code == 17) { /*repeat "0" 3-10 times */
  322. unsigned replength = 3; /*read in the bits that indicate repeat length */
  323. if ((*bp) >> 3 >= inlength) {
  324. SET_ERROR(upng, UPNG_EMALFORMED);
  325. break;
  326. }
  327. /*error, bit pointer jumps past memory */
  328. replength += read_bits(bp, in, 3);
  329. /*repeat this value in the next lengths */
  330. for (n = 0; n < replength; n++) {
  331. /* error: i is larger than the amount of codes */
  332. if (i >= hlit + hdist) {
  333. SET_ERROR(upng, UPNG_EMALFORMED);
  334. break;
  335. }
  336. if (i < hlit) {
  337. bitlen[i] = 0;
  338. } else {
  339. bitlenD[i - hlit] = 0;
  340. }
  341. i++;
  342. }
  343. } else if (code == 18) { /*repeat "0" 11-138 times */
  344. unsigned replength = 11; /*read in the bits that indicate repeat length */
  345. /* error, bit pointer jumps past memory */
  346. if ((*bp) >> 3 >= inlength) {
  347. SET_ERROR(upng, UPNG_EMALFORMED);
  348. break;
  349. }
  350. replength += read_bits(bp, in, 7);
  351. /*repeat this value in the next lengths */
  352. for (n = 0; n < replength; n++) {
  353. /* i is larger than the amount of codes */
  354. if (i >= hlit + hdist) {
  355. SET_ERROR(upng, UPNG_EMALFORMED);
  356. break;
  357. }
  358. if (i < hlit)
  359. bitlen[i] = 0;
  360. else
  361. bitlenD[i - hlit] = 0;
  362. i++;
  363. }
  364. } else {
  365. /* somehow an unexisting code appeared. This can never happen. */
  366. SET_ERROR(upng, UPNG_EMALFORMED);
  367. break;
  368. }
  369. }
  370. if (upng->error == UPNG_EOK && bitlen[256] == 0) {
  371. SET_ERROR(upng, UPNG_EMALFORMED);
  372. }
  373. /*the length of the end code 256 must be larger than 0 */
  374. /*now we've finally got hlit and hdist, so generate the code trees, and the function is done */
  375. if (upng->error == UPNG_EOK) {
  376. huffman_tree_create_lengths(upng, codetree, bitlen);
  377. }
  378. if (upng->error == UPNG_EOK) {
  379. huffman_tree_create_lengths(upng, codetreeD, bitlenD);
  380. }
  381. }
  382. /*inflate a block with dynamic of fixed Huffman tree*/
  383. static void inflate_huffman(upng_t* upng, unsigned char* out, unsigned long outsize, const unsigned char *in, unsigned long *bp, unsigned long *pos, unsigned long inlength, unsigned btype)
  384. {
  385. unsigned codetree_buffer[DEFLATE_CODE_BUFFER_SIZE];
  386. unsigned codetreeD_buffer[DISTANCE_BUFFER_SIZE];
  387. unsigned done = 0;
  388. huffman_tree codetree;
  389. huffman_tree codetreeD;
  390. if (btype == 1) {
  391. /* fixed trees */
  392. huffman_tree_init(&codetree, (unsigned*)FIXED_DEFLATE_CODE_TREE, NUM_DEFLATE_CODE_SYMBOLS, DEFLATE_CODE_BITLEN);
  393. huffman_tree_init(&codetreeD, (unsigned*)FIXED_DISTANCE_TREE, NUM_DISTANCE_SYMBOLS, DISTANCE_BITLEN);
  394. } else if (btype == 2) {
  395. /* dynamic trees */
  396. unsigned codelengthcodetree_buffer[CODE_LENGTH_BUFFER_SIZE];
  397. huffman_tree codelengthcodetree;
  398. huffman_tree_init(&codetree, codetree_buffer, NUM_DEFLATE_CODE_SYMBOLS, DEFLATE_CODE_BITLEN);
  399. huffman_tree_init(&codetreeD, codetreeD_buffer, NUM_DISTANCE_SYMBOLS, DISTANCE_BITLEN);
  400. huffman_tree_init(&codelengthcodetree, codelengthcodetree_buffer, NUM_CODE_LENGTH_CODES, CODE_LENGTH_BITLEN);
  401. get_tree_inflate_dynamic(upng, &codetree, &codetreeD, &codelengthcodetree, in, bp, inlength);
  402. }
  403. while (done == 0) {
  404. unsigned code = huffman_decode_symbol(upng, in, bp, &codetree, inlength);
  405. if (upng->error != UPNG_EOK) {
  406. return;
  407. }
  408. if (code == 256) {
  409. /* end code */
  410. done = 1;
  411. } else if (code <= 255) {
  412. /* literal symbol */
  413. if ((*pos) >= outsize) {
  414. SET_ERROR(upng, UPNG_EMALFORMED);
  415. return;
  416. }
  417. /* store output */
  418. out[(*pos)++] = (unsigned char)(code);
  419. } else if (code >= FIRST_LENGTH_CODE_INDEX && code <= LAST_LENGTH_CODE_INDEX) { /*length code */
  420. /* part 1: get length base */
  421. unsigned long length = LENGTH_BASE[code - FIRST_LENGTH_CODE_INDEX];
  422. unsigned codeD, distance, numextrabitsD;
  423. unsigned long start, forward, backward, numextrabits;
  424. /* part 2: get extra bits and add the value of that to length */
  425. numextrabits = LENGTH_EXTRA[code - FIRST_LENGTH_CODE_INDEX];
  426. /* error, bit pointer will jump past memory */
  427. if (((*bp) >> 3) >= inlength) {
  428. SET_ERROR(upng, UPNG_EMALFORMED);
  429. return;
  430. }
  431. length += read_bits(bp, in, numextrabits);
  432. /*part 3: get distance code */
  433. codeD = huffman_decode_symbol(upng, in, bp, &codetreeD, inlength);
  434. if (upng->error != UPNG_EOK) {
  435. return;
  436. }
  437. /* invalid distance code (30-31 are never used) */
  438. if (codeD > 29) {
  439. SET_ERROR(upng, UPNG_EMALFORMED);
  440. return;
  441. }
  442. distance = DISTANCE_BASE[codeD];
  443. /*part 4: get extra bits from distance */
  444. numextrabitsD = DISTANCE_EXTRA[codeD];
  445. /* error, bit pointer will jump past memory */
  446. if (((*bp) >> 3) >= inlength) {
  447. SET_ERROR(upng, UPNG_EMALFORMED);
  448. return;
  449. }
  450. distance += read_bits(bp, in, numextrabitsD);
  451. /*part 5: fill in all the out[n] values based on the length and dist */
  452. start = (*pos);
  453. backward = start - distance;
  454. if ((*pos) + length >= outsize) {
  455. SET_ERROR(upng, UPNG_EMALFORMED);
  456. return;
  457. }
  458. for (forward = 0; forward < length; forward++) {
  459. out[(*pos)++] = out[backward];
  460. backward++;
  461. if (backward >= start) {
  462. backward = start - distance;
  463. }
  464. }
  465. }
  466. }
  467. }
  468. static void inflate_uncompressed(upng_t* upng, unsigned char* out, unsigned long outsize, const unsigned char *in, unsigned long *bp, unsigned long *pos, unsigned long inlength)
  469. {
  470. unsigned long p;
  471. unsigned len, nlen, n;
  472. /* go to first boundary of byte */
  473. while (((*bp) & 0x7) != 0) {
  474. (*bp)++;
  475. }
  476. p = (*bp) / 8; /*byte position */
  477. /* read len (2 bytes) and nlen (2 bytes) */
  478. if (p >= inlength - 4) {
  479. SET_ERROR(upng, UPNG_EMALFORMED);
  480. return;
  481. }
  482. len = in[p] + 256 * in[p + 1];
  483. p += 2;
  484. nlen = in[p] + 256 * in[p + 1];
  485. p += 2;
  486. /* check if 16-bit nlen is really the one's complement of len */
  487. if (len + nlen != 65535) {
  488. SET_ERROR(upng, UPNG_EMALFORMED);
  489. return;
  490. }
  491. if ((*pos) + len >= outsize) {
  492. SET_ERROR(upng, UPNG_EMALFORMED);
  493. return;
  494. }
  495. /* read the literal data: len bytes are now stored in the out buffer */
  496. if (p + len > inlength) {
  497. SET_ERROR(upng, UPNG_EMALFORMED);
  498. return;
  499. }
  500. for (n = 0; n < len; n++) {
  501. out[(*pos)++] = in[p++];
  502. }
  503. (*bp) = p * 8;
  504. }
  505. /*inflate the deflated data (cfr. deflate spec); return value is the error*/
  506. static upng_error uz_inflate_data(upng_t* upng, unsigned char* out, unsigned long outsize, const unsigned char *in, unsigned long insize, unsigned long inpos)
  507. {
  508. unsigned long bp = 0; /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte) */
  509. unsigned long pos = 0; /*byte position in the out buffer */
  510. unsigned done = 0;
  511. while (done == 0) {
  512. unsigned btype;
  513. /* ensure next bit doesn't point past the end of the buffer */
  514. if ((bp >> 3) >= insize) {
  515. SET_ERROR(upng, UPNG_EMALFORMED);
  516. return upng->error;
  517. }
  518. /* read block control bits */
  519. done = read_bit(&bp, &in[inpos]);
  520. btype = read_bit(&bp, &in[inpos]) | (read_bit(&bp, &in[inpos]) << 1);
  521. /* process control type appropriateyly */
  522. if (btype == 3) {
  523. SET_ERROR(upng, UPNG_EMALFORMED);
  524. return upng->error;
  525. } else if (btype == 0) {
  526. inflate_uncompressed(upng, out, outsize, &in[inpos], &bp, &pos, insize); /*no compression */
  527. } else {
  528. inflate_huffman(upng, out, outsize, &in[inpos], &bp, &pos, insize, btype); /*compression, btype 01 or 10 */
  529. }
  530. /* stop if an error has occured */
  531. if (upng->error != UPNG_EOK) {
  532. return upng->error;
  533. }
  534. }
  535. return upng->error;
  536. }
  537. static upng_error uz_inflate(upng_t* upng, unsigned char *out, unsigned long outsize, const unsigned char *in, unsigned long insize)
  538. {
  539. /* we require two bytes for the zlib data header */
  540. if (insize < 2) {
  541. SET_ERROR(upng, UPNG_EMALFORMED);
  542. return upng->error;
  543. }
  544. /* 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way */
  545. if ((in[0] * 256 + in[1]) % 31 != 0) {
  546. SET_ERROR(upng, UPNG_EMALFORMED);
  547. return upng->error;
  548. }
  549. /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec */
  550. if ((in[0] & 15) != 8 || ((in[0] >> 4) & 15) > 7) {
  551. SET_ERROR(upng, UPNG_EMALFORMED);
  552. return upng->error;
  553. }
  554. /* the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary." */
  555. if (((in[1] >> 5) & 1) != 0) {
  556. SET_ERROR(upng, UPNG_EMALFORMED);
  557. return upng->error;
  558. }
  559. /* create output buffer */
  560. uz_inflate_data(upng, out, outsize, in, insize, 2);
  561. return upng->error;
  562. }
  563. /*Paeth predicter, used by PNG filter type 4*/
  564. static int paeth_predictor(int a, int b, int c)
  565. {
  566. int p = a + b - c;
  567. int pa = p > a ? p - a : a - p;
  568. int pb = p > b ? p - b : b - p;
  569. int pc = p > c ? p - c : c - p;
  570. if (pa <= pb && pa <= pc)
  571. return a;
  572. else if (pb <= pc)
  573. return b;
  574. else
  575. return c;
  576. }
  577. static void unfilter_scanline(upng_t* upng, unsigned char *recon, const unsigned char *scanline, const unsigned char *precon, unsigned long bytewidth, unsigned char filterType, unsigned long length)
  578. {
  579. /*
  580. For PNG filter method 0
  581. unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, the filter works byte per byte (bytewidth = 1)
  582. precon is the previous unfiltered scanline, recon the result, scanline the current one
  583. the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
  584. recon and scanline MAY be the same memory address! precon must be disjoint.
  585. */
  586. unsigned long i;
  587. switch (filterType) {
  588. case 0:
  589. for (i = 0; i < length; i++)
  590. recon[i] = scanline[i];
  591. break;
  592. case 1:
  593. for (i = 0; i < bytewidth; i++)
  594. recon[i] = scanline[i];
  595. for (i = bytewidth; i < length; i++)
  596. recon[i] = scanline[i] + recon[i - bytewidth];
  597. break;
  598. case 2:
  599. if (precon)
  600. for (i = 0; i < length; i++)
  601. recon[i] = scanline[i] + precon[i];
  602. else
  603. for (i = 0; i < length; i++)
  604. recon[i] = scanline[i];
  605. break;
  606. case 3:
  607. if (precon) {
  608. for (i = 0; i < bytewidth; i++)
  609. recon[i] = scanline[i] + precon[i] / 2;
  610. for (i = bytewidth; i < length; i++)
  611. recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
  612. } else {
  613. for (i = 0; i < bytewidth; i++)
  614. recon[i] = scanline[i];
  615. for (i = bytewidth; i < length; i++)
  616. recon[i] = scanline[i] + recon[i - bytewidth] / 2;
  617. }
  618. break;
  619. case 4:
  620. if (precon) {
  621. for (i = 0; i < bytewidth; i++)
  622. recon[i] = (unsigned char)(scanline[i] + paeth_predictor(0, precon[i], 0));
  623. for (i = bytewidth; i < length; i++)
  624. recon[i] = (unsigned char)(scanline[i] + paeth_predictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
  625. } else {
  626. for (i = 0; i < bytewidth; i++)
  627. recon[i] = scanline[i];
  628. for (i = bytewidth; i < length; i++)
  629. recon[i] = (unsigned char)(scanline[i] + paeth_predictor(recon[i - bytewidth], 0, 0));
  630. }
  631. break;
  632. default:
  633. SET_ERROR(upng, UPNG_EMALFORMED);
  634. break;
  635. }
  636. }
  637. static void unfilter(upng_t* upng, unsigned char *out, const unsigned char *in, unsigned w, unsigned h, unsigned bpp)
  638. {
  639. /*
  640. For PNG filter method 0
  641. this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 it's called 7 times)
  642. out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
  643. w and h are image dimensions or dimensions of reduced image, bpp is bpp per pixel
  644. in and out are allowed to be the same memory address!
  645. */
  646. unsigned y;
  647. unsigned char *prevline = 0;
  648. unsigned long bytewidth = (bpp + 7) / 8; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise */
  649. unsigned long linebytes = (w * bpp + 7) / 8;
  650. for (y = 0; y < h; y++) {
  651. unsigned long outindex = linebytes * y;
  652. unsigned long inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row */
  653. unsigned char filterType = in[inindex];
  654. unfilter_scanline(upng, &out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes);
  655. if (upng->error != UPNG_EOK) {
  656. return;
  657. }
  658. prevline = &out[outindex];
  659. }
  660. }
  661. static void remove_padding_bits(unsigned char *out, const unsigned char *in, unsigned long olinebits, unsigned long ilinebits, unsigned h)
  662. {
  663. /*
  664. After filtering there are still padding bpp if scanlines have non multiple of 8 bit amounts. They need to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers for the Adam7 code, the color convert code and the output to the user.
  665. in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must have >= ilinebits*h bpp, out must have >= olinebits*h bpp, olinebits must be <= ilinebits
  666. also used to move bpp after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
  667. only useful if (ilinebits - olinebits) is a value in the range 1..7
  668. */
  669. unsigned y;
  670. unsigned long diff = ilinebits - olinebits;
  671. unsigned long obp = 0, ibp = 0; /*bit pointers */
  672. for (y = 0; y < h; y++) {
  673. unsigned long x;
  674. for (x = 0; x < olinebits; x++) {
  675. unsigned char bit = (unsigned char)((in[(ibp) >> 3] >> (7 - ((ibp) & 0x7))) & 1);
  676. ibp++;
  677. if (bit == 0)
  678. out[(obp) >> 3] &= (unsigned char)(~(1 << (7 - ((obp) & 0x7))));
  679. else
  680. out[(obp) >> 3] |= (1 << (7 - ((obp) & 0x7)));
  681. ++obp;
  682. }
  683. ibp += diff;
  684. }
  685. }
  686. /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from the IDAT chunks*/
  687. static void post_process_scanlines(upng_t* upng, unsigned char *out, unsigned char *in, const upng_t* info_png)
  688. {
  689. unsigned bpp = upng_get_bpp(info_png);
  690. unsigned w = info_png->width;
  691. unsigned h = info_png->height;
  692. if (bpp == 0) {
  693. SET_ERROR(upng, UPNG_EMALFORMED);
  694. return;
  695. }
  696. if (bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) {
  697. unfilter(upng, in, in, w, h, bpp);
  698. if (upng->error != UPNG_EOK) {
  699. return;
  700. }
  701. remove_padding_bits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
  702. } else {
  703. unfilter(upng, out, in, w, h, bpp); /*we can immediatly filter into the out buffer, no other steps needed */
  704. }
  705. }
  706. static upng_format determine_format(upng_t* upng) {
  707. switch (upng->color_type) {
  708. case UPNG_LUM:
  709. switch (upng->color_depth) {
  710. case 1:
  711. return UPNG_LUMINANCE1;
  712. case 2:
  713. return UPNG_LUMINANCE2;
  714. case 4:
  715. return UPNG_LUMINANCE4;
  716. case 8:
  717. return UPNG_LUMINANCE8;
  718. default:
  719. return UPNG_BADFORMAT;
  720. }
  721. case UPNG_RGB:
  722. switch (upng->color_depth) {
  723. case 8:
  724. return UPNG_RGB8;
  725. case 16:
  726. return UPNG_RGB16;
  727. default:
  728. return UPNG_BADFORMAT;
  729. }
  730. case UPNG_LUMA:
  731. switch (upng->color_depth) {
  732. case 1:
  733. return UPNG_LUMINANCE_ALPHA1;
  734. case 2:
  735. return UPNG_LUMINANCE_ALPHA2;
  736. case 4:
  737. return UPNG_LUMINANCE_ALPHA4;
  738. case 8:
  739. return UPNG_LUMINANCE_ALPHA8;
  740. default:
  741. return UPNG_BADFORMAT;
  742. }
  743. case UPNG_RGBA:
  744. switch (upng->color_depth) {
  745. case 8:
  746. return UPNG_RGBA8;
  747. case 16:
  748. return UPNG_RGBA16;
  749. default:
  750. return UPNG_BADFORMAT;
  751. }
  752. default:
  753. return UPNG_BADFORMAT;
  754. }
  755. }
  756. static void upng_free_source(upng_t* upng)
  757. {
  758. if (upng->source.owning != 0) {
  759. free((void*)upng->source.buffer);
  760. }
  761. upng->source.buffer = NULL;
  762. upng->source.size = 0;
  763. upng->source.owning = 0;
  764. }
  765. /*read the information from the header and store it in the upng_Info. return value is error*/
  766. upng_error upng_header(upng_t* upng)
  767. {
  768. /* if we have an error state, bail now */
  769. if (upng->error != UPNG_EOK) {
  770. return upng->error;
  771. }
  772. /* if the state is not NEW (meaning we are ready to parse the header), stop now */
  773. if (upng->state != UPNG_NEW) {
  774. return upng->error;
  775. }
  776. /* minimum length of a valid PNG file is 29 bytes
  777. * FIXME: verify this against the specification, or
  778. * better against the actual code below */
  779. if (upng->source.size < 29) {
  780. SET_ERROR(upng, UPNG_ENOTPNG);
  781. return upng->error;
  782. }
  783. /* check that PNG header matches expected value */
  784. if (upng->source.buffer[0] != 137 || upng->source.buffer[1] != 80 || upng->source.buffer[2] != 78 || upng->source.buffer[3] != 71 || upng->source.buffer[4] != 13 || upng->source.buffer[5] != 10 || upng->source.buffer[6] != 26 || upng->source.buffer[7] != 10) {
  785. SET_ERROR(upng, UPNG_ENOTPNG);
  786. return upng->error;
  787. }
  788. /* check that the first chunk is the IHDR chunk */
  789. if (MAKE_DWORD_PTR(upng->source.buffer + 12) != CHUNK_IHDR) {
  790. SET_ERROR(upng, UPNG_EMALFORMED);
  791. return upng->error;
  792. }
  793. /* read the values given in the header */
  794. upng->width = MAKE_DWORD_PTR(upng->source.buffer + 16);
  795. upng->height = MAKE_DWORD_PTR(upng->source.buffer + 20);
  796. upng->color_depth = upng->source.buffer[24];
  797. upng->color_type = (upng_color)upng->source.buffer[25];
  798. /* determine our color format */
  799. upng->format = determine_format(upng);
  800. if (upng->format == UPNG_BADFORMAT) {
  801. SET_ERROR(upng, UPNG_EUNFORMAT);
  802. return upng->error;
  803. }
  804. /* check that the compression method (byte 27) is 0 (only allowed value in spec) */
  805. if (upng->source.buffer[26] != 0) {
  806. SET_ERROR(upng, UPNG_EMALFORMED);
  807. return upng->error;
  808. }
  809. /* check that the compression method (byte 27) is 0 (only allowed value in spec) */
  810. if (upng->source.buffer[27] != 0) {
  811. SET_ERROR(upng, UPNG_EMALFORMED);
  812. return upng->error;
  813. }
  814. /* check that the compression method (byte 27) is 0 (spec allows 1, but uPNG does not support it) */
  815. if (upng->source.buffer[28] != 0) {
  816. SET_ERROR(upng, UPNG_EUNINTERLACED);
  817. return upng->error;
  818. }
  819. upng->state = UPNG_HEADER;
  820. return upng->error;
  821. }
  822. /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
  823. upng_error upng_decode(upng_t* upng)
  824. {
  825. const unsigned char *chunk;
  826. unsigned char* compressed;
  827. unsigned char* inflated;
  828. unsigned long compressed_size = 0, compressed_index = 0;
  829. unsigned long inflated_size;
  830. upng_error error;
  831. /* if we have an error state, bail now */
  832. if (upng->error != UPNG_EOK) {
  833. return upng->error;
  834. }
  835. /* parse the main header, if necessary */
  836. upng_header(upng);
  837. if (upng->error != UPNG_EOK) {
  838. return upng->error;
  839. }
  840. /* if the state is not HEADER (meaning we are ready to decode the image), stop now */
  841. if (upng->state != UPNG_HEADER) {
  842. return upng->error;
  843. }
  844. /* release old result, if any */
  845. if (upng->buffer != 0) {
  846. free(upng->buffer);
  847. upng->buffer = 0;
  848. upng->size = 0;
  849. }
  850. /* first byte of the first chunk after the header */
  851. chunk = upng->source.buffer + 33;
  852. /* scan through the chunks, finding the size of all IDAT chunks, and also
  853. * verify general well-formed-ness */
  854. while (chunk < upng->source.buffer + upng->source.size) {
  855. unsigned long length;
  856. const unsigned char *data; /*the data in the chunk */
  857. /* make sure chunk header is not larger than the total compressed */
  858. if ((unsigned long)(chunk - upng->source.buffer + 12) > upng->source.size) {
  859. SET_ERROR(upng, UPNG_EMALFORMED);
  860. return upng->error;
  861. }
  862. /* get length; sanity check it */
  863. length = upng_chunk_length(chunk);
  864. if (length > INT_MAX) {
  865. SET_ERROR(upng, UPNG_EMALFORMED);
  866. return upng->error;
  867. }
  868. /* make sure chunk header+paylaod is not larger than the total compressed */
  869. if ((unsigned long)(chunk - upng->source.buffer + length + 12) > upng->source.size) {
  870. SET_ERROR(upng, UPNG_EMALFORMED);
  871. return upng->error;
  872. }
  873. /* get pointer to payload */
  874. data = chunk + 8;
  875. /* parse chunks */
  876. if (upng_chunk_type(chunk) == CHUNK_IDAT) {
  877. compressed_size += length;
  878. } else if (upng_chunk_type(chunk) == CHUNK_IEND) {
  879. break;
  880. } else if (upng_chunk_critical(chunk)) {
  881. SET_ERROR(upng, UPNG_EUNSUPPORTED);
  882. return upng->error;
  883. }
  884. chunk += upng_chunk_length(chunk) + 12;
  885. }
  886. /* allocate enough space for the (compressed and filtered) image data */
  887. compressed = (unsigned char*)malloc(compressed_size);
  888. if (compressed == NULL) {
  889. SET_ERROR(upng, UPNG_ENOMEM);
  890. return upng->error;
  891. }
  892. /* scan through the chunks again, this time copying the values into
  893. * our compressed buffer. there's no reason to validate anything a second time. */
  894. chunk = upng->source.buffer + 33;
  895. while (chunk < upng->source.buffer + upng->source.size) {
  896. unsigned long length;
  897. const unsigned char *data; /*the data in the chunk */
  898. length = upng_chunk_length(chunk);
  899. data = chunk + 8;
  900. /* parse chunks */
  901. if (upng_chunk_type(chunk) == CHUNK_IDAT) {
  902. memcpy(compressed + compressed_index, data, length);
  903. compressed_index += length;
  904. } else if (upng_chunk_type(chunk) == CHUNK_IEND) {
  905. break;
  906. }
  907. chunk += upng_chunk_length(chunk) + 12;
  908. }
  909. /* allocate space to store inflated (but still filtered) data */
  910. inflated_size = ((upng->width * (upng->height * upng_get_bpp(upng) + 7)) / 8) + upng->height;
  911. inflated = (unsigned char*)malloc(inflated_size);
  912. if (inflated == NULL) {
  913. free(compressed);
  914. SET_ERROR(upng, UPNG_ENOMEM);
  915. return upng->error;
  916. }
  917. /* decompress image data */
  918. error = uz_inflate(upng, inflated, inflated_size, compressed, compressed_size);
  919. if (error != UPNG_EOK) {
  920. free(compressed);
  921. free(inflated);
  922. return upng->error;
  923. }
  924. /* free the compressed compressed data */
  925. free(compressed);
  926. /* allocate final image buffer */
  927. upng->size = (upng->height * upng->width * upng_get_bpp(upng) + 7) / 8;
  928. upng->buffer = (unsigned char*)malloc(upng->size);
  929. if (upng->buffer == NULL) {
  930. free(inflated);
  931. upng->size = 0;
  932. SET_ERROR(upng, UPNG_ENOMEM);
  933. return upng->error;
  934. }
  935. /* unfilter scanlines */
  936. post_process_scanlines(upng, upng->buffer, inflated, upng);
  937. free(inflated);
  938. if (upng->error != UPNG_EOK) {
  939. free(upng->buffer);
  940. upng->buffer = NULL;
  941. upng->size = 0;
  942. } else {
  943. upng->state = UPNG_DECODED;
  944. }
  945. /* we are done with our input buffer; free it if we own it */
  946. upng_free_source(upng);
  947. return upng->error;
  948. }
  949. static upng_t* upng_new(void)
  950. {
  951. upng_t* upng;
  952. upng = (upng_t*)malloc(sizeof(upng_t));
  953. if (upng == NULL) {
  954. return NULL;
  955. }
  956. upng->buffer = NULL;
  957. upng->size = 0;
  958. upng->width = upng->height = 0;
  959. upng->color_type = UPNG_RGBA;
  960. upng->color_depth = 8;
  961. upng->format = UPNG_RGBA8;
  962. upng->state = UPNG_NEW;
  963. upng->error = UPNG_EOK;
  964. upng->error_line = 0;
  965. upng->source.buffer = NULL;
  966. upng->source.size = 0;
  967. upng->source.owning = 0;
  968. return upng;
  969. }
  970. upng_t* upng_new_from_bytes(const unsigned char* buffer, unsigned long size)
  971. {
  972. upng_t* upng = upng_new();
  973. if (upng == NULL) {
  974. return NULL;
  975. }
  976. upng->source.buffer = buffer;
  977. upng->source.size = size;
  978. upng->source.owning = 0;
  979. return upng;
  980. }
  981. upng_t* upng_new_from_file(const char *filename)
  982. {
  983. upng_t* upng;
  984. unsigned char *buffer;
  985. FILE *file;
  986. long size;
  987. upng = upng_new();
  988. if (upng == NULL) {
  989. return NULL;
  990. }
  991. file = fopen(filename, "rb");
  992. if (file == NULL) {
  993. SET_ERROR(upng, UPNG_ENOTFOUND);
  994. return upng;
  995. }
  996. /* get filesize */
  997. fseek(file, 0, SEEK_END);
  998. size = ftell(file);
  999. rewind(file);
  1000. /* read contents of the file into the vector */
  1001. buffer = (unsigned char *)malloc((unsigned long)size);
  1002. if (buffer == NULL) {
  1003. fclose(file);
  1004. SET_ERROR(upng, UPNG_ENOMEM);
  1005. return upng;
  1006. }
  1007. fread(buffer, 1, (unsigned long)size, file);
  1008. fclose(file);
  1009. /* set the read buffer as our source buffer, with owning flag set */
  1010. upng->source.buffer = buffer;
  1011. upng->source.size = size;
  1012. upng->source.owning = 1;
  1013. return upng;
  1014. }
  1015. void upng_free(upng_t* upng)
  1016. {
  1017. /* deallocate image buffer */
  1018. if (upng->buffer != NULL) {
  1019. free(upng->buffer);
  1020. }
  1021. /* deallocate source buffer, if necessary */
  1022. upng_free_source(upng);
  1023. /* deallocate struct itself */
  1024. free(upng);
  1025. }
  1026. upng_error upng_get_error(const upng_t* upng)
  1027. {
  1028. return upng->error;
  1029. }
  1030. unsigned upng_get_error_line(const upng_t* upng)
  1031. {
  1032. return upng->error_line;
  1033. }
  1034. unsigned upng_get_width(const upng_t* upng)
  1035. {
  1036. return upng->width;
  1037. }
  1038. unsigned upng_get_height(const upng_t* upng)
  1039. {
  1040. return upng->height;
  1041. }
  1042. unsigned upng_get_bpp(const upng_t* upng)
  1043. {
  1044. return upng_get_bitdepth(upng) * upng_get_components(upng);
  1045. }
  1046. unsigned upng_get_components(const upng_t* upng)
  1047. {
  1048. switch (upng->color_type) {
  1049. case UPNG_LUM:
  1050. return 1;
  1051. case UPNG_RGB:
  1052. return 3;
  1053. case UPNG_LUMA:
  1054. return 2;
  1055. case UPNG_RGBA:
  1056. return 4;
  1057. default:
  1058. return 0;
  1059. }
  1060. }
  1061. unsigned upng_get_bitdepth(const upng_t* upng)
  1062. {
  1063. return upng->color_depth;
  1064. }
  1065. unsigned upng_get_pixelsize(const upng_t* upng)
  1066. {
  1067. unsigned bits = upng_get_bitdepth(upng) * upng_get_components(upng);
  1068. bits += bits % 8;
  1069. return bits;
  1070. }
  1071. upng_format upng_get_format(const upng_t* upng)
  1072. {
  1073. return upng->format;
  1074. }
  1075. const unsigned char* upng_get_buffer(const upng_t* upng)
  1076. {
  1077. return upng->buffer;
  1078. }
  1079. unsigned upng_get_size(const upng_t* upng)
  1080. {
  1081. return upng->size;
  1082. }