Chameleon

Chameleon Svn Source Tree

Root/branches/chucko/i386/boot2/picopng.c

1// picoPNG version 20080503 (cleaned up and ported to c by kaitek)
2// Copyright (c) 2005-2008 Lode Vandevenne
3//
4// This software is provided 'as-is', without any express or implied
5// warranty. In no event will the authors be held liable for any damages
6// arising from the use of this software.
7//
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//
12// 1. The origin of this software must not be misrepresented; you must not
13// claim that you wrote the original software. If you use this software
14// in a product, an acknowledgment in the product documentation would be
15// appreciated but is not required.
16// 2. Altered source versions must be plainly marked as such, and must not be
17// misrepresented as being the original software.
18// 3. This notice may not be removed or altered from any source distribution.
19
20#include <sys/types.h>
21#include "libsa.h"
22#include "picopng.h"
23
24/*************************************************************************************************/
25
26typedef struct png_alloc_node {
27struct png_alloc_node *prev, *next;
28void *addr;
29size_t size;
30} png_alloc_node_t;
31
32png_alloc_node_t *png_alloc_head = NULL;
33png_alloc_node_t *png_alloc_tail = NULL;
34
35png_alloc_node_t *png_alloc_find_node(void *addr)
36{
37png_alloc_node_t *node;
38for (node = png_alloc_head; node; node = node->next)
39if (node->addr == addr)
40break;
41return node;
42}
43
44void png_alloc_add_node(void *addr, size_t size)
45{
46png_alloc_node_t *node;
47if (png_alloc_find_node(addr))
48return;
49node = malloc(sizeof (png_alloc_node_t));
50node->addr = addr;
51node->size = size;
52node->prev = png_alloc_tail;
53node->next = NULL;
54png_alloc_tail = node;
55if (node->prev)
56node->prev->next = node;
57if (!png_alloc_head)
58png_alloc_head = node;
59}
60
61void png_alloc_remove_node(png_alloc_node_t *node)
62{
63if (!node) {
64return;
65}
66if (node->prev) {
67node->prev->next = node->next;
68}
69if (node->next) {
70node->next->prev = node->prev;
71}
72if (node == png_alloc_head) {
73png_alloc_head = node->next;
74}
75if (node == png_alloc_tail) {
76png_alloc_tail = node->prev;
77}
78node->prev = node->next = node->addr = NULL;
79free(node);
80}
81
82void *png_alloc_malloc(size_t size)
83{
84void *addr = malloc(size);
85png_alloc_add_node(addr, size);
86return addr;
87}
88
89void *png_alloc_realloc(void *addr, size_t size)
90{
91void *new_addr = NULL;
92if (!addr) {
93return png_alloc_malloc(size);
94}
95
96png_alloc_node_t *old_node;
97old_node = png_alloc_find_node(addr);
98
99if (old_node)
100{
101new_addr = realloc(addr, size);
102if (new_addr && (new_addr != addr))
103{
104png_alloc_remove_node(old_node);
105png_alloc_add_node(new_addr, size);
106}
107}
108
109return new_addr;
110}
111
112void png_alloc_free(void *addr)
113{
114if (!addr) {
115return;
116}
117
118png_alloc_node_t *node = png_alloc_find_node(addr);
119if (node) {
120png_alloc_remove_node(node);
121}
122free(addr);
123}
124
125void png_alloc_free_all()
126{
127while (png_alloc_tail) {
128void *addr = png_alloc_tail->addr;
129png_alloc_remove_node(png_alloc_tail);
130free(addr);
131}
132}
133
134/*************************************************************************************************/
135
136__unused void vector32_cleanup(vector32_t *p)
137{
138p->size = p->allocsize = 0;
139if (p->data)
140png_alloc_free(p->data);
141p->data = NULL;
142}
143
144uint32_t vector32_resize(vector32_t *p, size_t size)
145{// returns 1 if success, 0 if failure ==> nothing done
146if (size * sizeof (uint32_t) > p->allocsize) {
147size_t newsize = size * sizeof (uint32_t) * 2;
148void *data = png_alloc_realloc(p->data, newsize);
149if (data) {
150p->allocsize = newsize;
151p->data = (uint32_t *) data;
152p->size = size;
153} else
154return 0;
155} else
156p->size = size;
157return 1;
158}
159
160uint32_t vector32_resizev(vector32_t *p, size_t size, uint32_t value)
161{// resize and give all new elements the value
162size_t oldsize = p->size, i;
163if (!vector32_resize(p, size))
164return 0;
165for (i = oldsize; i < size; i++)
166p->data[i] = value;
167return 1;
168}
169
170void vector32_init(vector32_t *p)
171{
172p->data = NULL;
173p->size = p->allocsize = 0;
174}
175
176vector32_t *vector32_new(size_t size, uint32_t value)
177{
178vector32_t *p = png_alloc_malloc(sizeof (vector32_t));
179if (!p) {
180return NULL;
181}
182vector32_init(p);
183if (size && !vector32_resizev(p, size, value)) {
184vector32_cleanup(p);
185png_alloc_free(p);
186return NULL;
187}
188return p;
189}
190
191/*************************************************************************************************/
192
193__unused void vector8_cleanup(vector8_t *p)
194{
195p->size = p->allocsize = 0;
196if (p->data)
197png_alloc_free(p->data);
198p->data = NULL;
199}
200
201uint32_t vector8_resize(vector8_t *p, size_t size)
202{// returns 1 if success, 0 if failure ==> nothing done
203// xxx: the use of sizeof uint32_t here seems like a bug (this descends from the lodepng vector
204// compatibility functions which do the same). without this there is corruption in certain cases,
205// so this was probably done to cover up allocation bug(s) in the original picopng code!
206if (size * sizeof (uint32_t) > p->allocsize) {
207size_t newsize = size * sizeof (uint32_t) * 2;
208void *data = png_alloc_realloc(p->data, newsize);
209if (data) {
210p->allocsize = newsize;
211p->data = (uint8_t *) data;
212p->size = size;
213} else
214return 0; // error: not enough memory
215} else
216p->size = size;
217return 1;
218}
219
220vector8_t *vector8_new(size_t size, uint8_t value)
221{
222vector8_t *p = png_alloc_malloc(sizeof (vector8_t));
223if (!p)
224 return NULL;
225p->data = NULL;
226p->size = p->allocsize = 0;
227if (size) {
228 size_t i;
229 size_t newsize = size * sizeof (uint32_t) * 2;
230 void *data = png_alloc_malloc(newsize);
231 if (!data) {
232png_alloc_free(p);
233return NULL;
234 }
235 p->data = (uint8_t *) data;
236 p->allocsize = newsize;
237 p->size = size;
238 for (i = 0; i < size; ++i)
239 p->data[i] = value;
240 }
241return p;
242}
243
244vector8_t *vector8_copy(vector8_t *p)
245{
246vector8_t *q = vector8_new(p->size, 0);
247uint32_t n;
248if (!q)
249{
250 return NULL;
251}
252for (n = 0; n < q->size; n++)
253q->data[n] = p->data[n];
254return q;
255}
256
257/*************************************************************************************************/
258
259const uint32_t LENBASE[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51,
26059, 67, 83, 99, 115, 131, 163, 195, 227, 258 };
261const uint32_t 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,
2624, 5, 5, 5, 5, 0 };
263const uint32_t DISTBASE[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385,
264513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
265const uint32_t DISTEXTRA[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
26610, 10, 11, 11, 12, 12, 13, 13 };
267// code length code lengths
268const uint32_t CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
269
270/*************************************************************************************************/
271
272typedef struct {
273// 2D representation of a huffman tree: The one dimension is "0" or "1", the other contains all
274// nodes and leaves of the tree.
275vector32_t *tree2d;
276} HuffmanTree;
277
278HuffmanTree *HuffmanTree_new()
279{
280HuffmanTree *tree = png_alloc_malloc(sizeof (HuffmanTree));
281if (!tree)
282{
283return NULL;
284}
285tree->tree2d = NULL;
286return tree;
287}
288
289int HuffmanTree_makeFromLengths(HuffmanTree *tree, const vector32_t *bitlen, uint32_t maxbitlen)
290{// make tree given the lengths
291uint32_t bits, n, i;
292uint32_t numcodes = (uint32_t) bitlen->size, treepos = 0, nodefilled = 0;
293vector32_t *tree1d, *blcount, *nextcode;
294tree1d = vector32_new(numcodes, 0);
295blcount = vector32_new(maxbitlen + 1, 0);
296nextcode = vector32_new(maxbitlen + 1, 0);
297if (!tree1d || !blcount || !nextcode || !nextcode->data)
298{
299goto error;
300}
301for (bits = 0; bits < numcodes; bits++)
302blcount->data[bitlen->data[bits]]++; // count number of instances of each code length
303for (bits = 1; bits <= maxbitlen; bits++)
304nextcode->data[bits] = (nextcode->data[bits - 1] + blcount->data[bits - 1]) << 1;
305for (n = 0; n < numcodes; n++)
306if (bitlen->data[n] != 0)
307tree1d->data[n] = nextcode->data[bitlen->data[n]]++; // generate all the codes
308// 0x7fff here means the tree2d isn't filled there yet
309vector32_t *tree2d = vector32_new(numcodes * 2, 0x7fff);
310tree->tree2d = tree2d;
311for (n = 0; n < numcodes; n++) // the codes
312for (i = 0; i < bitlen->data[n]; i++) { // the bits for this code
313uint32_t bit = (tree1d->data[n] >> (bitlen->data[n] - i - 1)) & 1;
314if (treepos > numcodes - 2)
315return 55;
316if (tree2d->data[2 * treepos + bit] == 0x7fff) { // not yet filled in
317if (i + 1 == bitlen->data[n]) { // last bit
318tree2d->data[2 * treepos + bit] = n;
319treepos = 0;
320} else { // addresses are encoded as values > numcodes
321tree2d->data[2 * treepos + bit] = ++nodefilled + numcodes;
322treepos = nodefilled;
323}
324} else // subtract numcodes from address to get address value
325treepos = tree2d->data[2 * treepos + bit] - numcodes;
326}
327return 0;
328error:
329if (tree1d)
330{
331vector32_cleanup(tree1d);
332png_alloc_free(tree1d);
333}
334if (blcount)
335{
336vector32_cleanup(blcount);
337png_alloc_free(blcount);
338}
339if (nextcode)
340{
341vector32_cleanup(nextcode);
342png_alloc_free(nextcode);
343}
344return 1;
345}
346
347int HuffmanTree_decode(const HuffmanTree *tree, bool *decoded, uint32_t *result, size_t *treepos,
348uint32_t bit)
349{// Decodes a symbol from the tree
350const vector32_t *tree2d = tree->tree2d;
351uint32_t numcodes = (uint32_t) tree2d->size / 2;
352if (*treepos >= numcodes)
353return 11; // error: you appeared outside the codetree
354*result = tree2d->data[2 * (*treepos) + bit];
355*decoded = (*result < numcodes);
356*treepos = *decoded ? 0 : *result - numcodes;
357return 0;
358}
359
360/*************************************************************************************************/
361
362int Inflator_error;
363
364uint32_t Zlib_readBitFromStream(size_t *bitp, const uint8_t *bits)
365{
366uint32_t result = (bits[*bitp >> 3] >> (*bitp & 0x7)) & 1;
367(*bitp)++;
368return result;
369}
370
371uint32_t Zlib_readBitsFromStream(size_t *bitp, const uint8_t *bits, size_t nbits)
372{
373uint32_t i, result = 0;
374for (i = 0; i < nbits; i++)
375result += (Zlib_readBitFromStream(bitp, bits)) << i;
376return result;
377}
378
379void Inflator_generateFixedTrees(HuffmanTree *tree, HuffmanTree *treeD)
380{// get the tree of a deflated block with fixed tree
381size_t i;
382vector32_t *bitlen, *bitlenD;
383bitlen = vector32_new(288, 8);
384bitlenD = vector32_new(32, 5);
385for (i = 144; i <= 255; i++)
386bitlen->data[i] = 9;
387for (i = 256; i <= 279; i++)
388bitlen->data[i] = 7;
389HuffmanTree_makeFromLengths(tree, bitlen, 15);
390HuffmanTree_makeFromLengths(treeD, bitlenD, 15);
391}
392
393uint32_t Inflator_huffmanDecodeSymbol(const uint8_t *in, size_t *bp, const HuffmanTree *codetree,
394size_t inlength)
395{// decode a single symbol from given list of bits with given code tree. returns the symbol
396bool decoded = false;
397uint32_t ct = 0;
398size_t treepos = 0;
399for (;;) {
400if ((*bp & 0x07) == 0 && (*bp >> 3) > inlength) {
401Inflator_error = 10; // error: end reached without endcode
402return 0;
403}
404Inflator_error = HuffmanTree_decode(codetree, &decoded, &ct, &treepos,
405Zlib_readBitFromStream(bp, in));
406if (Inflator_error)
407return 0; // stop, an error happened
408if (decoded)
409return ct;
410}
411}
412
413void Inflator_getTreeInflateDynamic(HuffmanTree *tree, HuffmanTree *treeD, const uint8_t *in,
414size_t *bp, size_t inlength)
415{// get the tree of a deflated block with dynamic tree, the tree itself is also Huffman
416// compressed with a known tree
417size_t i, n;
418size_t HLIT;
419size_t HDIST;
420size_t HCLEN;
421size_t replength;
422vector32_t *codelengthcode;
423HuffmanTree *codelengthcodetree = HuffmanTree_new(); // the code tree for code length codes
424vector32_t *bitlen, *bitlenD;
425bitlen = vector32_new(288, 0);
426bitlenD = vector32_new(32, 0);
427if (*bp >> 3 >= inlength - 2) {
428Inflator_error = 49; // the bit pointer is or will go past the memory
429return;
430}
431HLIT = Zlib_readBitsFromStream(bp, in, 5) + 257;// number of literal/length codes + 257
432HDIST = Zlib_readBitsFromStream(bp, in, 5) + 1;// number of dist codes + 1
433HCLEN = Zlib_readBitsFromStream(bp, in, 4) + 4;// number of code length codes + 4
434// lengths of tree to decode the lengths of the dynamic tree
435codelengthcode = vector32_new(19, 0);
436for (i = 0; i < 19; i++)
437codelengthcode->data[CLCL[i]] = (i < HCLEN) ? Zlib_readBitsFromStream(bp, in, 3) : 0;
438Inflator_error = HuffmanTree_makeFromLengths(codelengthcodetree, codelengthcode, 7);
439if (Inflator_error)
440return;
441
442for (i = 0; i < HLIT + HDIST; ) {
443uint32_t code = Inflator_huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength);
444if (Inflator_error) {
445return;
446}
447if (code <= 15) { // a length code
448if (i < HLIT) {
449bitlen->data[i++] = code;
450} else {
451bitlenD->data[i++ - HLIT] = code;
452}
453} else if (code == 16)
454{ // repeat previous
455uint32_t value; // set value to the previous code
456if (*bp >> 3 >= inlength)
457{
458Inflator_error = 50; // error, bit pointer jumps past memory
459return;
460}
461replength = 3 + Zlib_readBitsFromStream(bp, in, 2);
462
463if ((i - 1) < HLIT) {
464value = bitlen->data[i - 1];
465} else {
466value = bitlenD->data[i - HLIT - 1];
467}
468for (n = 0; n < replength; n++) { // repeat this value in the next lengths
469if (i >= HLIT + HDIST) {
470Inflator_error = 13; // error: i is larger than the amount of codes
471return;
472}
473if (i < HLIT) {
474bitlen->data[i++] = value;
475} else {
476bitlenD->data[i++ - HLIT] = value;
477}
478}
479} else if (code == 17) { // repeat "0" 3-10 times
480if (*bp >> 3 >= inlength) {
481Inflator_error = 50; // error, bit pointer jumps past memory
482return;
483}
484replength = 3 + Zlib_readBitsFromStream(bp, in, 3);
485for (n = 0; n < replength; n++) { // repeat this value in the next lengths
486if (i >= HLIT + HDIST) {
487Inflator_error = 14; // error: i is larger than the amount of codes
488return;
489}
490if (i < HLIT)
491{
492bitlen->data[i++] = 0;
493}
494else
495{
496bitlenD->data[i++ - HLIT] = 0;
497}
498}
499} else if (code == 18) { // repeat "0" 11-138 times
500if (*bp >> 3 >= inlength) {
501Inflator_error = 50; // error, bit pointer jumps past memory
502return;
503}
504replength = 11 + Zlib_readBitsFromStream(bp, in, 7);
505for (n = 0; n < replength; n++) { // repeat this value in the next lengths
506if (i >= HLIT + HDIST) {
507Inflator_error = 15; // error: i is larger than the amount of codes
508return;
509}
510if (i < HLIT)
511{
512bitlen->data[i++] = 0;
513}
514else
515{
516bitlenD->data[i++ - HLIT] = 0;
517}
518}
519} else {
520Inflator_error = 16; // error: an nonexitent code appeared. This can never happen.
521return;
522}
523}
524if (bitlen->data[256] == 0) {
525Inflator_error = 64; // the length of the end code 256 must be larger than 0
526return;
527}
528// now we've finally got HLIT and HDIST, so generate the code trees, and the function is done
529Inflator_error = HuffmanTree_makeFromLengths(tree, bitlen, 15);
530if (Inflator_error)
531return;
532Inflator_error = HuffmanTree_makeFromLengths(treeD, bitlenD, 15);
533if (Inflator_error)
534return;
535}
536
537void Inflator_inflateHuffmanBlock(vector8_t *out, const uint8_t *in, size_t *bp, size_t *pos,
538size_t inlength, uint32_t btype)
539{
540HuffmanTree *codetree, *codetreeD; // the code tree for Huffman codes, dist codes
541codetree = HuffmanTree_new();
542codetreeD = HuffmanTree_new();
543if (btype == 1)
544Inflator_generateFixedTrees(codetree, codetreeD);
545else if (btype == 2) {
546Inflator_getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength);
547if (Inflator_error)
548return;
549}
550for (;;) {
551uint32_t code = Inflator_huffmanDecodeSymbol(in, bp, codetree, inlength);
552if (Inflator_error)
553return;
554if (code == 256) // end code
555{
556return;
557}
558else if (code <= 255) { // literal symbol
559if (*pos >= out->size)
560{
561vector8_resize(out, (*pos + 1) * 2); // reserve more room
562}
563out->data[(*pos)++] = (uint8_t) code;
564} else if (code >= 257 && code <= 285)
565{ // length code
566size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257];
567if ((*bp >> 3) >= inlength)
568{
569Inflator_error = 51; // error, bit pointer will jump past memory
570return;
571}
572length += Zlib_readBitsFromStream(bp, in, numextrabits);
573uint32_t codeD = Inflator_huffmanDecodeSymbol(in, bp, codetreeD, inlength);
574if (Inflator_error)
575return;
576if (codeD > 29) {
577Inflator_error = 18; // error: invalid dist code (30-31 are never used)
578return;
579}
580uint32_t dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD];
581if ((*bp >> 3) >= inlength) {
582Inflator_error = 51; // error, bit pointer will jump past memory
583return;
584}
585dist += Zlib_readBitsFromStream(bp, in, numextrabitsD);
586size_t start = *pos, back = start - dist; // backwards
587if (*pos + length >= out->size)
588vector8_resize(out, (*pos + length) * 2); // reserve more room
589size_t i;
590for (i = 0; i < length; i++) {
591out->data[(*pos)++] = out->data[back++];
592if (back >= start)
593back = start - dist;
594}
595}
596}
597}
598
599void Inflator_inflateNoCompression(vector8_t *out, const uint8_t *in, size_t *bp, size_t *pos,
600size_t inlength)
601{
602while ((*bp & 0x7) != 0)
603(*bp)++; // go to first boundary of byte
604size_t p = *bp / 8;
605if (p >= inlength - 4) {
606Inflator_error = 52; // error, bit pointer will jump past memory
607return;
608}
609uint32_t LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3];
610p += 4;
611if (LEN + NLEN != 65535) {
612Inflator_error = 21; // error: NLEN is not one's complement of LEN
613return;
614}
615if (*pos + LEN >= out->size)
616vector8_resize(out, *pos + LEN);
617if (p + LEN > inlength) {
618Inflator_error = 23; // error: reading outside of in buffer
619return;
620}
621uint32_t n;
622for (n = 0; n < LEN; n++)
623out->data[(*pos)++] = in[p++]; // read LEN bytes of literal data
624*bp = p * 8;
625}
626
627void Inflator_inflate(vector8_t *out, const vector8_t *in, size_t inpos)
628{
629size_t bp = 0, pos = 0; // bit pointer and byte pointer
630Inflator_error = 0;
631uint32_t BFINAL = 0;
632while (!BFINAL && !Inflator_error) {
633if (bp >> 3 >= in->size) {
634Inflator_error = 52; // error, bit pointer will jump past memory
635return;
636}
637BFINAL = Zlib_readBitFromStream(&bp, &in->data[inpos]);
638uint32_t BTYPE = Zlib_readBitFromStream(&bp, &in->data[inpos]);
639BTYPE += 2 * Zlib_readBitFromStream(&bp, &in->data[inpos]);
640if (BTYPE == 3) {
641Inflator_error = 20; // error: invalid BTYPE
642return;
643}
644else if (BTYPE == 0)
645Inflator_inflateNoCompression(out, &in->data[inpos], &bp, &pos, in->size);
646else
647Inflator_inflateHuffmanBlock(out, &in->data[inpos], &bp, &pos, in->size, BTYPE);
648}
649if (!Inflator_error)
650vector8_resize(out, pos); // Only now we know the true size of out, resize it to that
651}
652
653/*************************************************************************************************/
654
655int Zlib_decompress(vector8_t *out, const vector8_t *in) // returns error value
656{
657if (in->size < 2)
658return 53; // error, size of zlib data too small
659if ((in->data[0] * 256 + in->data[1]) % 31 != 0)
660// error: 256 * in->data[0] + in->data[1] must be a multiple of 31, the FCHECK value is
661// supposed to be made that way
662return 24;
663uint32_t CM = in->data[0] & 15, CINFO = (in->data[0] >> 4) & 15, FDICT = (in->data[1] >> 5) & 1;
664if (CM != 8 || CINFO > 7){
665// error: only compression method 8: inflate with sliding window of 32k is supported by
666// the PNG spec
667
668return 25;
669}
670if (FDICT != 0) {
671// error: the specification of PNG says about the zlib stream: "The additional flags shall
672// not specify a preset dictionary."
673return 26;
674}
675Inflator_inflate(out, in, 2);
676return Inflator_error; // note: adler32 checksum was skipped and ignored
677}
678
679/*************************************************************************************************/
680
681#define PNG_SIGNATURE0x0a1a0a0d474e5089ull
682
683#define CHUNK_IHDR0x52444849
684#define CHUNK_IDAT0x54414449
685#define CHUNK_IEND0x444e4549
686#define CHUNK_PLTE0x45544c50
687#define CHUNK_tRNS0x534e5274
688
689int PNG_error;
690
691uint32_t PNG_readBitFromReversedStream(size_t *bitp, const uint8_t *bits)
692{
693uint32_t result = (bits[*bitp >> 3] >> (7 - (*bitp & 0x7))) & 1;
694(*bitp)++;
695return result;
696}
697
698uint32_t PNG_readBitsFromReversedStream(size_t *bitp, const uint8_t *bits, uint32_t nbits)
699{
700uint32_t i, result = 0;
701for (i = nbits - 1; i < nbits; i--)
702result += ((PNG_readBitFromReversedStream(bitp, bits)) << i);
703return result;
704}
705
706void PNG_setBitOfReversedStream(size_t *bitp, uint8_t *bits, uint32_t bit)
707{
708bits[*bitp >> 3] |= (bit << (7 - (*bitp & 0x7)));
709(*bitp)++;
710}
711
712uint32_t PNG_read32bitInt(const uint8_t *buffer)
713{
714return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
715}
716
717int PNG_checkColorValidity(uint32_t colorType, uint32_t bd) // return type is a LodePNG error code
718{
719if ((colorType == 2 || colorType == 4 || colorType == 6)) {
720if (!(bd == 8 || bd == 16))
721return 37;
722else
723return 0;
724} else if (colorType == 0) {
725if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16))
726return 37;
727else
728return 0;
729} else if (colorType == 3) {
730if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8))
731return 37;
732else
733return 0;
734} else
735return 31; // nonexistent color type
736}
737
738uint32_t PNG_getBpp(const PNG_info_t *info)
739{
740uint32_t bitDepth, colorType;
741bitDepth = info->bitDepth;
742colorType = info->colorType;
743if (colorType == 2)
744{
745return (3 * bitDepth);
746}
747else if (colorType >= 4)
748{
749return (colorType - 2) * bitDepth;
750}
751else
752{
753return bitDepth;
754}
755}
756
757void PNG_readPngHeader(PNG_info_t *info, const uint8_t *in, size_t inlength)
758{// read the information from the header and store it in the Info
759if (inlength < 29) {
760PNG_error = 27; // error: the data length is smaller than the length of the header
761return;
762}
763if (*(uint64_t *) in != PNG_SIGNATURE) {
764PNG_error = 28; // no PNG signature
765return;
766}
767if (*(uint32_t *) &in[12] != CHUNK_IHDR) {
768PNG_error = 29; // error: it doesn't start with a IHDR chunk!
769return;
770}
771info->width = PNG_read32bitInt(&in[16]);
772info->height = PNG_read32bitInt(&in[20]);
773info->bitDepth = in[24];
774info->colorType = in[25];
775info->compressionMethod = in[26];
776if (in[26] != 0) {
777PNG_error = 32; // error: only compression method 0 is allowed in the specification
778return;
779}
780info->filterMethod = in[27];
781if (in[27] != 0) {
782PNG_error = 33; // error: only filter method 0 is allowed in the specification
783return;
784}
785info->interlaceMethod = in[28];
786if (in[28] > 1) {
787PNG_error = 34; // error: only interlace methods 0 and 1 exist in the specification
788return;
789}
790PNG_error = PNG_checkColorValidity(info->colorType, info->bitDepth);
791}
792
793int PNG_paethPredictor(int a, int b, int c) // Paeth predicter, used by PNG filter type 4
794{
795int p, pa, pb, pc;
796p = a + b - c;
797pa = p > a ? (p - a) : (a - p);
798pb = p > b ? (p - b) : (b - p);
799pc = p > c ? (p - c) : (c - p);
800return (pa <= pb && pa <= pc) ? a : (pb <= pc ? b : c);
801}
802
803void PNG_unFilterScanline(uint8_t *recon, const uint8_t *scanline, const uint8_t *precon,
804size_t bytewidth, uint32_t filterType, size_t length)
805{
806size_t i;
807switch (filterType) {
808case 0:
809for (i = 0; i < length; i++)
810recon[i] = scanline[i];
811break;
812case 1:
813for (i = 0; i < bytewidth; i++)
814recon[i] = scanline[i];
815for (i = bytewidth; i < length; i++)
816recon[i] = scanline[i] + recon[i - bytewidth];
817break;
818case 2:
819if (precon)
820for (i = 0; i < length; i++)
821recon[i] = scanline[i] + precon[i];
822else
823for (i = 0; i < length; i++)
824recon[i] = scanline[i];
825break;
826case 3:
827if (precon) {
828for (i = 0; i < bytewidth; i++)
829recon[i] = scanline[i] + precon[i] / 2;
830for (i = bytewidth; i < length; i++)
831recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
832} else {
833for (i = 0; i < bytewidth; i++)
834recon[i] = scanline[i];
835for (i = bytewidth; i < length; i++)
836recon[i] = scanline[i] + recon[i - bytewidth] / 2;
837}
838break;
839case 4:
840if (precon) {
841for (i = 0; i < bytewidth; i++)
842recon[i] = (uint8_t) (scanline[i] + PNG_paethPredictor(0, precon[i], 0));
843for (i = bytewidth; i < length; i++)
844recon[i] = (uint8_t) (scanline[i] + PNG_paethPredictor(recon[i - bytewidth],
845precon[i], precon[i - bytewidth]));
846} else {
847for (i = 0; i < bytewidth; i++)
848recon[i] = scanline[i];
849for (i = bytewidth; i < length; i++)
850recon[i] = (uint8_t) (scanline[i] + PNG_paethPredictor(recon[i - bytewidth], 0, 0));
851}
852break;
853default:
854PNG_error = 36; // error: nonexistent filter type given
855return;
856}
857}
858
859void PNG_adam7Pass(uint8_t *out, uint8_t *linen, uint8_t *lineo, const uint8_t *in, uint32_t w,
860size_t passleft, size_t passtop, size_t spacex, size_t spacey, size_t passw, size_t passh,
861uint32_t bpp)
862{// filter and reposition the pixels into the output when the image is Adam7 interlaced. This
863// function can only do it after the full image is already decoded. The out buffer must have
864// the correct allocated memory size already.
865if (passw == 0)
866return;
867size_t bytewidth = (bpp + 7) / 8, linelength = 1 + ((bpp * passw + 7) / 8);
868uint32_t y;
869for (y = 0; y < passh; y++) {
870size_t i, b;
871uint8_t filterType = in[y * linelength], *prevline = (y == 0) ? 0 : lineo;
872PNG_unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType,
873(w * bpp + 7) / 8);
874if (PNG_error)
875return;
876if (bpp >= 8)
877for (i = 0; i < passw; i++)
878for (b = 0; b < bytewidth; b++) // b = current byte of this pixel
879out[bytewidth * w * (passtop + spacey * y) + bytewidth *
880(passleft + spacex * i) + b] = linen[bytewidth * i + b];
881else
882for (i = 0; i < passw; i++) {
883size_t obp, bp;
884obp = bpp * w * (passtop + spacey * y) + bpp * (passleft + spacex * i);
885bp = i * bpp;
886for (b = 0; b < bpp; b++)
887PNG_setBitOfReversedStream(&obp, out, PNG_readBitFromReversedStream(&bp, linen));
888}
889uint8_t *temp = linen;
890linen = lineo;
891lineo = temp; // swap the two buffer pointers "line old" and "line new"
892}
893}
894
895int PNG_convert(const PNG_info_t *info, vector8_t *out, const uint8_t *in)
896{// converts from any color type to 32-bit. return value = LodePNG error code
897size_t i, c;
898size_t numpixels = info->width * info->height;
899 if (!numpixels)
900 return 0; // nothing to do
901if (!vector8_resize(out, numpixels * 4))
902 return 83; // out of memory
903 size_t bp = 0;
904uint32_t bitDepth = info->bitDepth;
905uint32_t colorType = info->colorType;
906uint8_t *out_data = out->data;
907if (bitDepth == 8 && colorType == 0) // greyscale
908for (i = 0; i < numpixels; i++) {
909out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[i];
910out_data[4 * i + 3] = (info->key_defined && (in[i] == info->key_r)) ? 0 : 255;
911}
912else if (bitDepth == 8 && colorType == 2) // RGB color
913for (i = 0; i < numpixels; i++) {
914for (c = 0; c < 3; c++)
915out_data[4 * i + c] = in[3 * i + c];
916out_data[4 * i + 3] = (info->key_defined && (in[3 * i + 0] == info->key_r) &&
917(in[3 * i + 1] == info->key_g) && (in[3 * i + 2] == info->key_b)) ? 0 : 255;
918}
919else if (bitDepth == 8 && colorType == 3) // indexed color (palette)
920for (i = 0; i < numpixels; i++) {
921if (4U * in[i] >= info->palette->size)
922return 46;
923for (c = 0; c < 4; c++) // get rgb colors from the palette
924out_data[4 * i + c] = info->palette->data[4 * in[i] + c];
925}
926else if (bitDepth == 8 && colorType == 4) // greyscale with alpha
927for (i = 0; i < numpixels; i++) {
928out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[2 * i + 0];
929out_data[4 * i + 3] = in[2 * i + 1];
930}
931else if (bitDepth == 8 && colorType == 6)
932for (i = 0; i < numpixels; i++)
933for (c = 0; c < 4; c++)
934out_data[4 * i + c] = in[4 * i + c]; // RGB with alpha
935else if (bitDepth == 16 && colorType == 0) // greyscale
936for (i = 0; i < numpixels; i++) {
937out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[2 * i];
938out_data[4 * i + 3] = (info->key_defined && (256U * in[i] + in[i + 1] == info->key_r))
939? 0 : 255;
940}
941else if (bitDepth == 16 && colorType == 2) // RGB color
942for (i = 0; i < numpixels; i++) {
943for (c = 0; c < 3; c++)
944out_data[4 * i + c] = in[6 * i + 2 * c];
945out_data[4 * i + 3] = (info->key_defined &&
946(256U * in[6 * i + 0] + in[6 * i + 1] == info->key_r) &&
947(256U * in[6 * i + 2] + in[6 * i + 3] == info->key_g) &&
948(256U * in[6 * i + 4] + in[6 * i + 5] == info->key_b)) ? 0 : 255;
949}
950else if (bitDepth == 16 && colorType == 4) // greyscale with alpha
951for (i = 0; i < numpixels; i++) {
952out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[4 * i]; // msb
953out_data[4 * i + 3] = in[4 * i + 2];
954}
955else if (bitDepth == 16 && colorType == 6)
956for (i = 0; i < numpixels; i++)
957for (c = 0; c < 4; c++)
958out_data[4 * i + c] = in[8 * i + 2 * c]; // RGB with alpha
959else if (bitDepth < 8 && colorType == 0) // greyscale
960for (i = 0; i < numpixels; i++) {
961uint32_t value = (PNG_readBitsFromReversedStream(&bp, in, bitDepth) * 255) /
962((1 << bitDepth) - 1); // scale value from 0 to 255
963out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = (uint8_t) value;
964out_data[4 * i + 3] = (info->key_defined && value &&
965(((1U << bitDepth) - 1U) == info->key_r) && ((1U << bitDepth) - 1U)) ? 0 : 255;
966}
967else if (bitDepth < 8 && colorType == 3) // palette
968for (i = 0; i < numpixels; i++) {
969uint32_t value = PNG_readBitsFromReversedStream(&bp, in, bitDepth);
970if (4 * value >= info->palette->size)
971return 47;
972for (c = 0; c < 4; c++) // get rgb colors from the palette
973out_data[4 * i + c] = info->palette->data[4 * value + c];
974}
975return 0;
976}
977
978PNG_info_t *PNG_info_new()
979{
980PNG_info_t *info = png_alloc_malloc(sizeof (PNG_info_t));
981if (!info)
982{
983return NULL;
984}
985uint32_t i;
986for (i = 0; i < sizeof (PNG_info_t); i++)
987((uint8_t *) info)[i] = 0;
988info->palette = vector8_new(0, 0);
989info->image = vector8_new(0, 0);
990return info;
991}
992
993PNG_info_t *PNG_decode(const uint8_t *in, uint32_t size)
994{
995PNG_info_t *info;
996PNG_error = 0;
997if (size == 0 || in == 0) {
998PNG_error = 48; // the given data is empty
999return NULL;
1000}
1001info = PNG_info_new();
1002PNG_readPngHeader(info, in, size);
1003if (PNG_error)
1004return NULL;
1005size_t pos = 33; // first byte of the first chunk after the header
1006vector8_t *idat = NULL; // the data from idat chunks
1007bool IEND = false;
1008info->key_defined = false;
1009// loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is
1010// put at the start of the in buffer
1011while (!IEND) {
1012size_t i;
1013if (pos + 8 >= size) {
1014PNG_error = 30; // error: size of the in buffer too small to contain next chunk
1015return NULL;
1016}
1017size_t chunkLength = PNG_read32bitInt(&in[pos]);
1018pos += 4;
1019if (chunkLength > 0x7fffffff) {
1020PNG_error = 63;
1021return NULL;
1022}
1023if (pos + chunkLength >= size) {
1024PNG_error = 35; // error: size of the in buffer too small to contain next chunk
1025return NULL;
1026}
1027uint32_t chunkType = *(uint32_t *) &in[pos];
1028if (chunkType == CHUNK_IDAT) { // IDAT: compressed image data chunk
1029size_t offset = 0;
1030if (idat) {
1031offset = idat->size;
1032vector8_resize(idat, offset + chunkLength);
1033} else
1034idat = vector8_new(chunkLength, 0);
1035
1036if (!idat)
1037{
1038PNG_error = 1;
1039return NULL;
1040}
1041for (i = 0; i < chunkLength; i++)
1042idat->data[offset + i] = in[pos + 4 + i];
1043pos += (4 + chunkLength);
1044} else if (chunkType == CHUNK_IEND) { // IEND
1045pos += 4;
1046IEND = true;
1047} else if (chunkType == CHUNK_PLTE) { // PLTE: palette chunk
1048pos += 4; // go after the 4 letters
1049vector8_resize(info->palette, 4 * (chunkLength / 3));
1050if (info->palette->size > (4 * 256)) {
1051PNG_error = 38; // error: palette too big
1052return NULL;
1053}
1054for (i = 0; i < info->palette->size; i += 4) {
1055 size_t j;
1056for (j = 0; j < 3; j++)
1057info->palette->data[i + j] = in[pos++]; // RGB
1058info->palette->data[i + 3] = 255; // alpha
1059}
1060} else if (chunkType == CHUNK_tRNS) { // tRNS: palette transparency chunk
1061pos += 4; // go after the 4 letters
1062if (info->colorType == 3) {
1063if (4 * chunkLength > info->palette->size) {
1064PNG_error = 39; // error: more alpha values given than there are palette entries
1065return NULL;
1066}
1067for (i = 0; i < chunkLength; i++)
1068info->palette->data[4 * i + 3] = in[pos++];
1069} else if (info->colorType == 0) {
1070if (chunkLength != 2) {
1071PNG_error = 40; // error: this chunk must be 2 bytes for greyscale image
1072return NULL;
1073}
1074info->key_defined = true;
1075info->key_r = info->key_g = info->key_b = 256 * in[pos] + in[pos + 1];
1076pos += 2;
1077} else if (info->colorType == 2) {
1078if (chunkLength != 6) {
1079PNG_error = 41; // error: this chunk must be 6 bytes for RGB image
1080return NULL;
1081}
1082info->key_defined = true;
1083info->key_r = 256 * in[pos] + in[pos + 1];
1084pos += 2;
1085info->key_g = 256 * in[pos] + in[pos + 1];
1086pos += 2;
1087info->key_b = 256 * in[pos] + in[pos + 1];
1088pos += 2;
1089} else {
1090PNG_error = 42; // error: tRNS chunk not allowed for other color models
1091return NULL;
1092}
1093} else { // it's not an implemented chunk type, so ignore it: skip over the data
1094if (!(in[pos + 0] & 32)) {
1095// error: unknown critical chunk (5th bit of first byte of chunk type is 0)
1096PNG_error = 69;
1097return NULL;
1098}
1099pos += (chunkLength + 4); // skip 4 letters and uninterpreted data of unimplemented chunk
1100}
1101pos += 4; // step over CRC (which is ignored)
1102}
1103 if (!idat) {
1104 PNG_error = 1; // no data seen
1105 return NULL;
1106 }
1107uint32_t bpp = PNG_getBpp(info);
1108vector8_t *scanlines; // now the out buffer will be filled
1109scanlines = vector8_new(((info->width * (info->height * bpp + 7)) / 8) + info->height, 0);
1110if (!scanlines) {
1111PNG_error = 1;
1112return NULL;
1113}
1114PNG_error = Zlib_decompress(scanlines, idat);
1115if (PNG_error)
1116return NULL; // stop if the zlib decompressor returned an error
1117size_t bytewidth = (bpp + 7) / 8, outlength = (info->height * info->width * bpp + 7) / 8;
1118vector8_resize(info->image, outlength); // time to fill the out buffer
1119uint8_t *out_data = outlength ? info->image->data : 0;
1120if (info->interlaceMethod == 0) { // no interlace, just filter
1121size_t y, obp, bp;
1122size_t linestart, linelength;
1123linestart = 0;
1124// length in bytes of a scanline, excluding the filtertype byte
1125linelength = (info->width * bpp + 7) / 8;
1126if (bpp >= 8) // byte per byte
1127for (y = 0; y < info->height; y++) {
1128uint32_t filterType = scanlines->data[linestart];
1129const uint8_t *prevline;
1130prevline = (y == 0) ? 0 : &out_data[(y - 1) * info->width * bytewidth];
1131PNG_unFilterScanline(&out_data[linestart - y], &scanlines->data[linestart + 1],
1132prevline, bytewidth, filterType, linelength);
1133if (PNG_error)
1134return NULL;
1135linestart += (1 + linelength); // go to start of next scanline
1136} else { // less than 8 bits per pixel, so fill it up bit per bit
1137vector8_t *templine; // only used if bpp < 8
1138templine = vector8_new((info->width * bpp + 7) >> 3, 0);
1139for (y = 0, obp = 0; y < info->height; y++) {
1140uint32_t filterType = scanlines->data[linestart];
1141const uint8_t *prevline;
1142prevline = (y == 0) ? 0 : &out_data[(y - 1) * info->width * bytewidth];
1143PNG_unFilterScanline(templine->data, &scanlines->data[linestart + 1], prevline,
1144bytewidth, filterType, linelength);
1145if (PNG_error)
1146return NULL;
1147for (bp = 0; bp < info->width * bpp;)
1148PNG_setBitOfReversedStream(&obp, out_data, PNG_readBitFromReversedStream(&bp,
1149templine->data));
1150linestart += (1 + linelength); // go to start of next scanline
1151}
1152}
1153} else { // interlaceMethod is 1 (Adam7)
1154int i;
1155size_t passw[7] = {
1156(info->width + 7) / 8, (info->width + 3) / 8, (info->width + 3) / 4,
1157(info->width + 1) / 4, (info->width + 1) / 2, (info->width + 0) / 2,
1158(info->width + 0) / 1
1159};
1160size_t passh[7] = {
1161(info->height + 7) / 8, (info->height + 7) / 8, (info->height + 3) / 8,
1162(info->height + 3) / 4, (info->height + 1) / 4, (info->height + 1) / 2,
1163(info->height + 0) / 2
1164};
1165size_t passstart[7] = { 0 };
1166size_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,
11678, 4, 4, 2, 2 }; // values for the adam7 passes
1168for (i = 0; i < 6; i++)
1169passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8);
1170vector8_t *scanlineo, *scanlinen; // "old" and "new" scanline
1171scanlineo = vector8_new((info->width * bpp + 7) / 8, 0);
1172scanlinen = vector8_new((info->width * bpp + 7) / 8, 0);
1173for (i = 0; i < 7; i++)
1174PNG_adam7Pass(out_data, scanlinen->data, scanlineo->data, &scanlines->data[passstart[i]],
1175info->width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21],
1176passw[i], passh[i], bpp);
1177}
1178if (info->colorType != 6 || info->bitDepth != 8) { // conversion needed
1179vector8_t *copy = vector8_copy(info->image); // xxx: is this copy necessary?
1180if (!copy) {
1181return NULL;
1182}
1183PNG_error = PNG_convert(info, info->image, copy->data);
1184if (PNG_error) {
1185return NULL;
1186 }
1187}
1188return info;
1189}
1190
1191/*************************************************************************************************/
1192
1193#ifdef TEST
1194
1195#include <stdio.h>
1196#include <sys/stat.h>
1197
1198int main(int argc, char **argv)
1199{
1200char *fname = (argc > 1) ? argv[1] : "test.png";
1201PNG_info_t *info;
1202struct stat statbuf;
1203uint32_t insize, outsize;
1204FILE *infp, *outfp;
1205uint8_t *inbuf;
1206uint32_t n;
1207
1208if (stat(fname, &statbuf) != 0) {
1209perror("stat");
1210return 1;
1211} else if (!statbuf.st_size) {
1212printf("file empty\n");
1213return 1;
1214}
1215infp = fopen(fname, "rb");
1216if (!infp) {
1217perror("fopen");
1218return 1;
1219}
1220insize = (uint32_t) statbuf.st_size;
1221inbuf = malloc(insize);
1222if (!inbuf) {
1223perror("malloc");
1224fclose(infp);
1225return 1;
1226}
1227if (fread(inbuf, 1, insize, infp) != insize) {
1228perror("fread");
1229free(inbuf);
1230fclose(infp);
1231return 1;
1232}
1233fclose(infp);
1234
1235printf("input file: %s (size: %d)\n", fname, insize);
1236
1237info = PNG_decode(inbuf, insize);
1238free(inbuf);
1239printf("PNG_error: %d\n", PNG_error);
1240if (PNG_error != 0)
1241return 1;
1242
1243printf("width: %d, height: %d\nfirst 16 bytes: ", info->width, info->height);
1244for (n = 0; n < 16; n++)
1245printf("%02x ", info->image->data[n]);
1246printf("\n");
1247
1248outsize = info->width * info->height * 4;
1249printf("image size: %d\n", outsize);
1250if (outsize != info->image->size) {
1251printf("error: image size doesn't match dimensions\n");
1252return 1;
1253}
1254outfp = fopen("out.bin", "wb");
1255if (!outfp) {
1256perror("fopen");
1257return 1;
1258} else if (fwrite(info->image->data, 1, outsize, outfp) != outsize) {
1259perror("fwrite");
1260return 1;
1261}
1262fclose(outfp);
1263
1264#ifdef ALLOC_DEBUG
1265png_alloc_node_t *node;
1266for (node = png_alloc_head, n = 1; node; node = node->next, n++)
1267printf("node %d (%p) addr = %p, size = %ld\n", n, node, node->addr, node->size);
1268#endif
1269png_alloc_free_all(); // also frees info and image data from PNG_decode
1270
1271return 0;
1272}
1273
1274#endif
1275

Archive Download this file

Revision: 2439