Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 2456