Chameleon

Chameleon Svn Source Tree

Root/branches/ErmaC/Enoch/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
220uint32_t vector8_resizev(vector8_t *p, size_t size, uint8_t value)
221{// resize and give all new elements the value
222size_t oldsize = p->size, i;
223if (!vector8_resize(p, size))
224return 0;
225for (i = oldsize; i < size; i++)
226p->data[i] = value;
227return 1;
228}
229
230void vector8_init(vector8_t *p)
231{
232p->data = NULL;
233p->size = p->allocsize = 0;
234}
235
236vector8_t *vector8_new(size_t size, uint8_t value)
237{
238vector8_t *p = png_alloc_malloc(sizeof (vector8_t));
239if(!p) {
240return NULL;
241}
242vector8_init(p);
243if (size && !vector8_resizev(p, size, value)) {
244vector8_cleanup(p);
245png_alloc_free(p);
246return NULL;
247}
248return p;
249}
250
251vector8_t *vector8_copy(vector8_t *p)
252{
253vector8_t *q = vector8_new(p->size, 0);
254uint32_t n;
255if (!q) {
256 return NULL;
257}
258for (n = 0; n < q->size; n++)
259q->data[n] = p->data[n];
260return q;
261}
262
263/*************************************************************************************************/
264
265const uint32_t LENBASE[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51,
26659, 67, 83, 99, 115, 131, 163, 195, 227, 258 };
267const 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,
2684, 5, 5, 5, 5, 0 };
269const uint32_t DISTBASE[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385,
270513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
271const 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,
27210, 10, 11, 11, 12, 12, 13, 13 };
273// code length code lengths
274const uint32_t CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
275
276/*************************************************************************************************/
277
278typedef struct {
279// 2D representation of a huffman tree: The one dimension is "0" or "1", the other contains all
280// nodes and leaves of the tree.
281vector32_t *tree2d;
282} HuffmanTree;
283
284HuffmanTree *HuffmanTree_new()
285{
286HuffmanTree *tree = png_alloc_malloc(sizeof (HuffmanTree));
287if (!tree)
288{
289return NULL;
290}
291tree->tree2d = NULL;
292return tree;
293}
294
295int HuffmanTree_makeFromLengths(HuffmanTree *tree, const vector32_t *bitlen, uint32_t maxbitlen)
296{// make tree given the lengths
297uint32_t bits, n, i;
298uint32_t numcodes = (uint32_t) bitlen->size, treepos = 0, nodefilled = 0;
299vector32_t *tree1d, *blcount, *nextcode;
300tree1d = vector32_new(numcodes, 0);
301blcount = vector32_new(maxbitlen + 1, 0);
302nextcode = vector32_new(maxbitlen + 1, 0);
303if (!tree1d || !blcount || !nextcode || !nextcode->data)
304{
305goto error;
306}
307for (bits = 0; bits < numcodes; bits++)
308blcount->data[bitlen->data[bits]]++; // count number of instances of each code length
309for (bits = 1; bits <= maxbitlen; bits++)
310nextcode->data[bits] = (nextcode->data[bits - 1] + blcount->data[bits - 1]) << 1;
311for (n = 0; n < numcodes; n++)
312if (bitlen->data[n] != 0)
313tree1d->data[n] = nextcode->data[bitlen->data[n]]++; // generate all the codes
314// 0x7fff here means the tree2d isn't filled there yet
315vector32_t *tree2d = vector32_new(numcodes * 2, 0x7fff);
316tree->tree2d = tree2d;
317for (n = 0; n < numcodes; n++) // the codes
318for (i = 0; i < bitlen->data[n]; i++) { // the bits for this code
319uint32_t bit = (tree1d->data[n] >> (bitlen->data[n] - i - 1)) & 1;
320if (treepos > numcodes - 2)
321return 55;
322if (tree2d->data[2 * treepos + bit] == 0x7fff) { // not yet filled in
323if (i + 1 == bitlen->data[n]) { // last bit
324tree2d->data[2 * treepos + bit] = n;
325treepos = 0;
326} else { // addresses are encoded as values > numcodes
327tree2d->data[2 * treepos + bit] = ++nodefilled + numcodes;
328treepos = nodefilled;
329}
330} else // subtract numcodes from address to get address value
331treepos = tree2d->data[2 * treepos + bit] - numcodes;
332}
333return 0;
334error:
335if (tree1d)
336{
337vector32_cleanup(tree1d);
338png_alloc_free(tree1d);
339}
340if (blcount)
341{
342vector32_cleanup(blcount);
343png_alloc_free(blcount);
344}
345if (nextcode)
346{
347vector32_cleanup(nextcode);
348png_alloc_free(nextcode);
349}
350return 1;
351}
352
353int HuffmanTree_decode(const HuffmanTree *tree, bool *decoded, uint32_t *result, size_t *treepos,
354uint32_t bit)
355{// Decodes a symbol from the tree
356const vector32_t *tree2d = tree->tree2d;
357uint32_t numcodes = (uint32_t) tree2d->size / 2;
358if (*treepos >= numcodes)
359return 11; // error: you appeared outside the codetree
360*result = tree2d->data[2 * (*treepos) + bit];
361*decoded = (*result < numcodes);
362*treepos = *decoded ? 0 : *result - numcodes;
363return 0;
364}
365
366/*************************************************************************************************/
367
368int Inflator_error;
369
370uint32_t Zlib_readBitFromStream(size_t *bitp, const uint8_t *bits)
371{
372uint32_t result = (bits[*bitp >> 3] >> (*bitp & 0x7)) & 1;
373(*bitp)++;
374return result;
375}
376
377uint32_t Zlib_readBitsFromStream(size_t *bitp, const uint8_t *bits, size_t nbits)
378{
379uint32_t i, result = 0;
380for (i = 0; i < nbits; i++)
381result += (Zlib_readBitFromStream(bitp, bits)) << i;
382return result;
383}
384
385void Inflator_generateFixedTrees(HuffmanTree *tree, HuffmanTree *treeD)
386{// get the tree of a deflated block with fixed tree
387size_t i;
388vector32_t *bitlen, *bitlenD;
389bitlen = vector32_new(288, 8);
390bitlenD = vector32_new(32, 5);
391for (i = 144; i <= 255; i++)
392bitlen->data[i] = 9;
393for (i = 256; i <= 279; i++)
394bitlen->data[i] = 7;
395HuffmanTree_makeFromLengths(tree, bitlen, 15);
396HuffmanTree_makeFromLengths(treeD, bitlenD, 15);
397}
398
399uint32_t Inflator_huffmanDecodeSymbol(const uint8_t *in, size_t *bp, const HuffmanTree *codetree,
400size_t inlength)
401{// decode a single symbol from given list of bits with given code tree. returns the symbol
402bool decoded = false;
403uint32_t ct = 0;
404size_t treepos = 0;
405for (;;) {
406if ((*bp & 0x07) == 0 && (*bp >> 3) > inlength) {
407Inflator_error = 10; // error: end reached without endcode
408return 0;
409}
410Inflator_error = HuffmanTree_decode(codetree, &decoded, &ct, &treepos,
411Zlib_readBitFromStream(bp, in));
412if (Inflator_error)
413return 0; // stop, an error happened
414if (decoded)
415return ct;
416}
417}
418
419void Inflator_getTreeInflateDynamic(HuffmanTree *tree, HuffmanTree *treeD, const uint8_t *in,
420size_t *bp, size_t inlength)
421{// get the tree of a deflated block with dynamic tree, the tree itself is also Huffman
422// compressed with a known tree
423size_t i, n;
424size_t HLIT;
425size_t HDIST;
426size_t HCLEN;
427size_t replength;
428vector32_t *codelengthcode;
429HuffmanTree *codelengthcodetree = HuffmanTree_new(); // the code tree for code length codes
430vector32_t *bitlen, *bitlenD;
431bitlen = vector32_new(288, 0);
432bitlenD = vector32_new(32, 0);
433if (*bp >> 3 >= inlength - 2) {
434Inflator_error = 49; // the bit pointer is or will go past the memory
435return;
436}
437HLIT = Zlib_readBitsFromStream(bp, in, 5) + 257;// number of literal/length codes + 257
438HDIST = Zlib_readBitsFromStream(bp, in, 5) + 1;// number of dist codes + 1
439HCLEN = Zlib_readBitsFromStream(bp, in, 4) + 4;// number of code length codes + 4
440// lengths of tree to decode the lengths of the dynamic tree
441codelengthcode = vector32_new(19, 0);
442for (i = 0; i < 19; i++)
443codelengthcode->data[CLCL[i]] = (i < HCLEN) ? Zlib_readBitsFromStream(bp, in, 3) : 0;
444Inflator_error = HuffmanTree_makeFromLengths(codelengthcodetree, codelengthcode, 7);
445if (Inflator_error)
446return;
447
448for (i = 0; i < HLIT + HDIST; ) {
449uint32_t code = Inflator_huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength);
450if (Inflator_error) {
451return;
452}
453if (code <= 15) { // a length code
454if (i < HLIT) {
455bitlen->data[i++] = code;
456} else {
457bitlenD->data[i++ - HLIT] = code;
458}
459} else if (code == 16)
460{ // repeat previous
461uint32_t value; // set value to the previous code
462if (*bp >> 3 >= inlength)
463{
464Inflator_error = 50; // error, bit pointer jumps past memory
465return;
466}
467replength = 3 + Zlib_readBitsFromStream(bp, in, 2);
468
469if ((i - 1) < HLIT) {
470value = bitlen->data[i - 1];
471} else {
472value = bitlenD->data[i - HLIT - 1];
473}
474for (n = 0; n < replength; n++) { // repeat this value in the next lengths
475if (i >= HLIT + HDIST) {
476Inflator_error = 13; // error: i is larger than the amount of codes
477return;
478}
479if (i < HLIT) {
480bitlen->data[i++] = value;
481} else {
482bitlenD->data[i++ - HLIT] = value;
483}
484}
485} else if (code == 17) { // repeat "0" 3-10 times
486if (*bp >> 3 >= inlength) {
487Inflator_error = 50; // error, bit pointer jumps past memory
488return;
489}
490replength = 3 + Zlib_readBitsFromStream(bp, in, 3);
491for (n = 0; n < replength; n++) { // repeat this value in the next lengths
492if (i >= HLIT + HDIST) {
493Inflator_error = 14; // error: i is larger than the amount of codes
494return;
495}
496if (i < HLIT)
497{
498bitlen->data[i++] = 0;
499}
500else
501{
502bitlenD->data[i++ - HLIT] = 0;
503}
504}
505} else if (code == 18) { // repeat "0" 11-138 times
506if (*bp >> 3 >= inlength) {
507Inflator_error = 50; // error, bit pointer jumps past memory
508return;
509}
510replength = 11 + Zlib_readBitsFromStream(bp, in, 7);
511for (n = 0; n < replength; n++) { // repeat this value in the next lengths
512if (i >= HLIT + HDIST) {
513Inflator_error = 15; // error: i is larger than the amount of codes
514return;
515}
516if (i < HLIT)
517{
518bitlen->data[i++] = 0;
519}
520else
521{
522bitlenD->data[i++ - HLIT] = 0;
523}
524}
525} else {
526Inflator_error = 16; // error: an nonexitent code appeared. This can never happen.
527return;
528}
529}
530if (bitlen->data[256] == 0) {
531Inflator_error = 64; // the length of the end code 256 must be larger than 0
532return;
533}
534// now we've finally got HLIT and HDIST, so generate the code trees, and the function is done
535Inflator_error = HuffmanTree_makeFromLengths(tree, bitlen, 15);
536if (Inflator_error)
537return;
538Inflator_error = HuffmanTree_makeFromLengths(treeD, bitlenD, 15);
539if (Inflator_error)
540return;
541}
542
543void Inflator_inflateHuffmanBlock(vector8_t *out, const uint8_t *in, size_t *bp, size_t *pos,
544size_t inlength, uint32_t btype)
545{
546HuffmanTree *codetree, *codetreeD; // the code tree for Huffman codes, dist codes
547codetree = HuffmanTree_new();
548codetreeD = HuffmanTree_new();
549if (btype == 1)
550Inflator_generateFixedTrees(codetree, codetreeD);
551else if (btype == 2) {
552Inflator_getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength);
553if (Inflator_error)
554return;
555}
556for (;;) {
557uint32_t code = Inflator_huffmanDecodeSymbol(in, bp, codetree, inlength);
558if (Inflator_error)
559return;
560if (code == 256) // end code
561{
562return;
563}
564else if (code <= 255) { // literal symbol
565if (*pos >= out->size) {
566vector8_resize(out, (*pos + 1) * 2); // reserve more room
567}
568out->data[(*pos)++] = (uint8_t) code;
569} else if (code >= 257 && code <= 285)
570{ // length code
571size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257];
572if ((*bp >> 3) >= inlength)
573{
574Inflator_error = 51; // error, bit pointer will jump past memory
575return;
576}
577length += Zlib_readBitsFromStream(bp, in, numextrabits);
578uint32_t codeD = Inflator_huffmanDecodeSymbol(in, bp, codetreeD, inlength);
579if (Inflator_error)
580return;
581if (codeD > 29) {
582Inflator_error = 18; // error: invalid dist code (30-31 are never used)
583return;
584}
585uint32_t dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD];
586if ((*bp >> 3) >= inlength) {
587Inflator_error = 51; // error, bit pointer will jump past memory
588return;
589}
590dist += Zlib_readBitsFromStream(bp, in, numextrabitsD);
591size_t start = *pos, back = start - dist; // backwards
592if (*pos + length >= out->size)
593vector8_resize(out, (*pos + length) * 2); // reserve more room
594size_t i;
595for (i = 0; i < length; i++) {
596out->data[(*pos)++] = out->data[back++];
597if (back >= start)
598back = start - dist;
599}
600}
601}
602}
603
604void Inflator_inflateNoCompression(vector8_t *out, const uint8_t *in, size_t *bp, size_t *pos,
605size_t inlength)
606{
607while ((*bp & 0x7) != 0)
608(*bp)++; // go to first boundary of byte
609size_t p = *bp / 8;
610if (p >= inlength - 4) {
611Inflator_error = 52; // error, bit pointer will jump past memory
612return;
613}
614uint32_t LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3];
615p += 4;
616if (LEN + NLEN != 65535) {
617Inflator_error = 21; // error: NLEN is not one's complement of LEN
618return;
619}
620if (*pos + LEN >= out->size)
621vector8_resize(out, *pos + LEN);
622if (p + LEN > inlength) {
623Inflator_error = 23; // error: reading outside of in buffer
624return;
625}
626uint32_t n;
627for (n = 0; n < LEN; n++)
628out->data[(*pos)++] = in[p++]; // read LEN bytes of literal data
629*bp = p * 8;
630}
631
632void Inflator_inflate(vector8_t *out, const vector8_t *in, size_t inpos)
633{
634size_t bp = 0, pos = 0; // bit pointer and byte pointer
635Inflator_error = 0;
636uint32_t BFINAL = 0;
637while (!BFINAL && !Inflator_error) {
638if (bp >> 3 >= in->size) {
639Inflator_error = 52; // error, bit pointer will jump past memory
640return;
641}
642BFINAL = Zlib_readBitFromStream(&bp, &in->data[inpos]);
643uint32_t BTYPE = Zlib_readBitFromStream(&bp, &in->data[inpos]);
644BTYPE += 2 * Zlib_readBitFromStream(&bp, &in->data[inpos]);
645if (BTYPE == 3) {
646Inflator_error = 20; // error: invalid BTYPE
647return;
648}
649else if (BTYPE == 0)
650Inflator_inflateNoCompression(out, &in->data[inpos], &bp, &pos, in->size);
651else
652Inflator_inflateHuffmanBlock(out, &in->data[inpos], &bp, &pos, in->size, BTYPE);
653}
654if (!Inflator_error)
655vector8_resize(out, pos); // Only now we know the true size of out, resize it to that
656}
657
658/*************************************************************************************************/
659
660int Zlib_decompress(vector8_t *out, const vector8_t *in) // returns error value
661{
662if (in->size < 2)
663return 53; // error, size of zlib data too small
664if ((in->data[0] * 256 + in->data[1]) % 31 != 0)
665// error: 256 * in->data[0] + in->data[1] must be a multiple of 31, the FCHECK value is
666// supposed to be made that way
667return 24;
668uint32_t CM = in->data[0] & 15, CINFO = (in->data[0] >> 4) & 15, FDICT = (in->data[1] >> 5) & 1;
669if (CM != 8 || CINFO > 7){
670// error: only compression method 8: inflate with sliding window of 32k is supported by
671// the PNG spec
672
673return 25;
674}
675if (FDICT != 0) {
676// error: the specification of PNG says about the zlib stream: "The additional flags shall
677// not specify a preset dictionary."
678return 26;
679}
680Inflator_inflate(out, in, 2);
681return Inflator_error; // note: adler32 checksum was skipped and ignored
682}
683
684/*************************************************************************************************/
685
686#define PNG_SIGNATURE0x0a1a0a0d474e5089ull
687
688#define CHUNK_IHDR0x52444849
689#define CHUNK_IDAT0x54414449
690#define CHUNK_IEND0x444e4549
691#define CHUNK_PLTE0x45544c50
692#define CHUNK_tRNS0x534e5274
693
694int PNG_error;
695
696uint32_t PNG_readBitFromReversedStream(size_t *bitp, const uint8_t *bits)
697{
698uint32_t result = (bits[*bitp >> 3] >> (7 - (*bitp & 0x7))) & 1;
699(*bitp)++;
700return result;
701}
702
703uint32_t PNG_readBitsFromReversedStream(size_t *bitp, const uint8_t *bits, uint32_t nbits)
704{
705uint32_t i, result = 0;
706for (i = nbits - 1; i < nbits; i--)
707result += ((PNG_readBitFromReversedStream(bitp, bits)) << i);
708return result;
709}
710
711void PNG_setBitOfReversedStream(size_t *bitp, uint8_t *bits, uint32_t bit)
712{
713bits[*bitp >> 3] |= (bit << (7 - (*bitp & 0x7)));
714(*bitp)++;
715}
716
717uint32_t PNG_read32bitInt(const uint8_t *buffer)
718{
719return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
720}
721
722int PNG_checkColorValidity(uint32_t colorType, uint32_t bd) // return type is a LodePNG error code
723{
724if ((colorType == 2 || colorType == 4 || colorType == 6)) {
725if (!(bd == 8 || bd == 16))
726return 37;
727else
728return 0;
729} else if (colorType == 0) {
730if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16))
731return 37;
732else
733return 0;
734} else if (colorType == 3) {
735if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8))
736return 37;
737else
738return 0;
739} else
740return 31; // nonexistent color type
741}
742
743uint32_t PNG_getBpp(const PNG_info_t *info)
744{
745uint32_t bitDepth, colorType;
746bitDepth = info->bitDepth;
747colorType = info->colorType;
748if (colorType == 2) {
749return (3 * bitDepth);
750} else if (colorType >= 4) {
751return (colorType - 2) * bitDepth;
752} else {
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;
898uint32_t bitDepth, colorType;
899bitDepth = info->bitDepth;
900colorType = info->colorType;
901size_t numpixels = info->width * info->height, bp = 0;
902vector8_resize(out, numpixels * 4);
903uint8_t *out_data = out->size ? out->data : 0;
904if (bitDepth == 8 && colorType == 0) // greyscale
905for (i = 0; i < numpixels; i++) {
906out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[i];
907out_data[4 * i + 3] = (info->key_defined && (in[i] == info->key_r)) ? 0 : 255;
908}
909else if (bitDepth == 8 && colorType == 2) // RGB color
910for (i = 0; i < numpixels; i++) {
911for (c = 0; c < 3; c++)
912out_data[4 * i + c] = in[3 * i + c];
913out_data[4 * i + 3] = (info->key_defined && (in[3 * i + 0] == info->key_r) &&
914(in[3 * i + 1] == info->key_g) && (in[3 * i + 2] == info->key_b)) ? 0 : 255;
915}
916else if (bitDepth == 8 && colorType == 3) // indexed color (palette)
917for (i = 0; i < numpixels; i++) {
918if (4U * in[i] >= info->palette->size)
919return 46;
920for (c = 0; c < 4; c++) // get rgb colors from the palette
921out_data[4 * i + c] = info->palette->data[4 * in[i] + c];
922}
923else if (bitDepth == 8 && colorType == 4) // greyscale with alpha
924for (i = 0; i < numpixels; i++) {
925out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[2 * i + 0];
926out_data[4 * i + 3] = in[2 * i + 1];
927}
928else if (bitDepth == 8 && colorType == 6)
929for (i = 0; i < numpixels; i++)
930for (c = 0; c < 4; c++)
931out_data[4 * i + c] = in[4 * i + c]; // RGB with alpha
932else if (bitDepth == 16 && colorType == 0) // greyscale
933for (i = 0; i < numpixels; i++) {
934out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[2 * i];
935out_data[4 * i + 3] = (info->key_defined && (256U * in[i] + in[i + 1] == info->key_r))
936? 0 : 255;
937}
938else if (bitDepth == 16 && colorType == 2) // RGB color
939for (i = 0; i < numpixels; i++) {
940for (c = 0; c < 3; c++)
941out_data[4 * i + c] = in[6 * i + 2 * c];
942out_data[4 * i + 3] = (info->key_defined &&
943(256U * in[6 * i + 0] + in[6 * i + 1] == info->key_r) &&
944(256U * in[6 * i + 2] + in[6 * i + 3] == info->key_g) &&
945(256U * in[6 * i + 4] + in[6 * i + 5] == info->key_b)) ? 0 : 255;
946}
947else if (bitDepth == 16 && colorType == 4) // greyscale with alpha
948for (i = 0; i < numpixels; i++) {
949out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = in[4 * i]; // msb
950out_data[4 * i + 3] = in[4 * i + 2];
951}
952else if (bitDepth == 16 && colorType == 6)
953for (i = 0; i < numpixels; i++)
954for (c = 0; c < 4; c++)
955out_data[4 * i + c] = in[8 * i + 2 * c]; // RGB with alpha
956else if (bitDepth < 8 && colorType == 0) // greyscale
957for (i = 0; i < numpixels; i++) {
958uint32_t value = (PNG_readBitsFromReversedStream(&bp, in, bitDepth) * 255) /
959((1 << bitDepth) - 1); // scale value from 0 to 255
960out_data[4 * i + 0] = out_data[4 * i + 1] = out_data[4 * i + 2] = (uint8_t) value;
961out_data[4 * i + 3] = (info->key_defined && value &&
962(((1U << bitDepth) - 1U) == info->key_r) && ((1U << bitDepth) - 1U)) ? 0 : 255;
963}
964else if (bitDepth < 8 && colorType == 3) // palette
965for (i = 0; i < numpixels; i++) {
966uint32_t value = PNG_readBitsFromReversedStream(&bp, in, bitDepth);
967if (4 * value >= info->palette->size)
968return 47;
969for (c = 0; c < 4; c++) // get rgb colors from the palette
970out_data[4 * i + c] = info->palette->data[4 * value + c];
971}
972return 0;
973}
974
975PNG_info_t *PNG_info_new()
976{
977PNG_info_t *info = png_alloc_malloc(sizeof (PNG_info_t));
978if (!info) {
979return NULL;
980}
981uint32_t i;
982for (i = 0; i < sizeof (PNG_info_t); i++)
983((uint8_t *) info)[i] = 0;
984info->palette = vector8_new(0, 0);
985info->image = vector8_new(0, 0);
986return info;
987}
988
989PNG_info_t *PNG_decode(const uint8_t *in, uint32_t size)
990{
991PNG_info_t *info;
992PNG_error = 0;
993if (size == 0 || in == 0) {
994PNG_error = 48; // the given data is empty
995return NULL;
996}
997info = PNG_info_new();
998PNG_readPngHeader(info, in, size);
999if (PNG_error) {
1000return NULL;
1001}
1002size_t pos = 33; // first byte of the first chunk after the header
1003vector8_t *idat = NULL; // the data from idat chunks
1004bool IEND = false, known_type = true;
1005info->key_defined = false;
1006// loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is
1007// put at the start of the in buffer
1008while (!IEND) {
1009size_t i, j;
1010if (pos + 8 >= size) {
1011PNG_error = 30; // error: size of the in buffer too small to contain next chunk
1012return NULL;
1013}
1014size_t chunkLength = PNG_read32bitInt(&in[pos]);
1015pos += 4;
1016if (chunkLength > 0x7fffffff) {
1017PNG_error = 63;
1018return NULL;
1019}
1020if (pos + chunkLength >= size) {
1021PNG_error = 35; // error: size of the in buffer too small to contain next chunk
1022return NULL;
1023}
1024uint32_t chunkType = *(uint32_t *) &in[pos];
1025if (chunkType == CHUNK_IDAT) { // IDAT: compressed image data chunk
1026size_t offset = 0;
1027if (idat) {
1028offset = idat->size;
1029vector8_resize(idat, offset + chunkLength);
1030} else
1031idat = vector8_new(chunkLength, 0);
1032
1033if (!idat) {
1034PNG_error = 1;
1035return NULL;
1036}
1037for (i = 0; i < chunkLength; i++)
1038idat->data[offset + i] = in[pos + 4 + i];
1039pos += (4 + chunkLength);
1040} else if (chunkType == CHUNK_IEND) { // IEND
1041pos += 4;
1042IEND = true;
1043} else if (chunkType == CHUNK_PLTE) { // PLTE: palette chunk
1044pos += 4; // go after the 4 letters
1045vector8_resize(info->palette, 4 * (chunkLength / 3));
1046if (info->palette->size > (4 * 256)) {
1047PNG_error = 38; // error: palette too big
1048return NULL;
1049}
1050for (i = 0; i < info->palette->size; i += 4) {
1051for (j = 0; j < 3; j++)
1052info->palette->data[i + j] = in[pos++]; // RGB
1053info->palette->data[i + 3] = 255; // alpha
1054}
1055} else if (chunkType == CHUNK_tRNS) { // tRNS: palette transparency chunk
1056pos += 4; // go after the 4 letters
1057if (info->colorType == 3) {
1058if (4 * chunkLength > info->palette->size) {
1059PNG_error = 39; // error: more alpha values given than there are palette entries
1060return NULL;
1061}
1062for (i = 0; i < chunkLength; i++)
1063info->palette->data[4 * i + 3] = in[pos++];
1064} else if (info->colorType == 0) {
1065if (chunkLength != 2) {
1066PNG_error = 40; // error: this chunk must be 2 bytes for greyscale image
1067return NULL;
1068}
1069info->key_defined = true;
1070info->key_r = info->key_g = info->key_b = 256 * in[pos] + in[pos + 1];
1071pos += 2;
1072} else if (info->colorType == 2) {
1073if (chunkLength != 6) {
1074PNG_error = 41; // error: this chunk must be 6 bytes for RGB image
1075return NULL;
1076}
1077info->key_defined = true;
1078info->key_r = 256 * in[pos] + in[pos + 1];
1079pos += 2;
1080info->key_g = 256 * in[pos] + in[pos + 1];
1081pos += 2;
1082info->key_b = 256 * in[pos] + in[pos + 1];
1083pos += 2;
1084} else {
1085PNG_error = 42; // error: tRNS chunk not allowed for other color models
1086return NULL;
1087}
1088} else { // it's not an implemented chunk type, so ignore it: skip over the data
1089if (!(in[pos + 0] & 32)) {
1090// error: unknown critical chunk (5th bit of first byte of chunk type is 0)
1091PNG_error = 69;
1092return NULL;
1093}
1094pos += (chunkLength + 4); // skip 4 letters and uninterpreted data of unimplemented chunk
1095known_type = false;
1096}
1097pos += 4; // step over CRC (which is ignored)
1098}
1099uint32_t bpp = PNG_getBpp(info);
1100vector8_t *scanlines; // now the out buffer will be filled
1101scanlines = vector8_new(((info->width * (info->height * bpp + 7)) / 8) + info->height, 0);
1102if (!scanlines) {
1103PNG_error = 1;
1104return NULL;
1105}
1106PNG_error = Zlib_decompress(scanlines, idat);
1107if (PNG_error)
1108return NULL; // stop if the zlib decompressor returned an error
1109size_t bytewidth = (bpp + 7) / 8, outlength = (info->height * info->width * bpp + 7) / 8;
1110vector8_resize(info->image, outlength); // time to fill the out buffer
1111uint8_t *out_data = outlength ? info->image->data : 0;
1112if (info->interlaceMethod == 0) { // no interlace, just filter
1113size_t y, obp, bp;
1114size_t linestart, linelength;
1115linestart = 0;
1116// length in bytes of a scanline, excluding the filtertype byte
1117linelength = (info->width * bpp + 7) / 8;
1118if (bpp >= 8) // byte per byte
1119for (y = 0; y < info->height; y++) {
1120uint32_t filterType = scanlines->data[linestart];
1121const uint8_t *prevline;
1122prevline = (y == 0) ? 0 : &out_data[(y - 1) * info->width * bytewidth];
1123PNG_unFilterScanline(&out_data[linestart - y], &scanlines->data[linestart + 1],
1124prevline, bytewidth, filterType, linelength);
1125if (PNG_error)
1126return NULL;
1127linestart += (1 + linelength); // go to start of next scanline
1128} else { // less than 8 bits per pixel, so fill it up bit per bit
1129vector8_t *templine; // only used if bpp < 8
1130templine = vector8_new((info->width * bpp + 7) >> 3, 0);
1131for (y = 0, obp = 0; y < info->height; y++) {
1132uint32_t filterType = scanlines->data[linestart];
1133const uint8_t *prevline;
1134prevline = (y == 0) ? 0 : &out_data[(y - 1) * info->width * bytewidth];
1135PNG_unFilterScanline(templine->data, &scanlines->data[linestart + 1], prevline,
1136bytewidth, filterType, linelength);
1137if (PNG_error)
1138return NULL;
1139for (bp = 0; bp < info->width * bpp;)
1140PNG_setBitOfReversedStream(&obp, out_data, PNG_readBitFromReversedStream(&bp,
1141templine->data));
1142linestart += (1 + linelength); // go to start of next scanline
1143}
1144}
1145} else { // interlaceMethod is 1 (Adam7)
1146int i;
1147size_t passw[7] = {
1148(info->width + 7) / 8, (info->width + 3) / 8, (info->width + 3) / 4,
1149(info->width + 1) / 4, (info->width + 1) / 2, (info->width + 0) / 2,
1150(info->width + 0) / 1
1151};
1152size_t passh[7] = {
1153(info->height + 7) / 8, (info->height + 7) / 8, (info->height + 3) / 8,
1154(info->height + 3) / 4, (info->height + 1) / 4, (info->height + 1) / 2,
1155(info->height + 0) / 2
1156};
1157size_t passstart[7] = { 0 };
1158size_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,
11598, 4, 4, 2, 2 }; // values for the adam7 passes
1160for (i = 0; i < 6; i++)
1161passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8);
1162vector8_t *scanlineo, *scanlinen; // "old" and "new" scanline
1163scanlineo = vector8_new((info->width * bpp + 7) / 8, 0);
1164scanlinen = vector8_new((info->width * bpp + 7) / 8, 0);
1165for (i = 0; i < 7; i++)
1166PNG_adam7Pass(out_data, scanlinen->data, scanlineo->data, &scanlines->data[passstart[i]],
1167info->width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21],
1168passw[i], passh[i], bpp);
1169}
1170if (info->colorType != 6 || info->bitDepth != 8) { // conversion needed
1171vector8_t *copy = vector8_copy(info->image); // xxx: is this copy necessary?
1172if (!copy) {
1173return NULL;
1174}
1175PNG_error = PNG_convert(info, info->image, copy->data);
1176if (PNG_error) {
1177return NULL;
1178 }
1179}
1180return info;
1181}
1182
1183/*************************************************************************************************/
1184
1185#ifdef TEST
1186
1187#include <stdio.h>
1188#include <sys/stat.h>
1189
1190int main(int argc, char **argv)
1191{
1192char *fname = (argc > 1) ? argv[1] : "test.png";
1193PNG_info_t *info;
1194struct stat statbuf;
1195uint32_t insize, outsize;
1196FILE *infp, *outfp;
1197uint8_t *inbuf;
1198uint32_t n;
1199
1200if (stat(fname, &statbuf) != 0) {
1201perror("stat");
1202return 1;
1203} else if (!statbuf.st_size) {
1204printf("file empty\n");
1205return 1;
1206}
1207infp = fopen(fname, "rb");
1208if (!infp) {
1209perror("fopen");
1210return 1;
1211}
1212insize = (uint32_t) statbuf.st_size;
1213inbuf = malloc(insize);
1214if (!inbuf) {
1215perror("malloc");
1216fclose(infp);
1217return 1;
1218}
1219if (fread(inbuf, 1, insize, infp) != insize) {
1220perror("fread");
1221free(inbuf);
1222fclose(infp);
1223return 1;
1224}
1225fclose(infp);
1226
1227printf("input file: %s (size: %d)\n", fname, insize);
1228
1229info = PNG_decode(inbuf, insize);
1230free(inbuf);
1231printf("PNG_error: %d\n", PNG_error);
1232if (PNG_error != 0)
1233return 1;
1234
1235printf("width: %d, height: %d\nfirst 16 bytes: ", info->width, info->height);
1236for (n = 0; n < 16; n++)
1237printf("%02x ", info->image->data[n]);
1238printf("\n");
1239
1240outsize = info->width * info->height * 4;
1241printf("image size: %d\n", outsize);
1242if (outsize != info->image->size) {
1243printf("error: image size doesn't match dimensions\n");
1244return 1;
1245}
1246outfp = fopen("out.bin", "wb");
1247if (!outfp) {
1248perror("fopen");
1249return 1;
1250} else if (fwrite(info->image->data, 1, outsize, outfp) != outsize) {
1251perror("fwrite");
1252return 1;
1253}
1254fclose(outfp);
1255
1256#ifdef ALLOC_DEBUG
1257png_alloc_node_t *node;
1258for (node = png_alloc_head, n = 1; node; node = node->next, n++)
1259printf("node %d (%p) addr = %p, size = %ld\n", n, node, node->addr, node->size);
1260#endif
1261png_alloc_free_all(); // also frees info and image data from PNG_decode
1262
1263return 0;
1264}
1265
1266#endif
1267

Archive Download this file

Revision: 2347