aboutsummaryrefslogtreecommitdiffstats
path: root/src/gdisp/gdisp_image_png.c
blob: 4cb3ca07017f1f3dbc1974cdcc650f6a9e3e69a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
/*
 * This file is subject to the terms of the GFX License. If a copy of
 * the license was not distributed with this file, you can obtain one at:
 *
 *              http://ugfx.io/license.html
 */

#include "../../gfx.h"

#if GFX_USE_GDISP && GDISP_NEED_IMAGE && GDISP_NEED_IMAGE_PNG

#include "gdisp_image_support.h"

/*-----------------------------------------------------------------
 * Structure definitions
 *---------------------------------------------------------------*/

struct PNG_decode;

// PNG info (comes from the PNG header)
typedef struct PNG_info {
	gU8		flags;								// Flags (global)
		#define PNG_FLG_HEADERDONE			0x01		// The header has been processed
		#define PNG_FLG_TRANSPARENT			0x02		// Has transparency
		#define PNG_FLG_INTERLACE			0x04		// Is Interlaced
		#define PNG_FLG_BACKGROUND			0x08		// Has a specified background color
	gU8		bitdepth;							// 1, 2, 4, 8, 16
	gU8		mode;								// The PNG color-mode
		#define PNG_COLORMODE_GRAY			0x00		// Grayscale
		#define PNG_COLORMODE_RGB			0x02		// RGB
		#define PNG_COLORMODE_PALETTE		0x03		// Pallete
		#define PNG_COLORMODE_GRAYALPHA		0x04		// Grayscale with Alpha
		#define PNG_COLORMODE_RGBA			0x06		// RGBA
	gU8		bpp;								// Bits per pixel

	gU8		*cache;								// The image cache
	unsigned	cachesz;							// The image cache size

	void 		(*out)(struct PNG_decode *);		// The scan line output function

	#if GDISP_NEED_IMAGE_PNG_BACKGROUND
		gColor		bg;								// The background color
	#endif
	#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
		gU16	trans_r;						// Red/grayscale component of the transparent color (PNG_COLORMODE_GRAY and PNG_COLORMODE_RGB only)
		gU16	trans_g;						// Green component of the transparent color (PNG_COLORMODE_RGB only)
		gU16	trans_b;						// Blue component of the transparent color (PNG_COLORMODE_RGB only)
	#endif
	#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
		gU16	palsize;						// palette size in number of colors
		gU8 	*palette;						// palette in RGBA RGBA... order (4 bytes per entry - PNG_COLORMODE_PALETTE only)
	#endif
	} PNG_info;

// Handle the PNG file stream
typedef struct PNG_input {
	GFILE *		f;								// The gfile to retrieve data from
	unsigned	buflen;							// The number of bytes left in the buffer
	gU8		*pbuf;							// The pointer to the next byte
	gU32	chunklen;						// The number of bytes left in the current PNG chunk
	gU32	chunknext;						// The file position of the next PNG chunk
	gU8		buf[GDISP_IMAGE_PNG_FILE_BUFFER_SIZE];		// Must be a minimum of 8 bytes to hold a chunk header
	} PNG_input;

// Handle the display output and windowing
typedef struct PNG_output {
	GDisplay	*g;
	gCoord		x, y;
	gCoord		cx, cy;
	gCoord		sx, sy;
	gCoord		ix, iy;
	unsigned	cnt;
	gPixel		buf[GDISP_IMAGE_PNG_BLIT_BUFFER_SIZE];
	} PNG_output;

// Handle the PNG scan line filter
typedef struct PNG_filter {
	unsigned	scanbytes;
	unsigned	bytewidth;
	gU8		*line;
	gU8		*prev;
	} PNG_filter;

// Handle the PNG inflate decompression
typedef struct PNG_zTree {
	gU16 table[16];			// Table of code length counts
	gU16 trans[288];		// Code to symbol translation table
	} PNG_zTree;

typedef struct PNG_zinflate {
	gU8		data;					// The current input stream data byte
	gU8		bits;					// The number of bits left in the data byte
	gU8		flags;					// Decompression flags
	#define PNG_ZFLG_EOF			0x01	// No more input data
	#define PNG_ZFLG_FINAL			0x02	// This is the final block
	#define PNG_ZFLG_RESUME_MASK	0x0C	// The mask of bits for the resume state
	#define PNG_ZFLG_RESUME_NEW		0x00	// Process a new block
	#define PNG_ZFLG_RESUME_COPY	0x04	// Resume a byte copy from the input stream (length in tmp)
	#define PNG_ZFLG_RESUME_INFLATE	0x08	// Resume using the specified symbol (symbol in tmp[0])
	#define PNG_ZFLG_RESUME_OFFSET	0x0C	// Resume a byte offset copy from the buffer (length and offset in tmp)

	unsigned		bufpos;				// The current buffer output position
	unsigned		bufend;				// The current buffer end position (wraps)

	PNG_zTree	ltree;					// The dynamic length tree
	PNG_zTree	dtree;					// The dynamic distance tree
	gU8		tmp[288+32];			// Temporary space for decoding dynamic trees and other temporary uses
	gU8		buf[GDISP_IMAGE_PNG_Z_BUFFER_SIZE];	// The decoding buffer and sliding window
	} PNG_zinflate;

// Put all the decoding structures together.
// Note this is immediately followed by 2 scan lines of uncompressed image data for filtering (dynamic size).
typedef struct PNG_decode {
	gdispImage		*img;
	PNG_info		*pinfo;
	PNG_input		i;
	PNG_output		o;
	PNG_filter		f;
	PNG_zinflate	z;
	} PNG_decode;

/*-----------------------------------------------------------------
 * PNG input data stream functions
 *---------------------------------------------------------------*/

// Input initialization
static void PNG_iInit(PNG_decode *d) {
	if (d->pinfo->cache) {
		d->i.pbuf = d->pinfo->cache;
		d->i.buflen = d->pinfo->cachesz;
		d->i.f = 0;
	} else {
		d->i.buflen = 0;
		d->i.chunklen = 0;
		d->i.chunknext = 8;
		d->i.f = d->img->f;
	}
}

// Load the next byte of image data from the PNG file
static gBool PNG_iLoadData(PNG_decode *d) {
	gU32	sz;

	// Is there data still left in the buffer?
	if (d->i.buflen)
		return gTrue;

	// If we are cached then we have no more data
	if (!d->i.f)
		return gFalse;

	// Have we finished the current chunk?
	if (!d->i.chunklen) {
		while(1) {
			// Find a new chunk
			gfileSetPos(d->i.f, d->i.chunknext);
			if (gfileRead(d->i.f, d->i.buf, 8) != 8)
				return gFalse;

			// Calculate the chunk length and next chunk
			d->i.chunklen = gdispImageGetAlignedBE32(d->i.buf, 0);
			d->i.chunknext += d->i.chunklen + 12;

			// Process only image data chunks
			switch (gdispImageGetAlignedBE32(d->i.buf, 4)) {
			case 0x49444154:		// "IDAT" - Image Data
				if (!d->i.chunklen)
					break;
				goto gotchunk;
			case 0x49454E44:		// "IEND"	- All done
				return gFalse;
			}
		}
	}

gotchunk:

	// Try to read data some from the chunk
	sz = d->i.chunklen;
	if (sz > GDISP_IMAGE_PNG_FILE_BUFFER_SIZE)
		sz = GDISP_IMAGE_PNG_FILE_BUFFER_SIZE;
	if (gfileRead(d->i.f, d->i.buf, sz) != sz)
		return gFalse;
	d->i.chunklen -= sz;
	d->i.buflen = sz;
	d->i.pbuf = d->i.buf;
	return gTrue;
}

// Get the last loaded byte of image data from the PNG file
static gU8 PNG_iGetByte(PNG_decode *d) {
	d->i.buflen--;
	return *d->i.pbuf++;
}

/*-----------------------------------------------------------------
 * Display output and windowing functions
 *---------------------------------------------------------------*/

// Initialize the display output window
static void PNG_oInit(PNG_output *o, GDisplay *g, gCoord x, gCoord y, gCoord cx, gCoord cy, gCoord sx, gCoord sy) {
	o->g = g;
	o->x = x;
	o->y = y;
	o->cx = cx;
	o->cy = cy;
	o->sx = sx;
	o->sy = sy;
	o->ix = o->iy = 0;
	o->cnt = 0;
}

// Flush the output buffer to the display
static void PNG_oFlush(PNG_output *o) {
	switch(o->cnt) {
	case 0:		return;
	case 1:		gdispGDrawPixel(o->g, o->x+o->ix-o->sx, o->y+o->iy-o->sy, o->buf[0]); 						break;
	default:	gdispGBlitArea(o->g, o->x+o->ix-o->sx, o->y+o->iy-o->sy, o->cnt, 1, 0, 0, o->cnt, o->buf);	break;
	}
	o->ix += o->cnt;
	o->cnt = 0;
}

// Start a new image line
static gBool PNG_oStartY(PNG_output *o, gCoord y) {
	if (y < o->sy || y >= o->sy+o->cy)
		return gFalse;
	o->ix = 0;
	o->iy = y;
	return gTrue;
}

// Feed a pixel color to the display buffer
static void PNG_oColor(PNG_output *o, gColor c) {
	// Is it in the window
	if (o->ix+(gCoord)o->cnt < o->sx || o->ix+(gCoord)o->cnt >= o->sx+o->cx) {
		// No - just skip the pixel
		PNG_oFlush(o);
		o->ix++;
		return;
	}

	// Is the buffer full
	if (o->cnt >= sizeof(o->buf)/sizeof(o->buf[0]))
		PNG_oFlush(o);

	// Save the pixel
	o->buf[o->cnt++] = c;
}

#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY || GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
	// Feed a transparent pixel to the display buffer
	static void PNG_oTransparent(PNG_output *o) {
		// Flush any existing pixels
		PNG_oFlush(o);

		// Just skip the pixel
		o->ix++;
	}
#endif

/*-----------------------------------------------------------------
 * Inflate uncompress functions
 *---------------------------------------------------------------*/

// Wrap the zInflate buffer position (after increment)
#if (GDISP_IMAGE_PNG_Z_BUFFER_SIZE & ~(GDISP_IMAGE_PNG_Z_BUFFER_SIZE-1)) == GDISP_IMAGE_PNG_Z_BUFFER_SIZE
	#define WRAP_ZBUF(x)	{ x &= GDISP_IMAGE_PNG_Z_BUFFER_SIZE-1; }
#else
	#if GFX_COMPILER_WARNING_TYPE == GFX_COMPILER_WARNING_DIRECT
		#warning "PNG: GDISP_IMAGE_PNG_Z_BUFFER_SIZE is more efficient as a power of 2"
	#elif GFX_COMPILER_WARNING_TYPE == GFX_COMPILER_WARNING_MACRO
		COMPILER_WARNING("PNG: GDISP_IMAGE_PNG_Z_BUFFER_SIZE is more efficient as a power of 2")
	#endif
	#define WRAP_ZBUF(x)	{ if (x >= GDISP_IMAGE_PNG_Z_BUFFER_SIZE) x = 0; }
#endif

// Initialize the inflate decompressor
static void PNG_zInit(PNG_zinflate *z) {
	z->bits = 0;
	z->flags = 0;
	z->bufpos = z->bufend = 0;
}

// Get the inflate header (slightly customized for PNG validity testing)
static gBool PNG_zGetHeader(PNG_decode *d) {
	if (!PNG_iLoadData(d))
		return gFalse;
	d->z.tmp[0] = PNG_iGetByte(d);
	if (!PNG_iLoadData(d))
		return gFalse;
	d->z.tmp[1] = PNG_iGetByte(d);
	if (gdispImageGetAlignedBE16(d->z.tmp, 0) % 31 != 0				// Must be modulo 31, the FCHECK value is made that way
			|| (d->z.tmp[0] & 0x0F) != 8 || (d->z.tmp[0] & 0x80)	// only method 8: inflate 32k sliding window
			|| (d->z.tmp[1] & 0x20))								// no preset dictionary
		return gFalse;
	return gTrue;
}

// Get a bit from the input (treated as a LSB first stream)
static unsigned PNG_zGetBit(PNG_decode *d) {
	unsigned	bit;

	// Check for EOF
	if ((d->z.flags & PNG_ZFLG_EOF))
		return 1;

	// Check if data is empty
	if (!d->z.bits) {
		if (!PNG_iLoadData(d)) {
			d->z.flags |= PNG_ZFLG_EOF;
			return 1;
		}
		d->z.data = PNG_iGetByte(d);
		d->z.bits = 8;
	}

	// Get the next bit
	d->z.bits--;
	bit = d->z.data & 0x01;
	d->z.data >>= 1;
	return bit;
}

// Get multiple bits from the input (treated as a LSB first stream with bit order retained)
static unsigned PNG_zGetBits(PNG_decode *d, unsigned num) {
	unsigned val;
	unsigned limit;
	unsigned mask;

	val = 0;
	limit = 1 << num;

	for (mask = 1; mask < limit; mask <<= 1)
		if (PNG_zGetBit(d))
			val += mask;
	return val;
}

// Build an inflate dynamic tree using a string of byte lengths
static void PNG_zBuildTree(PNG_zTree *t, const gU8 *lengths, unsigned num) {
	unsigned		i, sum;
	gU16		offs[16];

	for (i = 0; i < 16; ++i)
		t->table[i] = 0;
	for (i = 0; i < num; ++i)
		t->table[lengths[i]]++;

	t->table[0] = 0;

	for (sum = 0, i = 0; i < 16; ++i) {
		offs[i] = sum;
		sum += t->table[i];
	}
	for (i = 0; i < num; ++i) {
		if (lengths[i])
			t->trans[offs[lengths[i]]++] = i;
	}
}

// Get an inflate decode symbol
static gU16 PNG_zGetSymbol(PNG_decode *d, PNG_zTree *t) {
	int			sum, cur;
	unsigned	len;

	sum = cur = 0;
	len = 0;
	do {
		cur <<= 1;
		cur += PNG_zGetBit(d);
		if ((d->z.flags & PNG_ZFLG_EOF))
			return 0;
		len++;

		sum += t->table[len];
		cur -= t->table[len];
	} while (cur >= 0);

	return t->trans[sum + cur];
}

// Build inflate fixed length and distance trees
static void PNG_zBuildFixedTrees(PNG_decode *d) {
	unsigned	i;

	for (i = 0; i < 16; ++i)	d->z.ltree.table[i] = 0;
	d->z.ltree.table[7] = 24;
	d->z.ltree.table[8] = 152;
	d->z.ltree.table[9] = 112;
	for (i = 0; i < 24; ++i)	d->z.ltree.trans[i] = 256 + i;
	for (i = 0; i < 144; ++i)	d->z.ltree.trans[24 + i] = i;
	for (i = 0; i < 8; ++i)		d->z.ltree.trans[24 + 144 + i] = 280 + i;
	for (i = 0; i < 112; ++i)	d->z.ltree.trans[24 + 144 + 8 + i] = 144 + i;

	for (i = 0; i < 16; ++i)	d->z.dtree.table[i] = 0;
	d->z.dtree.table[5] = 32;
	for (i = 0; i < 32; ++i)	d->z.dtree.trans[i] = i;
	for ( ; i < 288; ++i)		d->z.dtree.trans[i] = 0;
}

// Build inflate dynamic length and distance trees
static gBool PNG_zDecodeTrees(PNG_decode *d) {
	static const gU8 IndexLookup[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
	unsigned	hlit, hdist, hclen;
	unsigned	i, num;
	gU16	symbol;
	gU8		val;

	hlit	= PNG_zGetBits(d, 5) + 257;		// 257 - 286
	hdist	= PNG_zGetBits(d, 5) + 1;		// 1 - 32
	hclen	= PNG_zGetBits(d, 4) + 4;		// 4 - 19

	if ((d->z.flags & PNG_ZFLG_EOF))
		return gFalse;

	for (i = 0; i < 19; ++i)
		d->z.tmp[i] = 0;

	// Get code lengths for the code length alphabet
	for (i = 0; i < hclen; ++i)
		d->z.tmp[IndexLookup[i]] = PNG_zGetBits(d, 3);

	if ((d->z.flags & PNG_ZFLG_EOF))
		return gFalse;

	// Build the code length tree
	PNG_zBuildTree(&d->z.ltree, d->z.tmp, 19);

	// Decode code lengths
	for (num = 0; num < hlit + hdist; ) {
		symbol = PNG_zGetSymbol(d, &d->z.ltree);
		if ((d->z.flags & PNG_ZFLG_EOF))
			return gFalse;

		switch(symbol) {
		case 16:		// Copy the previous code length 3-6 times
			val = d->z.tmp[num - 1];
			for (i = PNG_zGetBits(d, 2) + 3; i; i--)
				d->z.tmp[num++] = val;
			break;
		case 17:		// Repeat code length 0 for 3-10 times
			for (i = PNG_zGetBits(d, 3) + 3; i; i--)
				d->z.tmp[num++] = 0;
			break;
		case 18:		// Repeat code length 0 for 11-138 times
			for (i = PNG_zGetBits(d, 7) + 11; i; i--)
				d->z.tmp[num++] = 0;
			break;
		default:		// symbols 0-15 are the actual code lengths
			d->z.tmp[num++] = symbol;
			break;
		}
	}

	// Build the trees
	PNG_zBuildTree(&d->z.ltree, d->z.tmp, hlit);
	PNG_zBuildTree(&d->z.dtree, d->z.tmp + hlit, hdist);
	return gTrue;
}

// Copy bytes from the input stream. Completing the copy completes the block.
static gBool PNG_zCopyInput(PNG_decode *d, unsigned length) {
	// Copy the block
	while(length--) {
		if (!PNG_iLoadData(d)) {				// EOF?
			d->z.flags |= PNG_ZFLG_EOF;
			return gFalse;
		}
		d->z.buf[d->z.bufend++] = PNG_iGetByte(d);
		WRAP_ZBUF(d->z.bufend);
		if (d->z.bufend == d->z.bufpos) {		// Buffer full?
			d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_COPY;
			((unsigned *)d->z.tmp)[0] = length;
			return gTrue;
		}
	}

	// The block is done
	d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_NEW;
	return gTrue;
}

// Copy an uncompressed inflate block into the output
static gBool PNG_zUncompressedBlock(PNG_decode *d) {
	unsigned	length;

	// This block works on byte boundaries
	d->z.bits = 0;

	// Get 4 byte header
	for (length = 0; length < 4; length++) {
		if (!PNG_iLoadData(d)) {			// EOF?
			d->z.flags |= PNG_ZFLG_EOF;
			return gFalse;
		}
		d->z.tmp[length] = PNG_iGetByte(d);
	}

	// Get length
	length = gdispImageGetAlignedLE16(d->z.tmp, 0);

	// Check length
	if ((gU16)length != (gU16)~gdispImageGetAlignedLE16(d->z.tmp, 2)) {
		d->z.flags |= PNG_ZFLG_EOF;
		return gFalse;
	}

	// Copy the block
	return PNG_zCopyInput(d, length);
}

// Inflate a compressed inflate block into the output
static gBool PNG_zInflateBlock(PNG_decode *d) {
	static const gU8	lbits[30]	= { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 6 };
	static const gU16	lbase[30]	= { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 323 };
	static const gU8	dbits[30]	= { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
	static const gU16	dbase[30]	= { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
	unsigned	length, dist, offset;
	gU16	symbol;

	while(1) {
		symbol = PNG_zGetSymbol(d, &d->z.ltree);							// EOF?
		if ((d->z.flags & PNG_ZFLG_EOF))
			goto iserror;

		// Is the block done?
		if (symbol == 256) {
			d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_NEW;
			return gTrue;
		}

		if (symbol < 256) {
			// The symbol is the data
			d->z.buf[d->z.bufend++] = (gU8)symbol;
			WRAP_ZBUF(d->z.bufend);
			if (d->z.bufend == d->z.bufpos) {								// Buffer full?
				d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_INFLATE;
				return gTrue;
			}
			continue;
		}

		// Shift the symbol down into an index
		symbol -= 257;

		if (symbol >= sizeof(lbits))										// Bad index?
			goto iserror;

		// Get more bits from length code
		length = PNG_zGetBits(d, lbits[symbol]) + lbase[symbol];
		if ((d->z.flags & PNG_ZFLG_EOF) || length >= GDISP_IMAGE_PNG_Z_BUFFER_SIZE)		// Bad length?
			goto iserror;

		// Get the distance code
		dist = PNG_zGetSymbol(d, &d->z.dtree);								// Bad distance?
		if ((d->z.flags & PNG_ZFLG_EOF) || dist >= sizeof(dbits))
			goto iserror;

		// Get more bits from distance code
		offset = PNG_zGetBits(d, dbits[dist]) + dbase[dist];
		if ((d->z.flags & PNG_ZFLG_EOF) || offset >= GDISP_IMAGE_PNG_Z_BUFFER_SIZE)		// Bad offset?
			goto iserror;

		// Work out the source buffer position allowing for wrapping
		if (offset > d->z.bufend)
			offset -= GDISP_IMAGE_PNG_Z_BUFFER_SIZE;
		offset = d->z.bufend - offset;

		// Copy the matching string
		while (length--) {
			d->z.buf[d->z.bufend++] = d->z.buf[offset++];
			WRAP_ZBUF(d->z.bufend);
			WRAP_ZBUF(offset);
			if (d->z.bufend == d->z.bufpos) {								// Buffer full?
				d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_OFFSET;
				((unsigned *)d->z.tmp)[0] = length;
				((unsigned *)d->z.tmp)[1] = offset;
				return gTrue;
			}
		}
	}

iserror:
	d->z.flags |= PNG_ZFLG_EOF;
	return gFalse;
}

// Start a new uncompressed/inflate block
static gBool PNG_zStartBlock(PNG_decode *d) {
	// Check for previous error, EOF or no more blocks
	if ((d->z.flags & (PNG_ZFLG_EOF|PNG_ZFLG_FINAL)))
		return gFalse;

	// Is this the final inflate block?
	if (PNG_zGetBit(d))
		d->z.flags |= PNG_ZFLG_FINAL;

	// Get the block type
	switch (PNG_zGetBits(d, 2)) {

	case 0:			// Decompress uncompressed block
		if (!PNG_zUncompressedBlock(d))
			return gFalse;
		break;

	case 1:			// Decompress block with fixed huffman trees
		PNG_zBuildFixedTrees(d);
		if (!PNG_zInflateBlock(d))
			return gFalse;
		break;

	case 2:			// Decompress block with dynamic huffman trees
		if (!PNG_zDecodeTrees(d))
			return gFalse;
		if (!PNG_zInflateBlock(d))
			return gFalse;
		break;

	default:		// Bad block type
		// Mark it as an error
		d->z.flags |= PNG_ZFLG_EOF;
		return gFalse;
	}
	return gTrue;
}

// Resume an offset copy
static gBool PNG_zResumeOffset(PNG_decode *d, unsigned length, unsigned offset) {
	// Copy the matching string
	while (length--) {
		d->z.buf[d->z.bufend++] = d->z.buf[offset++];
		WRAP_ZBUF(d->z.bufend);
		WRAP_ZBUF(offset);
		if (d->z.bufend == d->z.bufpos) {						// Buffer full?
			d->z.flags = (d->z.flags & ~PNG_ZFLG_RESUME_MASK) | PNG_ZFLG_RESUME_OFFSET;
			((unsigned *)d->z.tmp)[0] = length;
			((unsigned *)d->z.tmp)[1] = offset;
			return gTrue;
		}
	}
	return PNG_zInflateBlock(d);
}

// Get a fully decompressed byte from the inflate data stream
static gU8 PNG_zGetByte(PNG_decode *d) {
	gU8		data;

	// Do we have any data in the buffers
	while (d->z.bufpos == d->z.bufend) {

		// No, get some more data

		switch((d->z.flags & PNG_ZFLG_RESUME_MASK)) {
		case PNG_ZFLG_RESUME_NEW:			// Start a new inflate block
			if (!PNG_zStartBlock(d))
				return 0xFF;
			break;
		case PNG_ZFLG_RESUME_COPY:			// Resume uncompressed block copy for length bytes
			if (!PNG_zCopyInput(d, ((unsigned *)d->z.tmp)[0]))
				return 0xFF;
			break;
		case PNG_ZFLG_RESUME_INFLATE:		// Resume compressed block
			if (!PNG_zInflateBlock(d))
				return 0xFF;
			break;
		case PNG_ZFLG_RESUME_OFFSET:		// Resume compressed block using offset copy for length bytes
			if (!PNG_zResumeOffset(d, ((unsigned *)d->z.tmp)[0], ((unsigned *)d->z.tmp)[1]))
				return 0xFF;
			break;
		}

		// Check for no data being provided
		// A resume code means the buffer is completely full so the test must be skipped
		if ((d->z.flags & PNG_ZFLG_RESUME_MASK) != PNG_ZFLG_RESUME_NEW)
			break;
	}

	// Get the next data byte
	data = d->z.buf[d->z.bufpos++];
	WRAP_ZBUF(d->z.bufpos);

	return data;
}

/*-----------------------------------------------------------------
 * Scan-line filter functions
 *---------------------------------------------------------------*/

// Initialise the scan-line engine
static void PNG_fInit(PNG_filter *f, gU8 *buf, unsigned bytewidth, unsigned scanbytes) {
	f->scanbytes = scanbytes;
	f->bytewidth = bytewidth;
	f->line = buf;
	f->prev = 0;
}

// Get ready for the next scan-line
static void PNG_fNext(PNG_filter *f) {
	if (f->prev && f->line > f->prev) {
		f->line = f->prev;
		f->prev += f->scanbytes;
	} else {
		f->prev = f->line;
		f->line += f->scanbytes;
	}
}

// Predictor function for filter0 mode 4
static gU8 PNG_fCalcPath(gU16 a, gU16 b, gU16 c) {
	gU16 pa = b > c ? (b - c) : (c - b);
	gU16 pb = a > c ? (a - c) : (c - a);
	gU16 pc = a + b > c + c ? (a + b - c - c) : (c + c - a - b);

	if (pc < pa && pc < pb)
		return (gU8)c;
	if (pb < pa)
		return (gU8)b;
	return (gU8)a;
}

// Scan-line filter type 0
static gBool PNG_unfilter_type0(PNG_decode *d) {		// PNG filter method 0
	gU8		ft;
	unsigned	i;

	// Get the filter type and check for validity (eg not EOF)
	ft = PNG_zGetByte(d);
	if (ft > 0x04)
		return gFalse;

	// Uncompress the scan line
	for(i = 0; i < d->f.scanbytes; i++)
		d->f.line[i] = PNG_zGetByte(d);

	// Adjust the scan line based on the filter type
	// 0 = no adjustment
	switch(ft) {
	case 1:
		for(i = d->f.bytewidth; i < d->f.scanbytes; i++)
			d->f.line[i] += d->f.line[i - d->f.bytewidth];
		break;
	case 2:
		if (d->f.prev) {
			for(i = 0; i < d->f.scanbytes; i++)
				d->f.line[i] += d->f.prev[i];
		}
		break;
	case 3:
		if (d->f.prev) {
			for(i = 0; i < d->f.bytewidth; i++)
				d->f.line[i] += d->f.prev[i] / 2;
			for( ; i < d->f.scanbytes; i++)
				d->f.line[i] += (d->f.line[i - d->f.bytewidth] + d->f.prev[i]) / 2;
		} else {
			for(i = d->f.bytewidth; i < d->f.scanbytes; i++)
				d->f.line[i] += d->f.line[i - d->f.bytewidth] / 2;
		}
		break;
	case 4:
		if (d->f.prev) {
			for(i = 0; i < d->f.bytewidth; i++)
				d->f.line[i] += d->f.prev[i];					// PNG_fCalcPath(0, val, 0) is always val
			for( ; i < d->f.scanbytes; i++)
				d->f.line[i] += PNG_fCalcPath(d->f.line[i - d->f.bytewidth], d->f.prev[i], d->f.prev[i - d->f.bytewidth]);
		} else {
			for(i = d->f.bytewidth; i < d->f.scanbytes; i++)
				d->f.line[i] += d->f.line[i - d->f.bytewidth];	// PNG_fCalcPath(val, 0, 0) is always val
		}
		break;
	}

	return gTrue;
}

/*-----------------------------------------------------------------
 * Scan-line output and color conversion functions
 *---------------------------------------------------------------*/

#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124
	static void PNG_OutGRAY124(PNG_decode *d) {
		unsigned	i;
		PNG_info 	*pinfo;
		gU8		px;
		gU8		bits;

		pinfo = d->pinfo;
		for(i = 0; i < d->f.scanbytes; i++) {
			for(bits = 8; bits; bits -= pinfo->bitdepth) {
				px = (d->f.line[i] >> (bits - pinfo->bitdepth)) & ((1U << pinfo->bitdepth)-1);
				#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
					if ((pinfo->flags & PNG_FLG_TRANSPARENT) && (gU16)px == pinfo->trans_r) {
						#if GDISP_NEED_IMAGE_PNG_BACKGROUND
							if ((pinfo->flags & PNG_FLG_BACKGROUND)) {
								PNG_oColor(&d->o, pinfo->bg);
								continue;
							}
						#endif
						PNG_oTransparent(&d->o);
						continue;
					}
				#endif
				px = px << (8-pinfo->bitdepth);
				if (px >= 0x80) px += ((1U << (8-pinfo->bitdepth))-1);
				PNG_oColor(&d->o, LUMA2COLOR(px));
			}
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_8
	static void PNG_OutGRAY8(PNG_decode *d) {
		unsigned		i;
		gU8			px;
		#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i++) {
			px = d->f.line[i];
			#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
				if ((pinfo->flags & PNG_FLG_TRANSPARENT) && (gU16)px == pinfo->trans_r) {
					#if GDISP_NEED_IMAGE_PNG_BACKGROUND
						if ((pinfo->flags & PNG_FLG_BACKGROUND)) {
							PNG_oColor(&d->o, pinfo->bg);
							continue;
						}
					#endif
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif
			PNG_oColor(&d->o, LUMA2COLOR(px));
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_16
	static void PNG_OutGRAY16(PNG_decode *d) {
		unsigned		i;
		gU8			px;
		#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=2) {
			px = d->f.line[i];
			#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
				if ((pinfo->flags & PNG_FLG_TRANSPARENT) && gdispImageGetBE16(d->f.line, i) == pinfo->trans_r) {
					#if GDISP_NEED_IMAGE_PNG_BACKGROUND
						if ((pinfo->flags & PNG_FLG_BACKGROUND)) {
							PNG_oColor(&d->o, pinfo->bg);
							continue;
						}
					#endif
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif
			PNG_oColor(&d->o, LUMA2COLOR(px));
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_RGB_8
	static void PNG_OutRGB8(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=3) {
			#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
				if ((pinfo->flags & PNG_FLG_TRANSPARENT)
							&& (gU16)d->f.line[i+0] == pinfo->trans_r
							&& (gU16)d->f.line[i+1] == pinfo->trans_g
							&& (gU16)d->f.line[i+2] == pinfo->trans_b) {
					#if GDISP_NEED_IMAGE_PNG_BACKGROUND
						if ((pinfo->flags & PNG_FLG_BACKGROUND)) {
							PNG_oColor(&d->o, pinfo->bg);
							continue;
						}
					#endif
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif
			PNG_oColor(&d->o, RGB2COLOR(d->f.line[i+0], d->f.line[i+1], d->f.line[i+2]));
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_RGB_16
	static void PNG_OutRGB16(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=6) {
			#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
				if ((pinfo->flags & PNG_FLG_TRANSPARENT)
							&& gdispImageGetBE16(d->f.line, i+0) == pinfo->trans_r
							&& gdispImageGetBE16(d->f.line, i+2) == pinfo->trans_g
							&& gdispImageGetBE16(d->f.line, i+4) == pinfo->trans_b) {
					#if GDISP_NEED_IMAGE_PNG_BACKGROUND
						if ((pinfo->flags & PNG_FLG_BACKGROUND)) {
							PNG_oColor(&d->o, pinfo->bg);
							continue;
						}
					#endif
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif
			PNG_oColor(&d->o, RGB2COLOR(d->f.line[i+0], d->f.line[i+2], d->f.line[i+4]));
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_PALETTE_124
	static void PNG_OutPAL124(PNG_decode *d) {
		unsigned	i;
		PNG_info 	*pinfo;
		unsigned	idx;
		gU8 	bits;

		pinfo = d->pinfo;
		for(i = 0; i < d->f.scanbytes; i++) {
			for(bits = 8; bits; bits -= pinfo->bitdepth) {
				idx = (d->f.line[i] >> (bits - pinfo->bitdepth)) & ((1U << pinfo->bitdepth)-1);

				if ((gU16)idx >= pinfo->palsize) {
					PNG_oColor(&d->o, RGB2COLOR(0, 0, 0));
					continue;
				}
				idx *= 4;

				#define pix_color	RGB2COLOR(pinfo->palette[idx], pinfo->palette[idx+1], pinfo->palette[idx+2])
				#define pix_alpha	pinfo->palette[idx+3]

				#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
					#if GDISP_NEED_IMAGE_PNG_BACKGROUND
						if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
							PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
							continue;
						}
					#endif
					#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
						if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
							PNG_oTransparent(&d->o);
							continue;
						}
					#endif
				#endif

				PNG_oColor(&d->o, pix_color);

				#undef pix_color
				#undef pix_alpha
			}
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_PALETTE_8
	static void PNG_OutPAL8(PNG_decode *d) {
		unsigned	i;
		PNG_info 	*pinfo;
		unsigned	idx;

		pinfo = d->pinfo;
		for(i = 0; i < d->f.scanbytes; i++) {
			idx = (unsigned)d->f.line[i];

			if ((gU16)idx >= pinfo->palsize) {
				PNG_oColor(&d->o, RGB2COLOR(0, 0, 0));
				continue;
			}
			idx *= 4;

			#define pix_color	RGB2COLOR(pinfo->palette[idx], pinfo->palette[idx+1], pinfo->palette[idx+2])
			#define pix_alpha	pinfo->palette[idx+3]

			#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
				#if GDISP_NEED_IMAGE_PNG_BACKGROUND
					if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
						PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
						continue;
					}
				#endif
				#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
					if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
						PNG_oTransparent(&d->o);
						continue;
					}
				#endif
			#endif

			PNG_oColor(&d->o, pix_color);

			#undef pix_color
			#undef pix_alpha
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_GRAYALPHA_8
	static void PNG_OutGRAYA8(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_BACKGROUND
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=2) {
			#define pix_color	LUMA2COLOR(d->f.line[i])
			#define pix_alpha	d->f.line[i+1]

			#if GDISP_NEED_IMAGE_PNG_BACKGROUND
				if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
					PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
					continue;
				}
			#endif
			#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
				if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif

			PNG_oColor(&d->o, pix_color);

			#undef pix_color
			#undef pix_alpha
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_GRAYALPHA_16
	static void PNG_OutGRAYA16(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_BACKGROUND
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=4) {
			#define pix_color	LUMA2COLOR(d->f.line[i])
			#define pix_alpha	d->f.line[i+2]

			#if GDISP_NEED_IMAGE_PNG_BACKGROUND
				if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
					PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
					continue;
				}
			#endif
			#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
				if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif

			PNG_oColor(&d->o, pix_color);

			#undef pix_color
			#undef pix_alpha
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_RGBALPHA_8
	static void PNG_OutRGBA8(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_BACKGROUND
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=4) {
			#define pix_color	RGB2COLOR(d->f.line[i+0], d->f.line[i+1], d->f.line[i+2])
			#define pix_alpha	d->f.line[i+3]

			#if GDISP_NEED_IMAGE_PNG_BACKGROUND
				if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
					PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
					continue;
				}
			#endif
			#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
				if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif

			PNG_oColor(&d->o, pix_color);

			#undef pix_color
			#undef pix_alpha
		}
	}
#endif
#if GDISP_NEED_IMAGE_PNG_RGBALPHA_16
	static void PNG_OutRGBA16(PNG_decode *d) {
		unsigned		i;
		#if GDISP_NEED_IMAGE_PNG_BACKGROUND
			PNG_info 	*pinfo = d->pinfo;
		#endif

		for(i = 0; i < d->f.scanbytes; i+=8) {
			#define pix_color	RGB2COLOR(d->f.line[i+0], d->f.line[i+2], d->f.line[i+4])
			#define pix_alpha	d->f.line[i+6]

			#if GDISP_NEED_IMAGE_PNG_BACKGROUND
				if (pix_alpha != 255 && (pinfo->flags & PNG_FLG_BACKGROUND)) {
					PNG_oColor(&d->o, gdispBlendColor(pix_color, pinfo->bg, pix_alpha));
					continue;
				}
			#endif
			#if GDISP_NEED_IMAGE_PNG_ALPHACLIFF > 0
				if (pix_alpha < GDISP_NEED_IMAGE_PNG_ALPHACLIFF) {
					PNG_oTransparent(&d->o);
					continue;
				}
			#endif

			PNG_oColor(&d->o, pix_color);

			#undef pix_color
			#undef pix_alpha
		}
	}
#endif

/*-----------------------------------------------------------------
 * Public PNG functions
 *---------------------------------------------------------------*/

void gdispImageClose_PNG(gdispImage *img) {
	PNG_info *pinfo;

	pinfo = (PNG_info *)img->priv;
	if (pinfo) {
		if (pinfo->palette)
			gdispImageFree(img, (void *)pinfo->palette, pinfo->palsize*4);
		if (pinfo->cache)
			gdispImageFree(img, (void *)pinfo->cache, pinfo->cachesz);
		gdispImageFree(img, (void *)pinfo, sizeof(PNG_info));
		img->priv = 0;
	}
}

gdispImageError gdispImageOpen_PNG(gdispImage *img) {
	PNG_info	*pinfo;
	gU32	pos;
	gU32	len;
	gU8		buf[13];

	/* Read the file identifier */
	if (gfileRead(img->f, buf, 8) != 8)
		return GDISP_IMAGE_ERR_BADFORMAT;		// It can't be us

	// Check the PNG signature
	if(buf[0] != 137 || buf[1] != 80 || buf[2] != 78 || buf[3] != 71 || buf[4] != 13 || buf[5] != 10 || buf[6] != 26 || buf[7] != 10)
		return GDISP_IMAGE_ERR_BADFORMAT;		// It can't be us

	/* We know we are a PNG format image */
	img->flags = 0;
	img->priv = 0;
	img->type = GDISP_IMAGE_TYPE_PNG;

	/* Allocate our private area */
	if (!(img->priv = gdispImageAlloc(img, sizeof(PNG_info))))
		return GDISP_IMAGE_ERR_NOMEMORY;

	/* Initialise the essential bits in the private area */
	pinfo = (PNG_info *)img->priv;
	pinfo->flags = 0;
	pinfo->cache = 0;
	pinfo->trans_r = 0;
	pinfo->trans_g = 0;
	pinfo->trans_b = 0;
	#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
		pinfo->palsize = 0;
		pinfo->palette = 0;
	#endif

	// Cycle the chunks to get other information
	for(pos = 8; ; pos += len+12, gfileSetPos(img->f, pos)) {
		// Get a chunk header
		if (gfileRead(img->f, buf, 8) != 8)
			goto exit_baddata;

		// Calculate the chunk length
		len = gdispImageGetAlignedBE32(buf, 0);

		// Process the interesting information chunks
		switch (gdispImageGetAlignedBE32(buf, 4)) {
		case 0x49484452:		// "IHDR" - Header block

			// Check if the header is already done
			if ((pinfo->flags & PNG_FLG_HEADERDONE))
				goto exit_baddata;

			// Read the image parameters
			if (len < 13 || gfileRead(img->f, buf, 13) != 13)
				goto exit_baddata;

			img->width = gdispImageGetAlignedBE16(buf, 2);
			img->height = gdispImageGetAlignedBE16(buf, 6);
			pinfo->bitdepth = gdispImageGetVar(gU8, buf, 8);
			pinfo->mode = gdispImageGetVar(gU8, buf, 9);
			if (gdispImageGetVar(gU8, buf, 12)) {
				pinfo->flags |= PNG_FLG_INTERLACE;
				#if !GDISP_NEED_IMAGE_PNG_INTERLACED
					goto exit_unsupported;
				#endif
			}

			// Check width and height, filter, compression and interlacing
			if (gdispImageGetVar(gU16, buf, 0) != 0 || img->width <= 0			// width
					|| gdispImageGetVar(gU16, buf, 4) != 0  || img->height <= 0	// height
					|| gdispImageGetVar(gU8, buf, 10) != 0						// compression
					|| gdispImageGetVar(gU8, buf, 11) != 0						// filter
					|| gdispImageGetVar(gU8, buf, 12) > 1						// interlace
					)
				goto exit_unsupported;

			// Check mode, bitdepth and calculate bits per pixel
			switch(pinfo->mode) {
			#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_8 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_16
				case PNG_COLORMODE_GRAY:
					switch(pinfo->bitdepth) {
					#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124
						case 1:
						case 2:
						case 4:		pinfo->out = PNG_OutGRAY124;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_8
						case 8:		pinfo->out = PNG_OutGRAY8;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_16
						case 16:	pinfo->out = PNG_OutGRAY16;	break;
					#endif
					default:	goto exit_unsupported;
					}
					pinfo->bpp = pinfo->bitdepth;
					break;
			#endif
			#if GDISP_NEED_IMAGE_PNG_RGB_8 || GDISP_NEED_IMAGE_PNG_RGB_16
				case PNG_COLORMODE_RGB:
					switch(pinfo->bitdepth) {
					#if GDISP_NEED_IMAGE_PNG_RGB_8
						case 8:		pinfo->out = PNG_OutRGB8;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_RGB_16
						case 16:	pinfo->out = PNG_OutRGB16;	break;
					#endif
					default:	goto exit_unsupported;
					}
					pinfo->bpp = pinfo->bitdepth * 3;
					break;
			#endif
			#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
				case PNG_COLORMODE_PALETTE:
					switch(pinfo->bitdepth) {
					#if GDISP_NEED_IMAGE_PNG_PALETTE_124
						case 1:
						case 2:
						case 4:		pinfo->out = PNG_OutPAL124;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_PALETTE_8
						case 8:		pinfo->out = PNG_OutPAL8;	break;
					#endif
					default:	goto exit_unsupported;
					}
					pinfo->bpp = pinfo->bitdepth;
					break;
			#endif
			#if GDISP_NEED_IMAGE_PNG_GRAYALPHA_8 || GDISP_NEED_IMAGE_PNG_GRAYALPHA_16
				case PNG_COLORMODE_GRAYALPHA:
					switch(pinfo->bitdepth) {
					#if GDISP_NEED_IMAGE_PNG_GRAYALPHA_8
						case 8:		pinfo->out = PNG_OutGRAYA8;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_GRAYALPHA_16
						case 16:	pinfo->out = PNG_OutGRAYA16;	break;
					#endif
					default:	goto exit_unsupported;
					}
					pinfo->bpp = pinfo->bitdepth * 2;
					break;
			#endif
			#if GDISP_NEED_IMAGE_PNG_RGBALPHA_8 || GDISP_NEED_IMAGE_PNG_RGBALPHA_16
				case PNG_COLORMODE_RGBA:
					switch(pinfo->bitdepth) {
					#if GDISP_NEED_IMAGE_PNG_RGBALPHA_8
						case 8:		pinfo->out = PNG_OutRGBA8;	break;
					#endif
					#if GDISP_NEED_IMAGE_PNG_RGBALPHA_16
						case 16:	pinfo->out = PNG_OutRGBA16;	break;
					#endif
					default:	goto exit_unsupported;
					}
					pinfo->bpp = pinfo->bitdepth * 4;
					break;
			#endif
			default:
				goto exit_unsupported;
			}

			pinfo->flags |= PNG_FLG_HEADERDONE;
			break;

		case 0x49454E44:		// "IEND"	- All done
			goto exit_baddata;			// Oops we didn't get any data.

		case 0x49444154:		// "IDAT" - Image Data

			// Check if the header is already done
			if (!(pinfo->flags & PNG_FLG_HEADERDONE))
				goto exit_baddata;

			#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
				// Make sure a palette image actually has a palette
				if (pinfo->mode == PNG_COLORMODE_PALETTE && !pinfo->palette)
					goto exit_baddata;
			#endif

			// All good
			return GDISP_IMAGE_ERR_OK;

		#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
			case 0x504C5445:		// "PLTE"	- Palette

				// Check if the header is already done
				if (!(pinfo->flags & PNG_FLG_HEADERDONE))
					goto exit_baddata;

				// Skip a palette if we don't need it.
				if (pinfo->mode != PNG_COLORMODE_PALETTE)
					break;

				// Check the size and that we don't have one already
				if (len > 3 * 256 || pinfo->palette)
					goto exit_baddata;

				// Allocate the palette
				pinfo->palsize = len / 3;
				if (!(pinfo->palette = gfxAlloc(pinfo->palsize * 4)))
					goto exit_nonmem;

				// Read the palette
				{
					gU16	idx;
					gU8		*p;

					for(idx=pinfo->palsize, p=pinfo->palette; idx; p += 4, idx--) {
						if (gfileRead(img->f, p, 3) != 3)
							goto exit_baddata;
						p[3] = 255;
					}
				}

				break;
		#endif

		#if GDISP_NEED_IMAGE_PNG_TRANSPARENCY
			case 0x74524E53:		// "tRNS"	- Transparency

				// Check if the header is already done
				if (!(pinfo->flags & PNG_FLG_HEADERDONE))
					goto exit_baddata;

				// Transparency is handled differently depending on the mode
				switch(pinfo->mode) {

				#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
					case PNG_COLORMODE_PALETTE:
						if (len > pinfo->palsize)
							goto exit_baddata;

						// Adjust the palette
						{
							gU16	idx;
							gU8		*p;

							for(idx=len, p=pinfo->palette+3; idx; p += 4, idx--) {
								if (gfileRead(img->f, p, 1) != 1)
									goto exit_baddata;
							}
						}
						break;
				#endif

				#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_8 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_16
					case PNG_COLORMODE_GRAY:
						// Read the transparency color
						if (len != 2 || gfileRead(img->f, buf, 2) != 2)
							goto exit_baddata;

						pinfo->flags |= PNG_FLG_TRANSPARENT;
						pinfo->trans_r = gdispImageGetAlignedBE16(buf, 0);
						break;
				#endif
				#if GDISP_NEED_IMAGE_PNG_RGB_8 || GDISP_NEED_IMAGE_PNG_RGB_16
					case PNG_COLORMODE_RGB:
						// Read the transparency color
						if (len != 6 || gfileRead(img->f, buf, 6) != 6)
							goto exit_baddata;

						pinfo->flags |= PNG_FLG_TRANSPARENT;
						pinfo->trans_r = gdispImageGetAlignedBE16(buf, 0);
						pinfo->trans_g = gdispImageGetAlignedBE16(buf, 2);
						pinfo->trans_b = gdispImageGetAlignedBE16(buf, 4);
						break;
				#endif
				default:
					goto exit_unsupported;
				}

				break;
		#endif

		#if GDISP_NEED_IMAGE_PNG_BACKGROUND
			case 0x624B4744:		// "bKGD"	- Background

				// Check if the header is already done
				if (!(pinfo->flags & PNG_FLG_HEADERDONE))
					goto exit_baddata;

				pinfo->flags |= PNG_FLG_BACKGROUND;

				// Background data is handled differently depending on the mode
				switch(pinfo->mode) {

				#if GDISP_NEED_IMAGE_PNG_PALETTE_124 || GDISP_NEED_IMAGE_PNG_PALETTE_8
					case PNG_COLORMODE_PALETTE:
						if (!pinfo->palette || len < 1 || gfileRead(img->f, buf, 1) != 1 || (gU16)buf[0] >= pinfo->palsize)
							goto exit_baddata;
						pinfo->bg = RGB2COLOR(pinfo->palette[((unsigned)buf[0])*4+0],
												pinfo->palette[((unsigned)buf[0])*4+1],
												pinfo->palette[((unsigned)buf[0])*4+2]);
						break;
				#endif

				#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_8 || GDISP_NEED_IMAGE_PNG_GRAYSCALE_16 || GDISP_NEED_IMAGE_PNG_GRAYALPHA_8 || GDISP_NEED_IMAGE_PNG_GRAYALPHA_16
					case PNG_COLORMODE_GRAY:
					case PNG_COLORMODE_GRAYALPHA:
						if (len < 2 || gfileRead(img->f, buf, 2) != 2)
							goto exit_baddata;
						switch(pinfo->bitdepth) {
						#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_124
							case 1:
							case 2:
							case 4:
								buf[1] <<= 8-pinfo->bitdepth;
								if (buf[1] >= 0x80)
									buf[1] += ((1U << (8-pinfo->bitdepth))-1);
								pinfo->bg = LUMA2COLOR(buf[1]);
								break;
						#endif
						#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_8 || GDISP_NEED_IMAGE_PNG_GRAYALPHA_8
							case 8:
								pinfo->bg = LUMA2COLOR(buf[1]);
								break;
						#endif
						#if GDISP_NEED_IMAGE_PNG_GRAYSCALE_16 || GDISP_NEED_IMAGE_PNG_GRAYALPHA_16
							case 16:
								pinfo->bg = LUMA2COLOR(buf[0]);
								break;
						#endif
						}
						break;
				#endif
				#if GDISP_NEED_IMAGE_PNG_RGB_8 || GDISP_NEED_IMAGE_PNG_RGB_16 || GDISP_NEED_IMAGE_PNG_RGBALPHA_8 || GDISP_NEED_IMAGE_PNG_RGBALPHA_16
					case PNG_COLORMODE_RGB:
					case PNG_COLORMODE_RGBA:
						if (len < 6 || gfileRead(img->f, buf, 6) != 6)
							goto exit_baddata;

						#if GDISP_NEED_IMAGE_PNG_RGB_16 || GDISP_NEED_IMAGE_PNG_RGBALPHA_16
							if (pinfo->bitdepth == 16) {
								pinfo->bg = RGB2COLOR(buf[0], buf[2], buf[4]);
							} else
						#endif
								pinfo->bg = RGB2COLOR(buf[1], buf[3], buf[5]);
						break;
				#endif
				default:
					goto exit_unsupported;
				}
				break;
		#endif

		}
	}
exit_baddata:
	gdispImageClose_PNG(img);
	return GDISP_IMAGE_ERR_BADDATA;
exit_unsupported:
	gdispImageClose_PNG(img);
	return GDISP_IMAGE_ERR_UNSUPPORTED;
exit_nonmem:
	gdispImageClose_PNG(img);
	return GDISP_IMAGE_ERR_NOMEMORY;
}

gdispImageError gdispGImageDraw_PNG(GDisplay *g, gdispImage *img, gCoord x, gCoord y, gCoord cx, gCoord cy, gCoord sx, gCoord sy) {
	PNG_info 	*pinfo;
	PNG_decode	*d;

	// Allocate the space to decode with including space for 2 full scan lines for filtering.
	pinfo = (PNG_info *)img->priv;
	if (!(d = gdispImageAlloc(img, sizeof(PNG_decode) + (img->width * pinfo->bpp + 7) / 4)))
		return GDISP_IMAGE_ERR_NOMEMORY;


	// Initialise the decoder
	d->img = img;
	d->pinfo = pinfo;
	PNG_iInit(d);
	PNG_oInit(&d->o, g, x, y, cx, cy, sx, sy);
	PNG_zInit(&d->z);

	// Process the zlib inflate header
	if (!PNG_zGetHeader(d))
		goto exit_baddata;

	#if GDISP_NEED_IMAGE_PNG_INTERLACED
		if ((pinfo->flags & PNG_FLG_INTERLACE)) {
			// Interlaced decoding
			#error "PNG Decoder: Interlaced PNG's are not supported yet!"
		} else
	#endif
	{
		// Non-interlaced decoding
		PNG_fInit(&d->f, (gU8 *)(d+1), (pinfo->bpp + 7) / 8, (img->width * pinfo->bpp + 7) / 8);
		for(y = 0; y < sy+cy; PNG_fNext(&d->f), y++) {
			if (!PNG_unfilter_type0(d))
				goto exit_baddata;
			if (PNG_oStartY(&d->o, y)) {
				pinfo->out(d);
				PNG_oFlush(&d->o);
			}
		}
	}

	// Clean up
	gdispImageFree(img, d, sizeof(PNG_decode) + (img->width * pinfo->bpp + 7) / 4);
	return GDISP_IMAGE_ERR_OK;

exit_baddata:
	gdispImageFree(img, d, sizeof(PNG_decode) + (img->width * pinfo->bpp + 7) / 4);
	return GDISP_IMAGE_ERR_BADDATA;
}

gdispImageError gdispImageCache_PNG(gdispImage *img) {
	PNG_info 	*pinfo;
	unsigned	chunknext;
	unsigned	chunklen;
	gU8		*pcache;
	gU8		buf[8];

	// If we are already cached - just return OK
	pinfo = (PNG_info *)img->priv;
	if (pinfo->cache)
		return GDISP_IMAGE_ERR_OK;

	// Calculate the size of all the image data blocks in the image
	pinfo->cachesz = 0;
	chunknext = 8;
	while(1) {
		// Find a new chunk
		gfileSetPos(img->f, chunknext);
		if (gfileRead(img->f, buf, 8) != 8)
			return GDISP_IMAGE_ERR_BADDATA;

		// Calculate the chunk length and next chunk
		chunklen = gdispImageGetAlignedBE32(buf, 0);
		chunknext += chunklen + 12;

		// Process only image data chunks
		switch (gdispImageGetAlignedBE32(buf, 4)) {
		case 0x49444154:		// "IDAT" - Image Data
			pinfo->cachesz += chunklen;
			break;
		case 0x49454E44:		// "IEND"	- All done
			if (!pinfo->cachesz)
				return GDISP_IMAGE_ERR_BADDATA;
			goto gotsize;
		}
	}

gotsize:
	// Allocate the cache
	if (!(pcache = gdispImageAlloc(img, pinfo->cachesz)))
		return GDISP_IMAGE_ERR_NOMEMORY;

	pinfo->cache = pcache;

	// Read the image data into the cache
	chunknext = 8;
	while(1) {
		// Find a new chunk
		gfileSetPos(img->f, chunknext);
		if (gfileRead(img->f, buf, 8) != 8)
			goto baddata;

		// Calculate the chunk length and next chunk
		chunklen = gdispImageGetAlignedBE32(buf, 0);
		chunknext += chunklen + 12;

		// Process only image data chunks
		switch (gdispImageGetAlignedBE32(buf, 4)) {
		case 0x49444154:		// "IDAT" - Image Data
			if (gfileRead(img->f, pcache, chunklen) != chunklen)
				goto baddata;
			pcache += chunklen;
			break;
		case 0x49454E44:		// "IEND"	- All done
			return GDISP_IMAGE_ERR_OK;
		}
	}

baddata:
	// Oops - can't read the data. Throw away the cache.
	gdispImageFree(img, pinfo->cache, pinfo->cachesz);
	pinfo->cache = 0;
	return GDISP_IMAGE_ERR_BADDATA;
}

gDelay gdispImageNext_PNG(gdispImage *img) {
	(void) img;

	/* No more frames/pages */
	return gDelayForever;
}

#endif /* GFX_USE_GDISP && GDISP_NEED_IMAGE && GDISP_NEED_IMAGE_PNG */