Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 1996