Chameleon

Chameleon Svn Source Tree

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

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

Archive Download this file

Revision: 2454